added support for the scanned_notes encounter form
[openemr.git] / library / patient.inc
blobdcff7d825e975dfecf9c73dd4346af22a3563081
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 ";
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     $rez = sqlStatement($query);
166     for($iter=0; $row=sqlFetchArray($rez); $iter++)
167         $returnval[$iter]=$row;
169     //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
170     //accessible from $resultval['key']
172     if($iter==1) {
173         $akeys = array_keys($returnval[0]);
174         foreach($akeys as $key) {
176             $returnval[0][$key] = $returnval[0][$key];
177         }
178     }
179     return $returnval;
182 //same as above but does not reduce if only 1 row returned
183 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
184     $param1 = "";
185     if ($providers_only) {
186         $param1 = "AND authorized=1";
187     }
188     $command = "=";
189     if ($providerID == "%") {
190         $command = "like";
191     }
192     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
193         "from users where active = 1 and username != '' and id $command '" .
194         mysql_real_escape_string($providerID) . "' " . $param1;
196     $rez = sqlStatement($query);
197     for($iter=0; $row=sqlFetchArray($rez); $iter++)
198         $returnval[$iter]=$row;
200     return $returnval;
203 function getProviderName($providerID) {
204     $pi = getProviderInfo($providerID);
205     if (strlen($pi[0]["lname"]) > 0) {
206         return $pi[0]['fname'] . " " . $pi[0]['lname'];
207     }
208     return "";
211 function getProviderId($providerName) {
212     $query = "select id from users where username = '". mysql_real_escape_string($providerName)."'";
213     $rez = sqlStatement($query);
214     for($iter=0; $row=sqlFetchArray($rez); $iter++)
215         $returnval[$iter]=$row;
216     return $returnval;
219 function getEthnoRacials() {
220     $returnval = array("");
221     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
222     $rez = sqlStatement($sql);
223     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
224         if (($row["ethnoracial"] != "")) {
225             array_push($returnval, $row["ethnoracial"]);
226         }
227     }
228     return $returnval;
231 function getHistoryData($pid, $given = "*")
233     $sql = "select $given from history_data where pid='$pid' order by date DESC limit 0,1";
234     return sqlQuery($sql);
237 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
238 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
240   $sql = "select $given from insurance_data as insd " .
241     "left join insurance_companies as ic on ic.id = insd.provider " .
242     "where pid = '$pid' and type = '$type' order by date DESC limit 1";
243   return sqlQuery($sql);
246 function getInsuranceDataByDate($pid, $date, $type,
247   $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
248 { // this must take the date in the following manner: YYYY-MM-DD
249   // this function recalls the insurance value that was most recently enterred from the
250   // given date. it will call up most recent records up to and on the date given,
251   // but not records enterred after the given date
252   $sql = "select $given from insurance_data as insd " .
253     "left join insurance_companies as ic on ic.id = provider " .
254     "where pid = '$pid' and date_format(date,'%Y-%m-%d') <= '$date' and " .
255     "type='$type' order by date DESC limit 1";
256   return sqlQuery($sql);
259 function getEmployerData($pid, $given = "*")
261     $sql = "select $given from employer_data where pid='$pid' order by date DESC limit 0,1";
262     return sqlQuery($sql);
265 function _set_patient_inc_count($limit, $count, $where) {
266   // When the limit is exceeded, find out what the unlimited count would be.
267   $GLOBALS['PATIENT_INC_COUNT'] = $count;
268   if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
269     $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where");
270     $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
271   }
274 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")
276     // Allow the last name to be followed by a comma and some part of a first name.
277     // New behavior for searches:
278     // Allows comma alone followed by some part of a first name
279     // If the first letter of either name is capital, searches for name starting
280     // with given substring (the expected behavior).  If it is lower case, it
281     // it searches for the substring anywhere in the name.  This applies to either
282     // last name or first name or both.  The arbitrary limit of 100 results is set
283     // in the sql query below. --Mark Leeds
284     $lname = trim($lname);
285     $fname = '';
286      if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
287          $lname = trim($matches[1]);
288          $fname = trim($matches[2]);
289     }
290     $search_for_pieces1 = '';
291     $search_for_pieces2 = '';
292     if ($lname{0} != strtoupper($lname{0})) {$search_for_pieces1 = '%';}
293     if ($fname{0} != strtoupper($fname{0})) {$search_for_pieces2 = '%';}
295     $where = "lname LIKE '" . $search_for_pieces1 . "$lname%' " .
296         "AND fname LIKE '" . $search_for_pieces2 . "$fname%'";
297     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
298     if ($limit != "all") $sql .= " LIMIT $start, $limit";
300     $rez = sqlStatement($sql);
302     for($iter=0; $row=sqlFetchArray($rez); $iter++)
303         $returnval[$iter] = $row;
305     _set_patient_inc_count($limit, count($returnval), $where);
306     return $returnval;
309 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")
311     $where = "pubpid LIKE '$pid%'";
312     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
313     if ($limit != "all") $sql .= " limit $start, $limit";
314     $rez = sqlStatement($sql);
315     for($iter=0; $row=sqlFetchArray($rez); $iter++)
316         $returnval[$iter]=$row;
318     _set_patient_inc_count($limit, count($returnval), $where);
319     return $returnval;
322 // return a collection of Patient PIDs
323 // new arg style by JRM March 2008
324 // 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")
325 function getPatientPID($args)
327     $pid = "%";
328     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
329     $orderby = "lname ASC, fname ASC";
330     $limit="all";
331     $start="0";
333     // alter default values if defined in the passed in args
334     if (isset($args['pid'])) { $pid = $args['pid']; }
335     if (isset($args['given'])) { $given = $args['given']; }
336     if (isset($args['orderby'])) { $orderby = $args['orderby']; }
337     if (isset($args['limit'])) { $limit = $args['limit']; }
338     if (isset($args['start'])) { $start = $args['start']; }
340     $command = "=";
341     if ($pid == -1) $pid = "%";
342     elseif (empty($pid)) $pid = "NULL";
344     if (strstr($pid,"%")) $command = "like";
346     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
347     if ($limit != "all") $sql .= " limit $start, $limit";
349     $rez = sqlStatement($sql);
350     for($iter=0; $row=sqlFetchArray($rez); $iter++)
351         $returnval[$iter]=$row;
353     return $returnval;
356 function getPatientName($pid) {
357     if (empty($pid)) return "";
358     $patientData = getPatientPID(array("pid"=>$pid));
359     if (empty($patientData[0]['lname'])) return "";
360     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
361     return $patientName;
364 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
366     $DOB = fixDate($DOB, $DOB);
367     $where = "DOB like '$DOB%'";
368     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
369     if ($limit != "all") $sql .= " LIMIT $start, $limit";
371     $rez = sqlStatement($sql);
372     for($iter=0; $row=sqlFetchArray($rez); $iter++)
373         $returnval[$iter]=$row;
375     _set_patient_inc_count($limit, count($returnval), $where);
376     return $returnval;
379 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
381     $where = "ss LIKE '$ss%'";
382     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
383     if ($limit != "all") $sql .= " LIMIT $start, $limit";
385     $rez = sqlStatement($sql);
386     for($iter=0; $row=sqlFetchArray($rez); $iter++)
387         $returnval[$iter]=$row;
389     _set_patient_inc_count($limit, count($returnval), $where);
390     return $returnval;
393 //(CHEMED) Search by phone number
394 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
396     $phone = ereg_replace( "[[:punct:]]","", $phone );
397     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP '$phone'";
398     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
399     if ($limit != "all") $sql .= " LIMIT $start, $limit";
401     $rez = sqlStatement($sql);
402     for($iter=0; $row=sqlFetchArray($rez); $iter++)
403         $returnval[$iter]=$row;
405     _set_patient_inc_count($limit, count($returnval), $where);
406     return $returnval;
409 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
411     $sql="select $given from patient_data order by $orderby";
413     if ($limit != "all")
414         $sql .= " limit $start, $limit";
416     $rez = sqlStatement($sql);
417     for($iter=0; $row=sqlFetchArray($rez); $iter++)
418         $returnval[$iter]=$row;
420     return $returnval;
423 //----------------------input functions
424 function newPatientData(    $db_id="",
425                 $title = "",
426                 $fname = "",
427                 $lname = "",
428                 $mname = "",
429                 $sex = "",
430                 $DOB = "",
431                 $street = "",
432                 // DBC dutch use
433                 $nstreet = "",
434                 $nnr = "",
435                 $nadd = "",
436                 // EOS DBC
437                 $postal_code = "",
438                 $city = "",
439                 $state = "",
440                 $country_code = "",
441                 $ss = "",
442                 $occupation = "",
443                 $phone_home = "",
444                 $phone_biz = "",
445                 $phone_contact = "",
446                 $status = "",
447                 $contact_relationship = "",
448                 $referrer = "",
449                 $referrerID = "",
450                 $email = "",
451                 $language = "",
452                 $ethnoracial = "",
453                 $interpretter = "",
454                 $migrantseasonal = "",
455                 $family_size = "",
456                 $monthly_income = "",
457                 $homeless = "",
458                 $financial_review = "",
459                 $pubpid = "",
460                 $pid = "MAX(pid)+1",
461                 $providerID = "",
462                 $genericname1 = "",
463                 $genericval1 = "",
464                 $genericname2 = "",
465                 $genericval2 = "",
466                 $phone_cell = "",
467                 $hipaa_mail = "",
468                 $hipaa_voice = "",
469                 $squad = 0,
470                 $pharmacy_id = 0,
471                 $drivers_license = "",
472                 $hipaa_notice = "",
473                 $hipaa_message = "",
474                 $regdate = "",
475                 // dutch specific
476                 $prefixlast = "",
477                 $prefixlastpartner = "",
478                 $lastpartner = "",
479                 $initials = "",
480                 $provider_data = array(),
481                 $referer_data = array()
482                 // DBC Dutch System
484             )
486     $DOB = fixDate($DOB);
487     $regdate = fixDate($regdate);
489     $fitness = 0;
490     $referral_source = '';
491     if ($pid) {
492         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
493         // Check for brain damage:
494         if ($db_id != $rez['id']) {
495             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
496               $rez['id'] . "' to '$db_id' for pid '$pid'";
497             die($errmsg);
498         }
499         $fitness = $rez['fitness'];
500         $referral_source = $rez['referral_source'];
501     }
503     // Get the default price level.
504     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
505       "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
506     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
508     $query = ("replace into patient_data set
509         id='$db_id',
510         title='$title',
511         fname='$fname',
512         lname='$lname',
513         mname='$mname',
514         sex='$sex',
515         DOB='$DOB',
516         street='$street',
517         postal_code='$postal_code',
518         city='$city',
519         state='$state',
520         country_code='$country_code',
521         drivers_license='$drivers_license',
522         ss='$ss',
523         occupation='$occupation',
524         phone_home='$phone_home',
525         phone_biz='$phone_biz',
526         phone_contact='$phone_contact',
527         status='$status',
528         contact_relationship='$contact_relationship',
529         referrer='$referrer',
530         referrerID='$referrerID',
531         email='$email',
532         language='$language',
533         ethnoracial='$ethnoracial',
534         interpretter='$interpretter',
535         migrantseasonal='$migrantseasonal',
536         family_size='$family_size',
537         monthly_income='$monthly_income',
538         homeless='$homeless',
539         financial_review='$financial_review',
540         pubpid='$pubpid',
541         pid = $pid,
542         providerID = '$providerID',
543         genericname1 = '$genericname1',
544         genericval1 = '$genericval1',
545         genericname2 = '$genericname2',
546         genericval2 = '$genericval2',
547         phone_cell = '$phone_cell',
548         pharmacy_id = '$pharmacy_id',
549         hipaa_mail = '$hipaa_mail',
550         hipaa_voice = '$hipaa_voice',
551         hipaa_notice = '$hipaa_notice',
552         hipaa_message = '$hipaa_message',
553         squad = '$squad',
554         fitness='$fitness',
555         referral_source='$referral_source',
556         regdate='$regdate',
557         pricelevel='$pricelevel',
558         date=NOW()");
560     $id = sqlInsert($query);
562     // DBC 
563     if ( !$db_id ) {
564       // find the last inserted id for new patient case
565       $db_id = empty($GLOBALS['dutchpc']) ? mysql_insert_id() : dsql_lastid();
566     }
567     // EOS DBC
569     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
571          // dutch use
572         if ( $GLOBALS['dutchpc'] ) {
573                 $init = strtoupper(preg_replace('/[\s\.\-_0-9]/','',$initials));
574                 
575             $querynl = ("REPLACE INTO patient_data_NL SET
576                     pdn_id = '$db_id',
577                     pdn_pxlast = '$prefixlast',
578                     pdn_pxlastpar = '$prefixlastpartner',
579                     pdn_lastpar = '$lastpartner',
580                     pdn_street = '$nstreet',
581                     pdn_number = '$nnr',
582                     pdn_addition = '$nadd',
583                     pdn_initials = '$init'
584             ");
586             if ( $db_id ) $idnl = sqlInsert($querynl); // only if exists
587         }
588         // EOS dutch use
591        // DBC Dutch System
592         // provider first
593         if ( $GLOBALS['dutchpc'] && $db_id && $provider_data && $referer_data) {
594            $querypr = ("INSERT INTO cl_providers(pro_pid, pro_company, pro_initials, pro_prefix, pro_lname,
595                    pro_street, pro_number, pro_addition, pro_city, pro_zipcode,  pro_phone, pro_fax, pro_email, pro_referer ) 
596                    VALUES ($db_id, '{$provider_data['pro_company']}', '{$provider_data['pro_initials']}',
597                   '{$provider_data['pro_prefix']}', '{$provider_data['pro_lname']}',  
598                   '{$provider_data['pro_street']}', '{$provider_data['pro_number']}', '{$provider_data['pro_addition']}', 
599                   '{$provider_data['pro_city']}',  '{$provider_data['pro_zipcode']}',
600                   '{$provider_data['pro_phone']}', '{$provider_data['pro_fax']}',  '{$provider_data['pro_email']}', 
601                   '{$provider_data['pro_referer']}') 
602                   ON DUPLICATE KEY UPDATE  pro_referer = '{$provider_data['pro_referer']}',
603                   pro_company = '{$provider_data['pro_company']}', pro_initials = '{$provider_data['pro_initials']}',
604                   pro_prefix = '{$provider_data['pro_prefix']}',
605                   pro_lname = '{$provider_data['pro_lname']}', pro_street = '{$provider_data['pro_street']}',
606                   pro_number = '{$provider_data['pro_number']}', pro_addition = '{$provider_data['pro_addition']}',
607                   pro_city = '{$provider_data['pro_city']}', pro_zipcode = '{$provider_data['pro_zipcode']}',
608                   pro_phone = '{$provider_data['pro_phone']}', pro_fax = '{$provider_data['pro_fax']}',
609                   pro_email = '{$provider_data['pro_email']}'
610             ");
611            $idpr = sqlInsert($querypr);
613         // referer if it's the case
614         if ( $referer_data['ref_code'] ) {
615            $queryre = ("INSERT INTO cl_referers(ref_pid, ref_code, ref_company, ref_initials, ref_prefix,
616                    ref_lname, ref_street, ref_number, ref_addition, ref_city, ref_zipcode,  ref_phone, ref_fax,
617                    ref_email) 
618                    VALUES ($db_id, {$referer_data['ref_code']}, '{$referer_data['ref_company']}', 
619                    '{$referer_data['ref_initials']}', '{$referer_data['ref_prefix']}',
620                    '{$referer_data['ref_lname']}', '{$referer_data['ref_street']}', '{$referer_data['ref_number']}', 
621                    '{$referer_data['ref_addition']}', '{$referer_data['ref_city']}', '{$referer_data['ref_zipcode']}',
622                   '{$referer_data['ref_phone']}', '{$referer_data['ref_fax']}',  '{$referer_data['ref_email']}')
623                   ON DUPLICATE KEY UPDATE ref_code = {$referer_data['ref_code']},
624                   ref_company = '{$referer_data['ref_company']}', ref_initials = '{$referer_data['ref_initials']}',
625                   ref_prefix = '{$referer_data['ref_prefix']}',
626                   ref_lname = '{$referer_data['ref_lname']}', ref_street = '{$referer_data['ref_street']}',
627                   ref_number = '{$referer_data['ref_number']}', ref_addition = '{$referer_data['ref_addition']}',
628                   ref_city = '{$referer_data['ref_city']}', ref_zipcode = '{$referer_data['ref_zipcode']}',
629                   ref_phone = '{$referer_data['ref_phone']}', ref_fax = '{$referer_data['ref_fax']}',
630                   ref_email = '{$referer_data['ref_email']}'
631             ");
632            $idre = sqlInsert($queryre);
633         } 
634         } // if globals
635         // EOS DBC
637     sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
638                 $phone_biz,$phone_cell,$email,$pid);
640     return $foo['pid'];
643 // Supported input date formats are:
644 //   mm/dd/yyyy
645 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
646 //   yyyy/mm/dd
647 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
649 function fixDate($date, $default="0000-00-00") {
650     $fixed_date = $default;
651     $date = trim($date);
652     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
653         $dmy = preg_split("'[/.-]'", $date);
654         if ($dmy[0] > 99) {
655             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
656         } else {
657             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
658               if ($dmy[2] < 1000) $dmy[2] += 1900;
659               if ($dmy[2] < 1910) $dmy[2] += 100;
660             }
661             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
662         }
663     }
665     return $fixed_date;
668 function updatePatientData($pid,$new)
670   /*******************************************************************
671     $real = getPatientData($pid);
672     $new['DOB'] = fixDate($new['DOB']);
673     while(list($key, $value) = each ($new))
674         $real[$key] = $value;
675     $real['date'] = "'+NOW()+'";
676     $real['id'] = "";
677     $sql = "insert into patient_data set ";
678     while(list($key, $value) = each($real))
679         $sql .= $key." = '$value', ";
680     $sql = substr($sql, 0, -2);
681     return sqlInsert($sql);
682   *******************************************************************/
684   // The above was broken, though seems intent to insert a new patient_data
685   // row for each update.  A good idea, but nothing is doing that yet so
686   // the code below does not yet attempt it.
688   $new['DOB'] = fixDate($new['DOB']);
689   $db_id = $new['id'];
691   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
692   // Check for brain damage:
693   if ($pid != $rez['pid']) {
694     $errmsg = "Internal error: Attempt to change patient data with pid = '" .
695       $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
696     die($errmsg);
697   }
698   $sql = "UPDATE patient_data SET date = NOW()";
699   foreach ($new as $key => $value) {
700     $sql .= ", $key = '$value'";
701   }
702   $sql .= " WHERE id = '$db_id'";
703   $id = sqlInsert($sql);
705   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
706     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
707     $rez['phone_cell'],$rez['email'],$rez['pid']);
709   return $id;
712 function newEmployerData(    $pid,
713                 $name = "",
714                 $street = "",
715                 $postal_code = "",
716                 $city = "",
717                 $state = "",
718                 $country = ""
719             )
721     return sqlInsert("insert into employer_data set
722         name='$name',
723         street='$street',
724         postal_code='$postal_code',
725         city='$city',
726         state='$state',
727         country='$country',
728         pid='$pid',
729         date=NOW()
730         ");
733 function updateEmployerData($pid, $new)
735   $old = getEmployerData($pid);
736   $set = '';
737   $modified = false;
738   foreach (array('name','street','city','state','postal_code','country') as $key) {
739     $value = empty($old[$key]) ? '' : addslashes($old[$key]);
740     if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
741       $value = $new[$key];
742       $modified = true;
743     }
744     $set .= "$key = '$value', ";
745   }
746   if ($modified) {
747     $set .= "pid = '$pid', date = NOW()";
748     return sqlInsert("INSERT INTO employer_data SET $set");
749   }
750   return $old['id'];
753 // This updates or adds the given insurance data info, while retaining any
754 // previously added insurance_data rows that should be preserved.
755 // This does not directly support the maintenance of non-current insurance.
757 function newInsuranceData(
758   $pid,
759   $type = "",
760   $provider = "",
761   $policy_number = "",
762   $group_number = "",
763   $plan_name = "",
764   $subscriber_lname = "",
765   $subscriber_mname = "",
766   $subscriber_fname = "",
767   $subscriber_relationship = "",
768   $subscriber_ss = "",
769   $subscriber_DOB = "",
770   $subscriber_street = "",
771   $subscriber_postal_code = "",
772   $subscriber_city = "",
773   $subscriber_state = "",
774   $subscriber_country = "",
775   $subscriber_phone = "",
776   $subscriber_employer = "",
777   $subscriber_employer_street = "",
778   $subscriber_employer_city = "",
779   $subscriber_employer_postal_code = "",
780   $subscriber_employer_state = "",
781   $subscriber_employer_country = "",
782   $copay = "",
783   $subscriber_sex = "",
784   $effective_date = "0000-00-00",
785   $accept_assignment = "TRUE")
787   if (strlen($type) <= 0) return FALSE;
789   // If a bad date was passed, err on the side of caution.
790   $effective_date = fixDate($effective_date, date('Y-m-d'));
792   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
793     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
794   $idrow = sqlFetchArray($idres);
796   // Replace the most recent entry in any of the following cases:
797   // * Its effective date is >= this effective date.
798   // * It is the first entry and it has no (insurance) provider.
799   // * There is no encounter that is earlier than the new effective date but
800   //   on or after the old effective date.
801   // Otherwise insert a new entry.
803   $replace = false;
804   if ($idrow) {
805     if (strcmp($idrow['date'], $effective_date) > 0) {
806       $replace = true;
807     }
808     else {
809       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
810         $replace = true;
811       }
812       else {
813         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
814           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
815           "date >= '" . $idrow['date'] . " 00:00:00'");
816         if ($ferow['count'] == 0) $replace = true;
817       }
818     }
819   }
821   if ($replace) {
823     // TBD: This is a bit dangerous in that a typo in entering the effective
824     // date can wipe out previous insurance history.  So we want some data
825     // entry validation somewhere.
826     sqlStatement("DELETE FROM insurance_data WHERE " .
827       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
828       "id != " . $idrow['id']);
830     $data = array();
831     $data['type'] = $type;
832     $data['provider'] = $provider;
833     $data['policy_number'] = $policy_number;
834     $data['group_number'] = $group_number;
835     $data['plan_name'] = $plan_name;
836     $data['subscriber_lname'] = $subscriber_lname;
837     $data['subscriber_mname'] = $subscriber_mname;
838     $data['subscriber_fname'] = $subscriber_fname;
839     $data['subscriber_relationship'] = $subscriber_relationship;
840     $data['subscriber_ss'] = $subscriber_ss;
841     $data['subscriber_DOB'] = $subscriber_DOB;
842     $data['subscriber_street'] = $subscriber_street;
843     $data['subscriber_postal_code'] = $subscriber_postal_code;
844     $data['subscriber_city'] = $subscriber_city;
845     $data['subscriber_state'] = $subscriber_state;
846     $data['subscriber_country'] = $subscriber_country;
847     $data['subscriber_phone'] = $subscriber_phone;
848     $data['subscriber_employer'] = $subscriber_employer;
849     $data['subscriber_employer_city'] = $subscriber_employer_city;
850     $data['subscriber_employer_street'] = $subscriber_employer_street;
851     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
852     $data['subscriber_employer_state'] = $subscriber_employer_state;
853     $data['subscriber_employer_country'] = $subscriber_employer_country;
854     $data['copay'] = $copay;
855     $data['subscriber_sex'] = $subscriber_sex;
856     $data['pid'] = $pid;
857     $data['date'] = $effective_date;
858     $data['accept_assignment'] = $accept_assignment;
859     updateInsuranceData($idrow['id'], $data);
860     return $idrow['id'];
861   }
862   else {
863     return sqlInsert("INSERT INTO insurance_data SET
864       type = '$type',
865       provider = '$provider',
866       policy_number = '$policy_number',
867       group_number = '$group_number',
868       plan_name = '$plan_name',
869       subscriber_lname = '$subscriber_lname',
870       subscriber_mname = '$subscriber_mname',
871       subscriber_fname = '$subscriber_fname',
872       subscriber_relationship = '$subscriber_relationship',
873       subscriber_ss = '$subscriber_ss',
874       subscriber_DOB = '$subscriber_DOB',
875       subscriber_street = '$subscriber_street',
876       subscriber_postal_code = '$subscriber_postal_code',
877       subscriber_city = '$subscriber_city',
878       subscriber_state = '$subscriber_state',
879       subscriber_country = '$subscriber_country',
880       subscriber_phone = '$subscriber_phone',
881       subscriber_employer = '$subscriber_employer',
882       subscriber_employer_city = '$subscriber_employer_city',
883       subscriber_employer_street = '$subscriber_employer_street',
884       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
885       subscriber_employer_state = '$subscriber_employer_state',
886       subscriber_employer_country = '$subscriber_employer_country',
887       copay = '$copay',
888       subscriber_sex = '$subscriber_sex',
889       pid = '$pid',
890       date = '$effective_date',
891       accept_assignment = '$accept_assignment'
892     ");
893   }
896 // This is used internally only.
897 function updateInsuranceData($id, $new)
899   $fields = sqlListFields("insurance_data");
900   $use = array();
902   while(list($key, $value) = each ($new)) {
903     if (in_array($key, $fields)) {
904       $use[$key] = $value;
905     }
906   }
908   $sql = "UPDATE insurance_data SET ";
909   while(list($key, $value) = each($use))
910     $sql .= $key . " = '$value', ";
911   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
913   sqlStatement($sql);
916 function newHistoryData($pid, $new=false) {
917   $sql = "insert into history_data set pid = '$pid', date = NOW()";
918   if ($new) {
919     while(list($key, $value) = each($new)) {
920       if (!get_magic_quotes_gpc()) $value = addslashes($value);
921       $sql .= ", $key = '$value'";
922     }
923   }
924   return sqlInsert($sql);
927 function updateHistoryData($pid,$new)
929         $real = getHistoryData($pid);
930         while(list($key, $value) = each ($new))
931                 $real[$key] = $value;
932         $real['date'] = "'+NOW()+'";
933         $real['id'] = "";
935         $sql = "insert into history_data set ";
936         while(list($key, $value) = each($real))
937                 $sql .= $key." = '$value', ";
938         $sql = substr($sql, 0, -2);
941         return sqlInsert($sql);
944 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
945                 $phone_biz,$phone_cell,$email,$pid="")
947     if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
948     if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
950     $db = $GLOBALS['adodb']['db'];
951     $customer_info = array();
953     $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
954     $result = $db->Execute($sql);
955     if ($result && !$result->EOF) {
956         $customer_info['foreign_update'] = true;
957         $customer_info['foreign_id'] = $result->fields['foreign_id'];
958         $customer_info['foreign_table'] = $result->fields['foreign_table'];
959     }
961     ///xml rpc code to connect to accounting package and add user to it
962     $customer_info['firstname'] = $fname;
963     $customer_info['lastname'] = $lname;
964     $customer_info['address'] = $street;
965     $customer_info['suburb'] = $city;
966     $customer_info['state'] = $state;
967     $customer_info['postcode'] = $postal_code;
969     //ezybiz wants state as a code rather than abbreviation
970     $customer_info['geo_zone_id'] = "";
971     $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
972     $db = $GLOBALS['adodb']['db'];
973     $result = $db->Execute($sql);
974     if ($result && !$result->EOF) {
975         $customer_info['geo_zone_id'] = $result->fields['zone_id'];
976     }
978     //ezybiz wants country as a code rather than abbreviation
979     $customer_info['geo_country_id'] = "";
980     $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
981     $db = $GLOBALS['adodb']['db'];
982     $result = $db->Execute($sql);
983     if ($result && !$result->EOF) {
984         $customer_info['geo_country_id'] = $result->fields['countries_id'];
985     }
987     $customer_info['phone1'] = $phone_home;
988     $customer_info['phone1comment'] = "Home Phone";
989     $customer_info['phone2'] = $phone_biz;
990     $customer_info['phone2comment'] = "Business Phone";
991     $customer_info['phone3'] = $phone_cell;
992     $customer_info['phone3comment'] = "Cell Phone";
993     $customer_info['email'] = $email;
994     $customer_info['customernumber'] = $pid;
996     $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
997     $ws = new WSWrapper($function);
999     // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1000     if (is_numeric($ws->value)) {
1001         $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1002         $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1003     }
1006 // Returns Date of Birth given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1007 function getPatientAge($dobYMD)
1009     $tdyYMD=date("Ymd");
1010     $yearDiff = substr($tdyYMD,0,4) - substr($dobYMD,0,4);
1011     $ageInMonths = ((substr($tdyYMD,0,4)*12)+substr($tdyYMD,4,2)) -
1012                    ((substr($dobYMD,0,4)*12)+substr($dobYMD,4,2));
1013     $dayDiff = substr($tdyYMD,6,2) - substr($dobYMD,6,2);
1014     if ( $dayDiff < 0 ) {
1015         $ageInMonths -= 1;
1016     }
1017     if ( $ageInMonths > 24 ) {
1018         $age = intval($ageInMonths/12);
1019     }
1020     else  {
1021         $age = "$ageInMonths month";
1022     }
1023     return $age;
1026 function dateToDB ($date)
1028     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1029     return $date;
1033 // ----------------------------------------------------------------------------
1035  * DROPDOWN FOR COUNTRIES
1036  * 
1037  * build a dropdown with all countries from geo_country_reference
1038  * 
1039  * @param int $selected - id for selected record
1040  * @param string $name - the name/id for select form
1041  * @return void - just echo the html encoded string
1042  */
1043 function dropdown_countries($selected = 0, $name = 'country_code') {
1044     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1046     $string = "<select name='$name' id='$name'>";
1047     while ( $row = sqlFetchArray($r) ) {
1048         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1049         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1050     }
1052     $string .= '</select>';
1053     echo $string;
1057 // ----------------------------------------------------------------------------
1059  * DROPDOWN FOR YES/NO
1060  * 
1061  * build a dropdown with two options (yes - 1, no - 0)
1062  * 
1063  * @param int $selected - id for selected record
1064  * @param string $name - the name/id for select form
1065  * @return void - just echo the html encoded string 
1066  */
1067 function dropdown_yesno($selected = 0, $name = 'yesno') {
1068     $string = "<select name='$name' id='$name'>";
1070     $selected = (int)$selected;
1071     if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1072     else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1074     $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1075     $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1076     $string .= '</select>';
1078     echo $string;
1081 // ----------------------------------------------------------------------------
1083  * DROPDOWN FOR MALE/FEMALE options
1084  * 
1085  * build a dropdown with three options (unselected/male/female)
1086  * 
1087  * @param int $selected - id for selected record
1088  * @param string $name - the name/id for select form
1089  * @return void - just echo the html encoded string
1090  */
1091 function dropdown_sex($selected = 0, $name = 'sex') {
1092     $string = "<select name='$name' id='$name'>";
1094     if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1095     else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1096     else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1098     $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1099     $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1100     $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1101     $string .= '</select>';
1103     echo $string;
1106 // ----------------------------------------------------------------------------
1108  * DROPDOWN FOR MARITAL STATUS
1109  * 
1110  * build a dropdown with marital status
1111  * 
1112  * @param int $selected - id for selected record
1113  * @param string $name - the name/id for select form
1114  * @return void - just echo the html encoded string
1115  */
1116 function dropdown_marital($selected = 0, $name = 'status') {
1117     $string = "<select name='$name' id='$name'>";
1119     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1121     foreach ( $statii as $st ) {
1122         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1123         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1124     }
1126     $string .= '</select>';
1128     echo $string;
1131 // ----------------------------------------------------------------------------
1133  * DROPDOWN FOR PROVIDERS
1134  * 
1135  * build a dropdown with all providers
1136  * 
1137  * @param int $selected - id for selected record
1138  * @param string $name - the name/id for select form
1139  * @return void - just echo the html encoded string
1140  */
1141 function dropdown_providers($selected = 0, $name = 'status') {
1142     $provideri = getProviderInfo();
1144     $string = "<select name='$name' id='$name'>";
1145     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1146     foreach ( $provideri as $s ) {
1147         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1148         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1149     }
1151     $string .= '</select>';
1153     echo $string;
1156 // ----------------------------------------------------------------------------
1158  * DROPDOWN FOR INSURANCE COMPANIES
1159  * 
1160  * build a dropdown with all insurers
1161  * 
1162  * @param int $selected - id for selected record
1163  * @param string $name - the name/id for select form
1164  * @return void - just echo the html encoded string
1165  */
1166 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1167     $insurancei = getInsuranceProviders();
1169     $string = "<select name='$name' id='$name'>";
1170     $string .= '<option value="0">Onbekend</option>';
1171     foreach ( $insurancei as $iid => $iname ) {
1172         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1173         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1174     }
1176     $string .= '</select>';
1178     echo $string;
1182 // ----------------------------------------------------------------------------
1184  * COUNTRY CODE
1185  * 
1186  * return the name or the country code, function of arguments
1187  * 
1188  * @param int $country_code
1189  * @param string $country_name
1190  * @return string | int - name or code
1191  */
1192 function country_code($country_code = 0, $country_name = '') {
1193     $strint = '';
1194     if ( $country_code ) {
1195         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1196     } else {
1197         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1198     }
1200     $db = $GLOBALS['adodb']['db'];
1201     $result = $db->Execute($sql);
1202     if ($result && !$result->EOF) {
1203         $strint = $result->fields['res'];
1204     }
1206     return $strint;
1209 // ----------------------------------------------------------------------------
1211  * GET INSURANCE DATA
1212  * (Dutch usage)
1213  * 
1214  * return the insurer(s) and some patient
1215  * 
1216  * @param int $pid - patient id
1217  * @param int $current 1-current 0-all insurers
1218  * @return array
1219  */
1220 function get_insurers_nl($pid = 0, $current = 1) {
1221     if ( !$pid ) return FALSE;
1223     $join = 'insurance_companies ic ON ic.id = pi.pin_provider';
1224     $r = dsql_select('*', 'patient_insurers_NL pi', array('pin_pid' => $pid), 'pin_date DESC', $join);
1226     while ( $row = mysql_fetch_array($r) ) {
1227         $rez[] = $row;
1228     } // while
1230     return ( $current ? $rez[0] : $rez );
1234 // ----------------------------------------------------------------------------
1236  * SET INSURANCE DATA
1237  * (Dutch usage)
1238  * 
1239  * set the insurer for a patient
1240  * 
1241  * @param int $pid - patient id
1242  * @param int $insid - insurer id
1243  * @return void
1244  */
1245 function set_insurer_nl($pid = 0, $insid = 0, $date = '', $policy = '') {
1246     if ( !$pid || !$insid || ($date == '0000-00-00') ) return FALSE;
1248     $fields = array('pin_pid', 'pin_provider', 'pin_date', 'pin_policy');
1249     $values = array($pid, $insid, $date, $policy);
1250     dsql_insert('patient_insurers_NL', $fields, $values);
1253 // ----------------------------------------------------------------------------
1255  * FIND THE INSURERS STATUS FOR A PATIENT
1256  * (Dutch usage)
1257  * 
1258  * return the answer for the question: is this the first insurer or not?
1259  * 
1260  * @param int $pid - patient id
1261  * @return int - the number of insurer records ( 0 - no insurer; >0 some insurers)
1262  */
1263 function total_insurers($pid = 0) {
1264     if ( !$pid ) return FALSE;
1266     $r = dsql_select('COUNT(*) AS c', 'patient_insurers_NL', array('pin_pid' => $pid));
1267     $row = mysql_fetch_array($r);
1269     return $row['c'];
1272 function DBToDate ($date)
1274     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1275     return $date;
1278 function get_patient_balance($pid) {
1279   if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1280     $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1281       "pid = '$pid' AND activity = 1");
1282     $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1283       "pid = '$pid'");
1284     $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1285       "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1286       "pid = '$pid'");
1287     return sprintf('%01.2f', $brow['amount'] + $srow['amount']
1288       - $drow['payments'] - $drow['adjustments']);
1289   }
1290   else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1291     // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1292     $conn = $GLOBALS['adodb']['db'];
1293     $customer_info['id'] = 0;
1294     $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1295       "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1296       "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1297       "im.foreign_table = 'customer'";
1298     $result = $conn->Execute($sql);
1299     if($result && !$result->EOF) {
1300       $customer_info['id'] = $result->fields['foreign_id'];
1301     }
1302     $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1303     $ws = new WSWrapper($function);
1304     if(is_numeric($ws->value)) {
1305       return sprintf('%01.2f', $ws->value);
1306     }
1307   }
1308   return '';