fixed typo in security checks for prescription access
[openemr.git] / library / patient.inc
bloba924d16938a87fb85619491adb2cb1752e95c5be
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 /**
83  * GET ADDITIONAL INFORMATIONS 
84  * 
85  * only Dutch use
86  * 
87  * @param $pid - patient id
88  * @return array
89  */
90 function getPatientDataNL($pid) {
91     sqlQuery("SET NAMES 'utf8'");
92     $sql = "SELECT * FROM patient_data_NL WHERE pdn_id = '$pid'";
93     return sqlQuery($sql);
97 /**
98 GET FACILITIES
100 returns all facilities or just the id for the first one
101 (FACILITY FILTERING (lemonsoftware))
103 @param string - if 'first' return first facility ordered by id
104 @return array | int for 'first' case
106 function getFacilities($first = '') {
107     $r = sqlStatement("SELECT * FROM facility ORDER BY id");
108     $ret = array();
109     while ( $row = sqlFetchArray($r) ) {
110        $ret[] = $row;
113         if ( $first == 'first') {
114             return $ret[0]['id'];
115         } else {
116             return $ret;
117         }
121 GET SERVICE FACILITIES
123 returns all service_location facilities or just the id for the first one
124 (FACILITY FILTERING (CHEMED))
126 @param string - if 'first' return first facility ordered by id
127 @return array | int for 'first' case
129 function getServiceFacilities($first = '') {
130     $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
131     $ret = array();
132     while ( $row = sqlFetchArray($r) ) {
133        $ret[] = $row;
136         if ( $first == 'first') {
137             return $ret[0]['id'];
138         } else {
139             return $ret;
140         }
143 //(CHEMED) facility filter
144 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
145     $param1 = "";
146     if ($providers_only) {
147         $param1 = " AND authorized=1 AND ( info IS NULL OR info NOT LIKE '%Nocalendar%' ) ";
148     }
150     //--------------------------------
151     //(CHEMED) facility filter
152     $param2 = "";
153     if ($facility) {
154         $param2 = " AND facility_id = $facility ";
155     }
156     //--------------------------------
158     $command = "=";
159     if ($providerID == "%") {
160         $command = "like";
161     }
162     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
163         "from users where username != '' and active = 1 and id $command '" .
164         mysql_real_escape_string($providerID) . "' " . $param1 . $param2;
165     // sort by last name -- JRM June 2008
166     $query .= " ORDER BY lname, fname ";
167     $rez = sqlStatement($query);
168     for($iter=0; $row=sqlFetchArray($rez); $iter++)
169         $returnval[$iter]=$row;
171     //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
172     //accessible from $resultval['key']
174     if($iter==1) {
175         $akeys = array_keys($returnval[0]);
176         foreach($akeys as $key) {
178             $returnval[0][$key] = $returnval[0][$key];
179         }
180     }
181     return $returnval;
184 //same as above but does not reduce if only 1 row returned
185 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
186     $param1 = "";
187     if ($providers_only) {
188         $param1 = "AND authorized=1";
189     }
190     $command = "=";
191     if ($providerID == "%") {
192         $command = "like";
193     }
194     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
195         "from users where active = 1 and username != '' and id $command '" .
196         mysql_real_escape_string($providerID) . "' " . $param1;
198     $rez = sqlStatement($query);
199     for($iter=0; $row=sqlFetchArray($rez); $iter++)
200         $returnval[$iter]=$row;
202     return $returnval;
205 function getProviderName($providerID) {
206     $pi = getProviderInfo($providerID);
207     if (strlen($pi[0]["lname"]) > 0) {
208         return $pi[0]['fname'] . " " . $pi[0]['lname'];
209     }
210     return "";
213 function getProviderId($providerName) {
214     $query = "select id from users where username = '". mysql_real_escape_string($providerName)."'";
215     $rez = sqlStatement($query);
216     for($iter=0; $row=sqlFetchArray($rez); $iter++)
217         $returnval[$iter]=$row;
218     return $returnval;
221 function getEthnoRacials() {
222     $returnval = array("");
223     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
224     $rez = sqlStatement($sql);
225     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
226         if (($row["ethnoracial"] != "")) {
227             array_push($returnval, $row["ethnoracial"]);
228         }
229     }
230     return $returnval;
233 function getHistoryData($pid, $given = "*")
235     $sql = "select $given from history_data where pid='$pid' order by date DESC limit 0,1";
236     return sqlQuery($sql);
239 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
240 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
242   $sql = "select $given from insurance_data as insd " .
243     "left join insurance_companies as ic on ic.id = insd.provider " .
244     "where pid = '$pid' and type = '$type' order by date DESC limit 1";
245   return sqlQuery($sql);
248 function getInsuranceDataByDate($pid, $date, $type,
249   $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
250 { // this must take the date in the following manner: YYYY-MM-DD
251   // this function recalls the insurance value that was most recently enterred from the
252   // given date. it will call up most recent records up to and on the date given,
253   // but not records enterred after the given date
254   $sql = "select $given from insurance_data as insd " .
255     "left join insurance_companies as ic on ic.id = provider " .
256     "where pid = '$pid' and date_format(date,'%Y-%m-%d') <= '$date' and " .
257     "type='$type' order by date DESC limit 1";
258   return sqlQuery($sql);
261 function getEmployerData($pid, $given = "*")
263     $sql = "select $given from employer_data where pid='$pid' order by date DESC limit 0,1";
264     return sqlQuery($sql);
267 function _set_patient_inc_count($limit, $count, $where) {
268   // When the limit is exceeded, find out what the unlimited count would be.
269   $GLOBALS['PATIENT_INC_COUNT'] = $count;
270   if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
271     $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where");
272     $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
273   }
276 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")
278     // Allow the last name to be followed by a comma and some part of a first name.
279     // New behavior for searches:
280     // Allows comma alone followed by some part of a first name
281     // If the first letter of either name is capital, searches for name starting
282     // with given substring (the expected behavior).  If it is lower case, it
283     // it searches for the substring anywhere in the name.  This applies to either
284     // last name or first name or both.  The arbitrary limit of 100 results is set
285     // in the sql query below. --Mark Leeds
286     $lname = trim($lname);
287     $fname = '';
288      if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
289          $lname = trim($matches[1]);
290          $fname = trim($matches[2]);
291     }
292     $search_for_pieces1 = '';
293     $search_for_pieces2 = '';
294     if ($lname{0} != strtoupper($lname{0})) {$search_for_pieces1 = '%';}
295     if ($fname{0} != strtoupper($fname{0})) {$search_for_pieces2 = '%';}
297     $where = "lname LIKE '" . $search_for_pieces1 . "$lname%' " .
298         "AND fname LIKE '" . $search_for_pieces2 . "$fname%'";
299     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
300     if ($limit != "all") $sql .= " LIMIT $start, $limit";
302     $rez = sqlStatement($sql);
304     for($iter=0; $row=sqlFetchArray($rez); $iter++)
305         $returnval[$iter] = $row;
307     _set_patient_inc_count($limit, count($returnval), $where);
308     return $returnval;
311 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")
313     $where = "pubpid LIKE '$pid%'";
314     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
315     if ($limit != "all") $sql .= " limit $start, $limit";
316     $rez = sqlStatement($sql);
317     for($iter=0; $row=sqlFetchArray($rez); $iter++)
318         $returnval[$iter]=$row;
320     _set_patient_inc_count($limit, count($returnval), $where);
321     return $returnval;
324 // return a collection of Patient PIDs
325 // new arg style by JRM March 2008
326 // 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")
327 function getPatientPID($args)
329     $pid = "%";
330     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
331     $orderby = "lname ASC, fname ASC";
332     $limit="all";
333     $start="0";
335     // alter default values if defined in the passed in args
336     if (isset($args['pid'])) { $pid = $args['pid']; }
337     if (isset($args['given'])) { $given = $args['given']; }
338     if (isset($args['orderby'])) { $orderby = $args['orderby']; }
339     if (isset($args['limit'])) { $limit = $args['limit']; }
340     if (isset($args['start'])) { $start = $args['start']; }
342     $command = "=";
343     if ($pid == -1) $pid = "%";
344     elseif (empty($pid)) $pid = "NULL";
346     if (strstr($pid,"%")) $command = "like";
348     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
349     if ($limit != "all") $sql .= " limit $start, $limit";
351     $rez = sqlStatement($sql);
352     for($iter=0; $row=sqlFetchArray($rez); $iter++)
353         $returnval[$iter]=$row;
355     return $returnval;
358 function getPatientName($pid) {
359     if (empty($pid)) return "";
360     $patientData = getPatientPID(array("pid"=>$pid));
361     if (empty($patientData[0]['lname'])) return "";
362     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
363     return $patientName;
366 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
368     $DOB = fixDate($DOB, $DOB);
369     $where = "DOB like '$DOB%'";
370     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
371     if ($limit != "all") $sql .= " LIMIT $start, $limit";
373     $rez = sqlStatement($sql);
374     for($iter=0; $row=sqlFetchArray($rez); $iter++)
375         $returnval[$iter]=$row;
377     _set_patient_inc_count($limit, count($returnval), $where);
378     return $returnval;
381 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
383     $where = "ss LIKE '$ss%'";
384     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
385     if ($limit != "all") $sql .= " LIMIT $start, $limit";
387     $rez = sqlStatement($sql);
388     for($iter=0; $row=sqlFetchArray($rez); $iter++)
389         $returnval[$iter]=$row;
391     _set_patient_inc_count($limit, count($returnval), $where);
392     return $returnval;
395 //(CHEMED) Search by phone number
396 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
398     $phone = ereg_replace( "[[:punct:]]","", $phone );
399     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP '$phone'";
400     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
401     if ($limit != "all") $sql .= " LIMIT $start, $limit";
403     $rez = sqlStatement($sql);
404     for($iter=0; $row=sqlFetchArray($rez); $iter++)
405         $returnval[$iter]=$row;
407     _set_patient_inc_count($limit, count($returnval), $where);
408     return $returnval;
411 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
413     $sql="select $given from patient_data order by $orderby";
415     if ($limit != "all")
416         $sql .= " limit $start, $limit";
418     $rez = sqlStatement($sql);
419     for($iter=0; $row=sqlFetchArray($rez); $iter++)
420         $returnval[$iter]=$row;
422     return $returnval;
425 //----------------------input functions
426 function newPatientData(    $db_id="",
427                 $title = "",
428                 $fname = "",
429                 $lname = "",
430                 $mname = "",
431                 $sex = "",
432                 $DOB = "",
433                 $street = "",
434                 // DBC dutch use
435                 $nstreet = "",
436                 $nnr = "",
437                 $nadd = "",
438                 // EOS DBC
439                 $postal_code = "",
440                 $city = "",
441                 $state = "",
442                 $country_code = "",
443                 $ss = "",
444                 $occupation = "",
445                 $phone_home = "",
446                 $phone_biz = "",
447                 $phone_contact = "",
448                 $status = "",
449                 $contact_relationship = "",
450                 $referrer = "",
451                 $referrerID = "",
452                 $email = "",
453                 $language = "",
454                 $ethnoracial = "",
455                 $interpretter = "",
456                 $migrantseasonal = "",
457                 $family_size = "",
458                 $monthly_income = "",
459                 $homeless = "",
460                 $financial_review = "",
461                 $pubpid = "",
462                 $pid = "MAX(pid)+1",
463                 $providerID = "",
464                 $genericname1 = "",
465                 $genericval1 = "",
466                 $genericname2 = "",
467                 $genericval2 = "",
468                 $phone_cell = "",
469                 $hipaa_mail = "",
470                 $hipaa_voice = "",
471                 $squad = 0,
472                 $pharmacy_id = 0,
473                 $drivers_license = "",
474                 $hipaa_notice = "",
475                 $hipaa_message = "",
476                 $regdate = "",
477                 // dutch specific
478                 $prefixlast = "",
479                 $prefixlastpartner = "",
480                 $lastpartner = "",
481                 $initials = "",
482                 $provider_data = array(),
483                 $referer_data = array()
484                 // DBC Dutch System
486             )
488     $DOB = fixDate($DOB);
489     $regdate = fixDate($regdate);
491     $fitness = 0;
492     $referral_source = '';
493     if ($pid) {
494         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
495         // Check for brain damage:
496         if ($db_id != $rez['id']) {
497             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
498               $rez['id'] . "' to '$db_id' for pid '$pid'";
499             die($errmsg);
500         }
501         $fitness = $rez['fitness'];
502         $referral_source = $rez['referral_source'];
503     }
505     // Get the default price level.
506     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
507       "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
508     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
510     $query = ("replace into patient_data set
511         id='$db_id',
512         title='$title',
513         fname='$fname',
514         lname='$lname',
515         mname='$mname',
516         sex='$sex',
517         DOB='$DOB',
518         street='$street',
519         postal_code='$postal_code',
520         city='$city',
521         state='$state',
522         country_code='$country_code',
523         drivers_license='$drivers_license',
524         ss='$ss',
525         occupation='$occupation',
526         phone_home='$phone_home',
527         phone_biz='$phone_biz',
528         phone_contact='$phone_contact',
529         status='$status',
530         contact_relationship='$contact_relationship',
531         referrer='$referrer',
532         referrerID='$referrerID',
533         email='$email',
534         language='$language',
535         ethnoracial='$ethnoracial',
536         interpretter='$interpretter',
537         migrantseasonal='$migrantseasonal',
538         family_size='$family_size',
539         monthly_income='$monthly_income',
540         homeless='$homeless',
541         financial_review='$financial_review',
542         pubpid='$pubpid',
543         pid = $pid,
544         providerID = '$providerID',
545         genericname1 = '$genericname1',
546         genericval1 = '$genericval1',
547         genericname2 = '$genericname2',
548         genericval2 = '$genericval2',
549         phone_cell = '$phone_cell',
550         pharmacy_id = '$pharmacy_id',
551         hipaa_mail = '$hipaa_mail',
552         hipaa_voice = '$hipaa_voice',
553         hipaa_notice = '$hipaa_notice',
554         hipaa_message = '$hipaa_message',
555         squad = '$squad',
556         fitness='$fitness',
557         referral_source='$referral_source',
558         regdate='$regdate',
559         pricelevel='$pricelevel',
560         date=NOW()");
562     $id = sqlInsert($query);
564     // DBC 
565     if ( !$db_id ) {
566       // find the last inserted id for new patient case
567       $db_id = empty($GLOBALS['dutchpc']) ? mysql_insert_id() : dsql_lastid();
568     }
569     // EOS DBC
571     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
573          // dutch use
574         if ( $GLOBALS['dutchpc'] ) {
575                 $init = strtoupper(preg_replace('/[\s\.\-_0-9]/','',$initials));
576                 
577             $querynl = ("REPLACE INTO patient_data_NL SET
578                     pdn_id = '$db_id',
579                     pdn_pxlast = '$prefixlast',
580                     pdn_pxlastpar = '$prefixlastpartner',
581                     pdn_lastpar = '$lastpartner',
582                     pdn_street = '$nstreet',
583                     pdn_number = '$nnr',
584                     pdn_addition = '$nadd',
585                     pdn_initials = '$init'
586             ");
588             if ( $db_id ) $idnl = sqlInsert($querynl); // only if exists
589         }
590         // EOS dutch use
593        // DBC Dutch System
594         // provider first
595         if ( $GLOBALS['dutchpc'] && $db_id && $provider_data && $referer_data) {
596            $querypr = ("INSERT INTO cl_providers(pro_pid, pro_company, pro_initials, pro_prefix, pro_lname,
597                    pro_street, pro_number, pro_addition, pro_city, pro_zipcode,  pro_phone, pro_fax, pro_email, pro_referer ) 
598                    VALUES ($db_id, '{$provider_data['pro_company']}', '{$provider_data['pro_initials']}',
599                   '{$provider_data['pro_prefix']}', '{$provider_data['pro_lname']}',  
600                   '{$provider_data['pro_street']}', '{$provider_data['pro_number']}', '{$provider_data['pro_addition']}', 
601                   '{$provider_data['pro_city']}',  '{$provider_data['pro_zipcode']}',
602                   '{$provider_data['pro_phone']}', '{$provider_data['pro_fax']}',  '{$provider_data['pro_email']}', 
603                   '{$provider_data['pro_referer']}') 
604                   ON DUPLICATE KEY UPDATE  pro_referer = '{$provider_data['pro_referer']}',
605                   pro_company = '{$provider_data['pro_company']}', pro_initials = '{$provider_data['pro_initials']}',
606                   pro_prefix = '{$provider_data['pro_prefix']}',
607                   pro_lname = '{$provider_data['pro_lname']}', pro_street = '{$provider_data['pro_street']}',
608                   pro_number = '{$provider_data['pro_number']}', pro_addition = '{$provider_data['pro_addition']}',
609                   pro_city = '{$provider_data['pro_city']}', pro_zipcode = '{$provider_data['pro_zipcode']}',
610                   pro_phone = '{$provider_data['pro_phone']}', pro_fax = '{$provider_data['pro_fax']}',
611                   pro_email = '{$provider_data['pro_email']}'
612             ");
613            $idpr = sqlInsert($querypr);
615         // referer if it's the case
616         if ( $referer_data['ref_code'] ) {
617            $queryre = ("INSERT INTO cl_referers(ref_pid, ref_code, ref_company, ref_initials, ref_prefix,
618                    ref_lname, ref_street, ref_number, ref_addition, ref_city, ref_zipcode,  ref_phone, ref_fax,
619                    ref_email) 
620                    VALUES ($db_id, {$referer_data['ref_code']}, '{$referer_data['ref_company']}', 
621                    '{$referer_data['ref_initials']}', '{$referer_data['ref_prefix']}',
622                    '{$referer_data['ref_lname']}', '{$referer_data['ref_street']}', '{$referer_data['ref_number']}', 
623                    '{$referer_data['ref_addition']}', '{$referer_data['ref_city']}', '{$referer_data['ref_zipcode']}',
624                   '{$referer_data['ref_phone']}', '{$referer_data['ref_fax']}',  '{$referer_data['ref_email']}')
625                   ON DUPLICATE KEY UPDATE ref_code = {$referer_data['ref_code']},
626                   ref_company = '{$referer_data['ref_company']}', ref_initials = '{$referer_data['ref_initials']}',
627                   ref_prefix = '{$referer_data['ref_prefix']}',
628                   ref_lname = '{$referer_data['ref_lname']}', ref_street = '{$referer_data['ref_street']}',
629                   ref_number = '{$referer_data['ref_number']}', ref_addition = '{$referer_data['ref_addition']}',
630                   ref_city = '{$referer_data['ref_city']}', ref_zipcode = '{$referer_data['ref_zipcode']}',
631                   ref_phone = '{$referer_data['ref_phone']}', ref_fax = '{$referer_data['ref_fax']}',
632                   ref_email = '{$referer_data['ref_email']}'
633             ");
634            $idre = sqlInsert($queryre);
635         } 
636         } // if globals
637         // EOS DBC
639     sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
640                 $phone_biz,$phone_cell,$email,$pid);
642     return $foo['pid'];
645 // Supported input date formats are:
646 //   mm/dd/yyyy
647 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
648 //   yyyy/mm/dd
649 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
651 function fixDate($date, $default="0000-00-00") {
652     $fixed_date = $default;
653     $date = trim($date);
654     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
655         $dmy = preg_split("'[/.-]'", $date);
656         if ($dmy[0] > 99) {
657             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
658         } else {
659             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
660               if ($dmy[2] < 1000) $dmy[2] += 1900;
661               if ($dmy[2] < 1910) $dmy[2] += 100;
662             }
663             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
664         }
665     }
667     return $fixed_date;
670 function updatePatientData($pid,$new)
672   /*******************************************************************
673     $real = getPatientData($pid);
674     $new['DOB'] = fixDate($new['DOB']);
675     while(list($key, $value) = each ($new))
676         $real[$key] = $value;
677     $real['date'] = "'+NOW()+'";
678     $real['id'] = "";
679     $sql = "insert into patient_data set ";
680     while(list($key, $value) = each($real))
681         $sql .= $key." = '$value', ";
682     $sql = substr($sql, 0, -2);
683     return sqlInsert($sql);
684   *******************************************************************/
686   // The above was broken, though seems intent to insert a new patient_data
687   // row for each update.  A good idea, but nothing is doing that yet so
688   // the code below does not yet attempt it.
690   $new['DOB'] = fixDate($new['DOB']);
691   $db_id = $new['id'];
693   $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
694   // Check for brain damage:
695   if ($pid != $rez['pid']) {
696     $errmsg = "Internal error: Attempt to change patient data with pid = '" .
697       $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
698     die($errmsg);
699   }
700   $sql = "UPDATE patient_data SET date = NOW()";
701   foreach ($new as $key => $value) {
702     $sql .= ", $key = '$value'";
703   }
704   $sql .= " WHERE id = '$db_id'";
705   sqlStatement($sql);
707   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
708   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
709     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
710     $rez['phone_cell'],$rez['email'],$rez['pid']);
712   return $db_id;
715 function newEmployerData(    $pid,
716                 $name = "",
717                 $street = "",
718                 $postal_code = "",
719                 $city = "",
720                 $state = "",
721                 $country = ""
722             )
724     return sqlInsert("insert into employer_data set
725         name='$name',
726         street='$street',
727         postal_code='$postal_code',
728         city='$city',
729         state='$state',
730         country='$country',
731         pid='$pid',
732         date=NOW()
733         ");
736 function updateEmployerData($pid, $new)
738   $old = getEmployerData($pid);
739   $set = '';
740   $modified = false;
741   foreach (array('name','street','city','state','postal_code','country') as $key) {
742     $value = empty($old[$key]) ? '' : addslashes($old[$key]);
743     if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
744       $value = $new[$key];
745       $modified = true;
746     }
747     $set .= "$key = '$value', ";
748   }
749   if ($modified) {
750     $set .= "pid = '$pid', date = NOW()";
751     return sqlInsert("INSERT INTO employer_data SET $set");
752   }
753   return $old['id'];
756 // This updates or adds the given insurance data info, while retaining any
757 // previously added insurance_data rows that should be preserved.
758 // This does not directly support the maintenance of non-current insurance.
760 function newInsuranceData(
761   $pid,
762   $type = "",
763   $provider = "",
764   $policy_number = "",
765   $group_number = "",
766   $plan_name = "",
767   $subscriber_lname = "",
768   $subscriber_mname = "",
769   $subscriber_fname = "",
770   $subscriber_relationship = "",
771   $subscriber_ss = "",
772   $subscriber_DOB = "",
773   $subscriber_street = "",
774   $subscriber_postal_code = "",
775   $subscriber_city = "",
776   $subscriber_state = "",
777   $subscriber_country = "",
778   $subscriber_phone = "",
779   $subscriber_employer = "",
780   $subscriber_employer_street = "",
781   $subscriber_employer_city = "",
782   $subscriber_employer_postal_code = "",
783   $subscriber_employer_state = "",
784   $subscriber_employer_country = "",
785   $copay = "",
786   $subscriber_sex = "",
787   $effective_date = "0000-00-00",
788   $accept_assignment = "TRUE")
790   if (strlen($type) <= 0) return FALSE;
792   // If a bad date was passed, err on the side of caution.
793   $effective_date = fixDate($effective_date, date('Y-m-d'));
795   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
796     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
797   $idrow = sqlFetchArray($idres);
799   // Replace the most recent entry in any of the following cases:
800   // * Its effective date is >= this effective date.
801   // * It is the first entry and it has no (insurance) provider.
802   // * There is no encounter that is earlier than the new effective date but
803   //   on or after the old effective date.
804   // Otherwise insert a new entry.
806   $replace = false;
807   if ($idrow) {
808     if (strcmp($idrow['date'], $effective_date) > 0) {
809       $replace = true;
810     }
811     else {
812       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
813         $replace = true;
814       }
815       else {
816         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
817           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
818           "date >= '" . $idrow['date'] . " 00:00:00'");
819         if ($ferow['count'] == 0) $replace = true;
820       }
821     }
822   }
824   if ($replace) {
826     // TBD: This is a bit dangerous in that a typo in entering the effective
827     // date can wipe out previous insurance history.  So we want some data
828     // entry validation somewhere.
829     sqlStatement("DELETE FROM insurance_data WHERE " .
830       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
831       "id != " . $idrow['id']);
833     $data = array();
834     $data['type'] = $type;
835     $data['provider'] = $provider;
836     $data['policy_number'] = $policy_number;
837     $data['group_number'] = $group_number;
838     $data['plan_name'] = $plan_name;
839     $data['subscriber_lname'] = $subscriber_lname;
840     $data['subscriber_mname'] = $subscriber_mname;
841     $data['subscriber_fname'] = $subscriber_fname;
842     $data['subscriber_relationship'] = $subscriber_relationship;
843     $data['subscriber_ss'] = $subscriber_ss;
844     $data['subscriber_DOB'] = $subscriber_DOB;
845     $data['subscriber_street'] = $subscriber_street;
846     $data['subscriber_postal_code'] = $subscriber_postal_code;
847     $data['subscriber_city'] = $subscriber_city;
848     $data['subscriber_state'] = $subscriber_state;
849     $data['subscriber_country'] = $subscriber_country;
850     $data['subscriber_phone'] = $subscriber_phone;
851     $data['subscriber_employer'] = $subscriber_employer;
852     $data['subscriber_employer_city'] = $subscriber_employer_city;
853     $data['subscriber_employer_street'] = $subscriber_employer_street;
854     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
855     $data['subscriber_employer_state'] = $subscriber_employer_state;
856     $data['subscriber_employer_country'] = $subscriber_employer_country;
857     $data['copay'] = $copay;
858     $data['subscriber_sex'] = $subscriber_sex;
859     $data['pid'] = $pid;
860     $data['date'] = $effective_date;
861     $data['accept_assignment'] = $accept_assignment;
862     updateInsuranceData($idrow['id'], $data);
863     return $idrow['id'];
864   }
865   else {
866     return sqlInsert("INSERT INTO insurance_data SET
867       type = '$type',
868       provider = '$provider',
869       policy_number = '$policy_number',
870       group_number = '$group_number',
871       plan_name = '$plan_name',
872       subscriber_lname = '$subscriber_lname',
873       subscriber_mname = '$subscriber_mname',
874       subscriber_fname = '$subscriber_fname',
875       subscriber_relationship = '$subscriber_relationship',
876       subscriber_ss = '$subscriber_ss',
877       subscriber_DOB = '$subscriber_DOB',
878       subscriber_street = '$subscriber_street',
879       subscriber_postal_code = '$subscriber_postal_code',
880       subscriber_city = '$subscriber_city',
881       subscriber_state = '$subscriber_state',
882       subscriber_country = '$subscriber_country',
883       subscriber_phone = '$subscriber_phone',
884       subscriber_employer = '$subscriber_employer',
885       subscriber_employer_city = '$subscriber_employer_city',
886       subscriber_employer_street = '$subscriber_employer_street',
887       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
888       subscriber_employer_state = '$subscriber_employer_state',
889       subscriber_employer_country = '$subscriber_employer_country',
890       copay = '$copay',
891       subscriber_sex = '$subscriber_sex',
892       pid = '$pid',
893       date = '$effective_date',
894       accept_assignment = '$accept_assignment'
895     ");
896   }
899 // This is used internally only.
900 function updateInsuranceData($id, $new)
902   $fields = sqlListFields("insurance_data");
903   $use = array();
905   while(list($key, $value) = each ($new)) {
906     if (in_array($key, $fields)) {
907       $use[$key] = $value;
908     }
909   }
911   $sql = "UPDATE insurance_data SET ";
912   while(list($key, $value) = each($use))
913     $sql .= $key . " = '$value', ";
914   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
916   sqlStatement($sql);
919 function newHistoryData($pid, $new=false) {
920   $sql = "insert into history_data set pid = '$pid', date = NOW()";
921   if ($new) {
922     while(list($key, $value) = each($new)) {
923       if (!get_magic_quotes_gpc()) $value = addslashes($value);
924       $sql .= ", $key = '$value'";
925     }
926   }
927   return sqlInsert($sql);
930 function updateHistoryData($pid,$new)
932         $real = getHistoryData($pid);
933         while(list($key, $value) = each ($new))
934                 $real[$key] = $value;
935         $real['date'] = "'+NOW()+'";
936         $real['id'] = "";
938         $sql = "insert into history_data set ";
939         while(list($key, $value) = each($real))
940                 $sql .= $key." = '$value', ";
941         $sql = substr($sql, 0, -2);
944         return sqlInsert($sql);
947 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
948                 $phone_biz,$phone_cell,$email,$pid="")
950     if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
951     if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
953     $db = $GLOBALS['adodb']['db'];
954     $customer_info = array();
956     $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
957     $result = $db->Execute($sql);
958     if ($result && !$result->EOF) {
959         $customer_info['foreign_update'] = true;
960         $customer_info['foreign_id'] = $result->fields['foreign_id'];
961         $customer_info['foreign_table'] = $result->fields['foreign_table'];
962     }
964     ///xml rpc code to connect to accounting package and add user to it
965     $customer_info['firstname'] = $fname;
966     $customer_info['lastname'] = $lname;
967     $customer_info['address'] = $street;
968     $customer_info['suburb'] = $city;
969     $customer_info['state'] = $state;
970     $customer_info['postcode'] = $postal_code;
972     //ezybiz wants state as a code rather than abbreviation
973     $customer_info['geo_zone_id'] = "";
974     $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
975     $db = $GLOBALS['adodb']['db'];
976     $result = $db->Execute($sql);
977     if ($result && !$result->EOF) {
978         $customer_info['geo_zone_id'] = $result->fields['zone_id'];
979     }
981     //ezybiz wants country as a code rather than abbreviation
982     $customer_info['geo_country_id'] = "";
983     $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
984     $db = $GLOBALS['adodb']['db'];
985     $result = $db->Execute($sql);
986     if ($result && !$result->EOF) {
987         $customer_info['geo_country_id'] = $result->fields['countries_id'];
988     }
990     $customer_info['phone1'] = $phone_home;
991     $customer_info['phone1comment'] = "Home Phone";
992     $customer_info['phone2'] = $phone_biz;
993     $customer_info['phone2comment'] = "Business Phone";
994     $customer_info['phone3'] = $phone_cell;
995     $customer_info['phone3comment'] = "Cell Phone";
996     $customer_info['email'] = $email;
997     $customer_info['customernumber'] = $pid;
999     $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1000     $ws = new WSWrapper($function);
1002     // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1003     if (is_numeric($ws->value)) {
1004         $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1005         $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1006     }
1009 // Returns Date of Birth given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1010 function getPatientAge($dobYMD)
1012     $tdyYMD=date("Ymd");
1013     $yearDiff = substr($tdyYMD,0,4) - substr($dobYMD,0,4);
1014     $ageInMonths = ((substr($tdyYMD,0,4)*12)+substr($tdyYMD,4,2)) -
1015                    ((substr($dobYMD,0,4)*12)+substr($dobYMD,4,2));
1016     $dayDiff = substr($tdyYMD,6,2) - substr($dobYMD,6,2);
1017     if ( $dayDiff < 0 ) {
1018         $ageInMonths -= 1;
1019     }
1020     if ( $ageInMonths > 24 ) {
1021         $age = intval($ageInMonths/12);
1022     }
1023     else  {
1024         $age = "$ageInMonths month";
1025     }
1026     return $age;
1029 function dateToDB ($date)
1031     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1032     return $date;
1036 // ----------------------------------------------------------------------------
1038  * DROPDOWN FOR COUNTRIES
1039  * 
1040  * build a dropdown with all countries from geo_country_reference
1041  * 
1042  * @param int $selected - id for selected record
1043  * @param string $name - the name/id for select form
1044  * @return void - just echo the html encoded string
1045  */
1046 function dropdown_countries($selected = 0, $name = 'country_code') {
1047     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1049     $string = "<select name='$name' id='$name'>";
1050     while ( $row = sqlFetchArray($r) ) {
1051         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1052         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1053     }
1055     $string .= '</select>';
1056     echo $string;
1060 // ----------------------------------------------------------------------------
1062  * DROPDOWN FOR YES/NO
1063  * 
1064  * build a dropdown with two options (yes - 1, no - 0)
1065  * 
1066  * @param int $selected - id for selected record
1067  * @param string $name - the name/id for select form
1068  * @return void - just echo the html encoded string 
1069  */
1070 function dropdown_yesno($selected = 0, $name = 'yesno') {
1071     $string = "<select name='$name' id='$name'>";
1073     $selected = (int)$selected;
1074     if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1075     else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1077     $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1078     $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1079     $string .= '</select>';
1081     echo $string;
1084 // ----------------------------------------------------------------------------
1086  * DROPDOWN FOR MALE/FEMALE options
1087  * 
1088  * build a dropdown with three options (unselected/male/female)
1089  * 
1090  * @param int $selected - id for selected record
1091  * @param string $name - the name/id for select form
1092  * @return void - just echo the html encoded string
1093  */
1094 function dropdown_sex($selected = 0, $name = 'sex') {
1095     $string = "<select name='$name' id='$name'>";
1097     if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1098     else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1099     else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1101     $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1102     $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1103     $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1104     $string .= '</select>';
1106     echo $string;
1109 // ----------------------------------------------------------------------------
1111  * DROPDOWN FOR MARITAL STATUS
1112  * 
1113  * build a dropdown with marital status
1114  * 
1115  * @param int $selected - id for selected record
1116  * @param string $name - the name/id for select form
1117  * @return void - just echo the html encoded string
1118  */
1119 function dropdown_marital($selected = 0, $name = 'status') {
1120     $string = "<select name='$name' id='$name'>";
1122     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1124     foreach ( $statii as $st ) {
1125         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1126         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1127     }
1129     $string .= '</select>';
1131     echo $string;
1134 // ----------------------------------------------------------------------------
1136  * DROPDOWN FOR PROVIDERS
1137  * 
1138  * build a dropdown with all providers
1139  * 
1140  * @param int $selected - id for selected record
1141  * @param string $name - the name/id for select form
1142  * @return void - just echo the html encoded string
1143  */
1144 function dropdown_providers($selected = 0, $name = 'status') {
1145     $provideri = getProviderInfo();
1147     $string = "<select name='$name' id='$name'>";
1148     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1149     foreach ( $provideri as $s ) {
1150         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1151         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1152     }
1154     $string .= '</select>';
1156     echo $string;
1159 // ----------------------------------------------------------------------------
1161  * DROPDOWN FOR INSURANCE COMPANIES
1162  * 
1163  * build a dropdown with all insurers
1164  * 
1165  * @param int $selected - id for selected record
1166  * @param string $name - the name/id for select form
1167  * @return void - just echo the html encoded string
1168  */
1169 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1170     $insurancei = getInsuranceProviders();
1172     $string = "<select name='$name' id='$name'>";
1173     $string .= '<option value="0">Onbekend</option>';
1174     foreach ( $insurancei as $iid => $iname ) {
1175         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1176         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1177     }
1179     $string .= '</select>';
1181     echo $string;
1185 // ----------------------------------------------------------------------------
1187  * COUNTRY CODE
1188  * 
1189  * return the name or the country code, function of arguments
1190  * 
1191  * @param int $country_code
1192  * @param string $country_name
1193  * @return string | int - name or code
1194  */
1195 function country_code($country_code = 0, $country_name = '') {
1196     $strint = '';
1197     if ( $country_code ) {
1198         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1199     } else {
1200         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1201     }
1203     $db = $GLOBALS['adodb']['db'];
1204     $result = $db->Execute($sql);
1205     if ($result && !$result->EOF) {
1206         $strint = $result->fields['res'];
1207     }
1209     return $strint;
1212 // ----------------------------------------------------------------------------
1214  * GET INSURANCE DATA
1215  * (Dutch usage)
1216  * 
1217  * return the insurer(s) and some patient
1218  * 
1219  * @param int $pid - patient id
1220  * @param int $current 1-current 0-all insurers
1221  * @return array
1222  */
1223 function get_insurers_nl($pid = 0, $current = 1) {
1224     if ( !$pid ) return FALSE;
1226     $join = 'insurance_companies ic ON ic.id = pi.pin_provider';
1227     $r = dsql_select('*', 'patient_insurers_NL pi', array('pin_pid' => $pid), 'pin_date DESC', $join);
1229     while ( $row = mysql_fetch_array($r) ) {
1230         $rez[] = $row;
1231     } // while
1233     return ( $current ? $rez[0] : $rez );
1237 // ----------------------------------------------------------------------------
1239  * SET INSURANCE DATA
1240  * (Dutch usage)
1241  * 
1242  * set the insurer for a patient
1243  * 
1244  * @param int $pid - patient id
1245  * @param int $insid - insurer id
1246  * @return void
1247  */
1248 function set_insurer_nl($pid = 0, $insid = 0, $date = '', $policy = '') {
1249     if ( !$pid || !$insid || ($date == '0000-00-00') ) return FALSE;
1251     $fields = array('pin_pid', 'pin_provider', 'pin_date', 'pin_policy');
1252     $values = array($pid, $insid, $date, $policy);
1253     dsql_insert('patient_insurers_NL', $fields, $values);
1256 // ----------------------------------------------------------------------------
1258  * FIND THE INSURERS STATUS FOR A PATIENT
1259  * (Dutch usage)
1260  * 
1261  * return the answer for the question: is this the first insurer or not?
1262  * 
1263  * @param int $pid - patient id
1264  * @return int - the number of insurer records ( 0 - no insurer; >0 some insurers)
1265  */
1266 function total_insurers($pid = 0) {
1267     if ( !$pid ) return FALSE;
1269     $r = dsql_select('COUNT(*) AS c', 'patient_insurers_NL', array('pin_pid' => $pid));
1270     $row = mysql_fetch_array($r);
1272     return $row['c'];
1275 function DBToDate ($date)
1277     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1278     return $date;
1281 function get_patient_balance($pid) {
1282   if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1283     $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1284       "pid = '$pid' AND activity = 1");
1285     $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1286       "pid = '$pid'");
1287     $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1288       "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1289       "pid = '$pid'");
1290     return sprintf('%01.2f', $brow['amount'] + $srow['amount']
1291       - $drow['payments'] - $drow['adjustments']);
1292   }
1293   else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1294     // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1295     $conn = $GLOBALS['adodb']['db'];
1296     $customer_info['id'] = 0;
1297     $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1298       "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1299       "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1300       "im.foreign_table = 'customer'";
1301     $result = $conn->Execute($sql);
1302     if($result && !$result->EOF) {
1303       $customer_info['id'] = $result->fields['foreign_id'];
1304     }
1305     $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1306     $ws = new WSWrapper($function);
1307     if(is_numeric($ws->value)) {
1308       return sprintf('%01.2f', $ws->value);
1309     }
1310   }
1311   return '';