HTML users guide from Tony McCormick
[openemr.git] / library / patient.inc
blob330ec54d2f91fea746098435c14b943349e852d4
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 /* return a patient's name in the format LAST, FIRST */
359 function getPatientName($pid) {
360     if (empty($pid)) return "";
361     $patientData = getPatientPID(array("pid"=>$pid));
362     if (empty($patientData[0]['lname'])) return "";
363     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
364     return $patientName;
367 /* find patient data by DOB */
368 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
370     $DOB = fixDate($DOB, $DOB);
371     $where = "DOB like '$DOB%'";
372     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
373     if ($limit != "all") $sql .= " LIMIT $start, $limit";
375     $rez = sqlStatement($sql);
376     for($iter=0; $row=sqlFetchArray($rez); $iter++)
377         $returnval[$iter]=$row;
379     _set_patient_inc_count($limit, count($returnval), $where);
380     return $returnval;
383 /* find patient data by SSN */
384 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
386     $where = "ss LIKE '$ss%'";
387     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
388     if ($limit != "all") $sql .= " LIMIT $start, $limit";
390     $rez = sqlStatement($sql);
391     for($iter=0; $row=sqlFetchArray($rez); $iter++)
392         $returnval[$iter]=$row;
394     _set_patient_inc_count($limit, count($returnval), $where);
395     return $returnval;
398 //(CHEMED) Search by phone number
399 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
401     $phone = ereg_replace( "[[:punct:]]","", $phone );
402     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP '$phone'";
403     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
404     if ($limit != "all") $sql .= " LIMIT $start, $limit";
406     $rez = sqlStatement($sql);
407     for($iter=0; $row=sqlFetchArray($rez); $iter++)
408         $returnval[$iter]=$row;
410     _set_patient_inc_count($limit, count($returnval), $where);
411     return $returnval;
414 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
416     $sql="select $given from patient_data order by $orderby";
418     if ($limit != "all")
419         $sql .= " limit $start, $limit";
421     $rez = sqlStatement($sql);
422     for($iter=0; $row=sqlFetchArray($rez); $iter++)
423         $returnval[$iter]=$row;
425     return $returnval;
428 //----------------------input functions
429 function newPatientData(    $db_id="",
430                 $title = "",
431                 $fname = "",
432                 $lname = "",
433                 $mname = "",
434                 $sex = "",
435                 $DOB = "",
436                 $street = "",
437                 // DBC dutch use
438                 $nstreet = "",
439                 $nnr = "",
440                 $nadd = "",
441                 // EOS DBC
442                 $postal_code = "",
443                 $city = "",
444                 $state = "",
445                 $country_code = "",
446                 $ss = "",
447                 $occupation = "",
448                 $phone_home = "",
449                 $phone_biz = "",
450                 $phone_contact = "",
451                 $status = "",
452                 $contact_relationship = "",
453                 $referrer = "",
454                 $referrerID = "",
455                 $email = "",
456                 $language = "",
457                 $ethnoracial = "",
458                 $interpretter = "",
459                 $migrantseasonal = "",
460                 $family_size = "",
461                 $monthly_income = "",
462                 $homeless = "",
463                 $financial_review = "",
464                 $pubpid = "",
465                 $pid = "MAX(pid)+1",
466                 $providerID = "",
467                 $genericname1 = "",
468                 $genericval1 = "",
469                 $genericname2 = "",
470                 $genericval2 = "",
471                 $phone_cell = "",
472                 $hipaa_mail = "",
473                 $hipaa_voice = "",
474                 $squad = 0,
475                 $pharmacy_id = 0,
476                 $drivers_license = "",
477                 $hipaa_notice = "",
478                 $hipaa_message = "",
479                 $regdate = "",
480                 // dutch specific
481                 $prefixlast = "",
482                 $prefixlastpartner = "",
483                 $lastpartner = "",
484                 $initials = "",
485                 $provider_data = array(),
486                 $referer_data = array()
487                 // DBC Dutch System
489             )
491     $DOB = fixDate($DOB);
492     $regdate = fixDate($regdate);
494     $fitness = 0;
495     $referral_source = '';
496     if ($pid) {
497         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
498         // Check for brain damage:
499         if ($db_id != $rez['id']) {
500             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
501               $rez['id'] . "' to '$db_id' for pid '$pid'";
502             die($errmsg);
503         }
504         $fitness = $rez['fitness'];
505         $referral_source = $rez['referral_source'];
506     }
508     // Get the default price level.
509     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
510       "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
511     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
513     $query = ("replace into patient_data set
514         id='$db_id',
515         title='$title',
516         fname='$fname',
517         lname='$lname',
518         mname='$mname',
519         sex='$sex',
520         DOB='$DOB',
521         street='$street',
522         postal_code='$postal_code',
523         city='$city',
524         state='$state',
525         country_code='$country_code',
526         drivers_license='$drivers_license',
527         ss='$ss',
528         occupation='$occupation',
529         phone_home='$phone_home',
530         phone_biz='$phone_biz',
531         phone_contact='$phone_contact',
532         status='$status',
533         contact_relationship='$contact_relationship',
534         referrer='$referrer',
535         referrerID='$referrerID',
536         email='$email',
537         language='$language',
538         ethnoracial='$ethnoracial',
539         interpretter='$interpretter',
540         migrantseasonal='$migrantseasonal',
541         family_size='$family_size',
542         monthly_income='$monthly_income',
543         homeless='$homeless',
544         financial_review='$financial_review',
545         pubpid='$pubpid',
546         pid = $pid,
547         providerID = '$providerID',
548         genericname1 = '$genericname1',
549         genericval1 = '$genericval1',
550         genericname2 = '$genericname2',
551         genericval2 = '$genericval2',
552         phone_cell = '$phone_cell',
553         pharmacy_id = '$pharmacy_id',
554         hipaa_mail = '$hipaa_mail',
555         hipaa_voice = '$hipaa_voice',
556         hipaa_notice = '$hipaa_notice',
557         hipaa_message = '$hipaa_message',
558         squad = '$squad',
559         fitness='$fitness',
560         referral_source='$referral_source',
561         regdate='$regdate',
562         pricelevel='$pricelevel',
563         date=NOW()");
565     $id = sqlInsert($query);
567     // DBC 
568     if ( !$db_id ) {
569       // find the last inserted id for new patient case
570       $db_id = empty($GLOBALS['dutchpc']) ? mysql_insert_id() : dsql_lastid();
571     }
572     // EOS DBC
574     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
576          // dutch use
577         if ( $GLOBALS['dutchpc'] ) {
578                 $init = strtoupper(preg_replace('/[\s\.\-_0-9]/','',$initials));
579                 
580             $querynl = ("REPLACE INTO patient_data_NL SET
581                     pdn_id = '$db_id',
582                     pdn_pxlast = '$prefixlast',
583                     pdn_pxlastpar = '$prefixlastpartner',
584                     pdn_lastpar = '$lastpartner',
585                     pdn_street = '$nstreet',
586                     pdn_number = '$nnr',
587                     pdn_addition = '$nadd',
588                     pdn_initials = '$init'
589             ");
591             if ( $db_id ) $idnl = sqlInsert($querynl); // only if exists
592         }
593         // EOS dutch use
596        // DBC Dutch System
597         // provider first
598         if ( $GLOBALS['dutchpc'] && $db_id && $provider_data && $referer_data) {
599            $querypr = ("INSERT INTO cl_providers(pro_pid, pro_company, pro_initials, pro_prefix, pro_lname,
600                    pro_street, pro_number, pro_addition, pro_city, pro_zipcode,  pro_phone, pro_fax, pro_email, pro_referer ) 
601                    VALUES ($db_id, '{$provider_data['pro_company']}', '{$provider_data['pro_initials']}',
602                   '{$provider_data['pro_prefix']}', '{$provider_data['pro_lname']}',  
603                   '{$provider_data['pro_street']}', '{$provider_data['pro_number']}', '{$provider_data['pro_addition']}', 
604                   '{$provider_data['pro_city']}',  '{$provider_data['pro_zipcode']}',
605                   '{$provider_data['pro_phone']}', '{$provider_data['pro_fax']}',  '{$provider_data['pro_email']}', 
606                   '{$provider_data['pro_referer']}') 
607                   ON DUPLICATE KEY UPDATE  pro_referer = '{$provider_data['pro_referer']}',
608                   pro_company = '{$provider_data['pro_company']}', pro_initials = '{$provider_data['pro_initials']}',
609                   pro_prefix = '{$provider_data['pro_prefix']}',
610                   pro_lname = '{$provider_data['pro_lname']}', pro_street = '{$provider_data['pro_street']}',
611                   pro_number = '{$provider_data['pro_number']}', pro_addition = '{$provider_data['pro_addition']}',
612                   pro_city = '{$provider_data['pro_city']}', pro_zipcode = '{$provider_data['pro_zipcode']}',
613                   pro_phone = '{$provider_data['pro_phone']}', pro_fax = '{$provider_data['pro_fax']}',
614                   pro_email = '{$provider_data['pro_email']}'
615             ");
616            $idpr = sqlInsert($querypr);
618         // referer if it's the case
619         if ( $referer_data['ref_code'] ) {
620            $queryre = ("INSERT INTO cl_referers(ref_pid, ref_code, ref_company, ref_initials, ref_prefix,
621                    ref_lname, ref_street, ref_number, ref_addition, ref_city, ref_zipcode,  ref_phone, ref_fax,
622                    ref_email) 
623                    VALUES ($db_id, {$referer_data['ref_code']}, '{$referer_data['ref_company']}', 
624                    '{$referer_data['ref_initials']}', '{$referer_data['ref_prefix']}',
625                    '{$referer_data['ref_lname']}', '{$referer_data['ref_street']}', '{$referer_data['ref_number']}', 
626                    '{$referer_data['ref_addition']}', '{$referer_data['ref_city']}', '{$referer_data['ref_zipcode']}',
627                   '{$referer_data['ref_phone']}', '{$referer_data['ref_fax']}',  '{$referer_data['ref_email']}')
628                   ON DUPLICATE KEY UPDATE ref_code = {$referer_data['ref_code']},
629                   ref_company = '{$referer_data['ref_company']}', ref_initials = '{$referer_data['ref_initials']}',
630                   ref_prefix = '{$referer_data['ref_prefix']}',
631                   ref_lname = '{$referer_data['ref_lname']}', ref_street = '{$referer_data['ref_street']}',
632                   ref_number = '{$referer_data['ref_number']}', ref_addition = '{$referer_data['ref_addition']}',
633                   ref_city = '{$referer_data['ref_city']}', ref_zipcode = '{$referer_data['ref_zipcode']}',
634                   ref_phone = '{$referer_data['ref_phone']}', ref_fax = '{$referer_data['ref_fax']}',
635                   ref_email = '{$referer_data['ref_email']}'
636             ");
637            $idre = sqlInsert($queryre);
638         } 
639         } // if globals
640         // EOS DBC
642     sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
643                 $phone_biz,$phone_cell,$email,$pid);
645     return $foo['pid'];
648 // Supported input date formats are:
649 //   mm/dd/yyyy
650 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
651 //   yyyy/mm/dd
652 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
654 function fixDate($date, $default="0000-00-00") {
655     $fixed_date = $default;
656     $date = trim($date);
657     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
658         $dmy = preg_split("'[/.-]'", $date);
659         if ($dmy[0] > 99) {
660             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
661         } else {
662             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
663               if ($dmy[2] < 1000) $dmy[2] += 1900;
664               if ($dmy[2] < 1910) $dmy[2] += 100;
665             }
666             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
667         }
668     }
670     return $fixed_date;
673 // Create or update patient data from an array.
675 function updatePatientData($pid, $new, $create=false)
677   /*******************************************************************
678     $real = getPatientData($pid);
679     $new['DOB'] = fixDate($new['DOB']);
680     while(list($key, $value) = each ($new))
681         $real[$key] = $value;
682     $real['date'] = "'+NOW()+'";
683     $real['id'] = "";
684     $sql = "insert into patient_data set ";
685     while(list($key, $value) = each($real))
686         $sql .= $key." = '$value', ";
687     $sql = substr($sql, 0, -2);
688     return sqlInsert($sql);
689   *******************************************************************/
691   // The above was broken, though seems intent to insert a new patient_data
692   // row for each update.  A good idea, but nothing is doing that yet so
693   // the code below does not yet attempt it.
695   $new['DOB'] = fixDate($new['DOB']);
697   if ($create) {
698     $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
699     foreach ($new as $key => $value) {
700       if ($key == 'id') continue;
701       $sql .= ", $key = '$value'";
702     }
703     $db_id = sqlInsert($sql);
704   }
705   else {
706     $db_id = $new['id'];
707     $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
708     // Check for brain damage:
709     if ($pid != $rez['pid']) {
710       $errmsg = "Internal error: Attempt to change patient data with pid = '" .
711         $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
712       die($errmsg);
713     }
714     $sql = "UPDATE patient_data SET date = NOW()";
715     foreach ($new as $key => $value) {
716       $sql .= ", $key = '$value'";
717     }
718     $sql .= " WHERE id = '$db_id'";
719     sqlStatement($sql);
720   }
722   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
723   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
724     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
725     $rez['phone_cell'],$rez['email'],$rez['pid']);
727   return $db_id;
730 function newEmployerData(    $pid,
731                 $name = "",
732                 $street = "",
733                 $postal_code = "",
734                 $city = "",
735                 $state = "",
736                 $country = ""
737             )
739     return sqlInsert("insert into employer_data set
740         name='$name',
741         street='$street',
742         postal_code='$postal_code',
743         city='$city',
744         state='$state',
745         country='$country',
746         pid='$pid',
747         date=NOW()
748         ");
751 // Create or update employer data from an array.
753 function updateEmployerData($pid, $new, $create=false)
755   $colnames = array('name','street','city','state','postal_code','country');
757   if ($create) {
758     $set .= "pid = '$pid', date = NOW()";
759     foreach ($colnames as $key) {
760       $value = isset($new[$key]) ? $new[$key] : '';
761       $set .= ", $key = '$value'";
762     }
763     return sqlInsert("INSERT INTO employer_data SET $set");
764   }
765   else {
766     $set = '';
767     $old = getEmployerData($pid);
768     $modified = false;
769     foreach ($colnames as $key) {
770       $value = empty($old[$key]) ? '' : addslashes($old[$key]);
771       if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
772         $value = $new[$key];
773         $modified = true;
774       }
775       $set .= "$key = '$value', ";
776     }
777     if ($modified) {
778       $set .= "pid = '$pid', date = NOW()";
779       return sqlInsert("INSERT INTO employer_data SET $set");
780     }
781     return $old['id'];
782   }
785 // This updates or adds the given insurance data info, while retaining any
786 // previously added insurance_data rows that should be preserved.
787 // This does not directly support the maintenance of non-current insurance.
789 function newInsuranceData(
790   $pid,
791   $type = "",
792   $provider = "",
793   $policy_number = "",
794   $group_number = "",
795   $plan_name = "",
796   $subscriber_lname = "",
797   $subscriber_mname = "",
798   $subscriber_fname = "",
799   $subscriber_relationship = "",
800   $subscriber_ss = "",
801   $subscriber_DOB = "",
802   $subscriber_street = "",
803   $subscriber_postal_code = "",
804   $subscriber_city = "",
805   $subscriber_state = "",
806   $subscriber_country = "",
807   $subscriber_phone = "",
808   $subscriber_employer = "",
809   $subscriber_employer_street = "",
810   $subscriber_employer_city = "",
811   $subscriber_employer_postal_code = "",
812   $subscriber_employer_state = "",
813   $subscriber_employer_country = "",
814   $copay = "",
815   $subscriber_sex = "",
816   $effective_date = "0000-00-00",
817   $accept_assignment = "TRUE")
819   if (strlen($type) <= 0) return FALSE;
821   // If a bad date was passed, err on the side of caution.
822   $effective_date = fixDate($effective_date, date('Y-m-d'));
824   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
825     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
826   $idrow = sqlFetchArray($idres);
828   // Replace the most recent entry in any of the following cases:
829   // * Its effective date is >= this effective date.
830   // * It is the first entry and it has no (insurance) provider.
831   // * There is no encounter that is earlier than the new effective date but
832   //   on or after the old effective date.
833   // Otherwise insert a new entry.
835   $replace = false;
836   if ($idrow) {
837     if (strcmp($idrow['date'], $effective_date) > 0) {
838       $replace = true;
839     }
840     else {
841       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
842         $replace = true;
843       }
844       else {
845         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
846           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
847           "date >= '" . $idrow['date'] . " 00:00:00'");
848         if ($ferow['count'] == 0) $replace = true;
849       }
850     }
851   }
853   if ($replace) {
855     // TBD: This is a bit dangerous in that a typo in entering the effective
856     // date can wipe out previous insurance history.  So we want some data
857     // entry validation somewhere.
858     sqlStatement("DELETE FROM insurance_data WHERE " .
859       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
860       "id != " . $idrow['id']);
862     $data = array();
863     $data['type'] = $type;
864     $data['provider'] = $provider;
865     $data['policy_number'] = $policy_number;
866     $data['group_number'] = $group_number;
867     $data['plan_name'] = $plan_name;
868     $data['subscriber_lname'] = $subscriber_lname;
869     $data['subscriber_mname'] = $subscriber_mname;
870     $data['subscriber_fname'] = $subscriber_fname;
871     $data['subscriber_relationship'] = $subscriber_relationship;
872     $data['subscriber_ss'] = $subscriber_ss;
873     $data['subscriber_DOB'] = $subscriber_DOB;
874     $data['subscriber_street'] = $subscriber_street;
875     $data['subscriber_postal_code'] = $subscriber_postal_code;
876     $data['subscriber_city'] = $subscriber_city;
877     $data['subscriber_state'] = $subscriber_state;
878     $data['subscriber_country'] = $subscriber_country;
879     $data['subscriber_phone'] = $subscriber_phone;
880     $data['subscriber_employer'] = $subscriber_employer;
881     $data['subscriber_employer_city'] = $subscriber_employer_city;
882     $data['subscriber_employer_street'] = $subscriber_employer_street;
883     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
884     $data['subscriber_employer_state'] = $subscriber_employer_state;
885     $data['subscriber_employer_country'] = $subscriber_employer_country;
886     $data['copay'] = $copay;
887     $data['subscriber_sex'] = $subscriber_sex;
888     $data['pid'] = $pid;
889     $data['date'] = $effective_date;
890     $data['accept_assignment'] = $accept_assignment;
891     updateInsuranceData($idrow['id'], $data);
892     return $idrow['id'];
893   }
894   else {
895     return sqlInsert("INSERT INTO insurance_data SET
896       type = '$type',
897       provider = '$provider',
898       policy_number = '$policy_number',
899       group_number = '$group_number',
900       plan_name = '$plan_name',
901       subscriber_lname = '$subscriber_lname',
902       subscriber_mname = '$subscriber_mname',
903       subscriber_fname = '$subscriber_fname',
904       subscriber_relationship = '$subscriber_relationship',
905       subscriber_ss = '$subscriber_ss',
906       subscriber_DOB = '$subscriber_DOB',
907       subscriber_street = '$subscriber_street',
908       subscriber_postal_code = '$subscriber_postal_code',
909       subscriber_city = '$subscriber_city',
910       subscriber_state = '$subscriber_state',
911       subscriber_country = '$subscriber_country',
912       subscriber_phone = '$subscriber_phone',
913       subscriber_employer = '$subscriber_employer',
914       subscriber_employer_city = '$subscriber_employer_city',
915       subscriber_employer_street = '$subscriber_employer_street',
916       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
917       subscriber_employer_state = '$subscriber_employer_state',
918       subscriber_employer_country = '$subscriber_employer_country',
919       copay = '$copay',
920       subscriber_sex = '$subscriber_sex',
921       pid = '$pid',
922       date = '$effective_date',
923       accept_assignment = '$accept_assignment'
924     ");
925   }
928 // This is used internally only.
929 function updateInsuranceData($id, $new)
931   $fields = sqlListFields("insurance_data");
932   $use = array();
934   while(list($key, $value) = each ($new)) {
935     if (in_array($key, $fields)) {
936       $use[$key] = $value;
937     }
938   }
940   $sql = "UPDATE insurance_data SET ";
941   while(list($key, $value) = each($use))
942     $sql .= $key . " = '$value', ";
943   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
945   sqlStatement($sql);
948 function newHistoryData($pid, $new=false) {
949   $sql = "insert into history_data set pid = '$pid', date = NOW()";
950   if ($new) {
951     while(list($key, $value) = each($new)) {
952       if (!get_magic_quotes_gpc()) $value = addslashes($value);
953       $sql .= ", $key = '$value'";
954     }
955   }
956   return sqlInsert($sql);
959 function updateHistoryData($pid,$new)
961         $real = getHistoryData($pid);
962         while(list($key, $value) = each ($new))
963                 $real[$key] = $value;
964         $real['date'] = "'+NOW()+'";
965         $real['id'] = "";
967         $sql = "insert into history_data set ";
968         while(list($key, $value) = each($real))
969                 $sql .= $key." = '$value', ";
970         $sql = substr($sql, 0, -2);
973         return sqlInsert($sql);
976 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
977                 $phone_biz,$phone_cell,$email,$pid="")
979     if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
980     if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
982     $db = $GLOBALS['adodb']['db'];
983     $customer_info = array();
985     $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
986     $result = $db->Execute($sql);
987     if ($result && !$result->EOF) {
988         $customer_info['foreign_update'] = true;
989         $customer_info['foreign_id'] = $result->fields['foreign_id'];
990         $customer_info['foreign_table'] = $result->fields['foreign_table'];
991     }
993     ///xml rpc code to connect to accounting package and add user to it
994     $customer_info['firstname'] = $fname;
995     $customer_info['lastname'] = $lname;
996     $customer_info['address'] = $street;
997     $customer_info['suburb'] = $city;
998     $customer_info['state'] = $state;
999     $customer_info['postcode'] = $postal_code;
1001     //ezybiz wants state as a code rather than abbreviation
1002     $customer_info['geo_zone_id'] = "";
1003     $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1004     $db = $GLOBALS['adodb']['db'];
1005     $result = $db->Execute($sql);
1006     if ($result && !$result->EOF) {
1007         $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1008     }
1010     //ezybiz wants country as a code rather than abbreviation
1011     $customer_info['geo_country_id'] = "";
1012     $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1013     $db = $GLOBALS['adodb']['db'];
1014     $result = $db->Execute($sql);
1015     if ($result && !$result->EOF) {
1016         $customer_info['geo_country_id'] = $result->fields['countries_id'];
1017     }
1019     $customer_info['phone1'] = $phone_home;
1020     $customer_info['phone1comment'] = "Home Phone";
1021     $customer_info['phone2'] = $phone_biz;
1022     $customer_info['phone2comment'] = "Business Phone";
1023     $customer_info['phone3'] = $phone_cell;
1024     $customer_info['phone3comment'] = "Cell Phone";
1025     $customer_info['email'] = $email;
1026     $customer_info['customernumber'] = $pid;
1028     $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1029     $ws = new WSWrapper($function);
1031     // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1032     if (is_numeric($ws->value)) {
1033         $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1034         $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1035     }
1038 // Returns Age 
1039 //   in months if < 2 years old
1040 //   in years  if > 2 years old
1041 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1042 // (optional) nowYMD is a date in YYYYMMDD format
1043 function getPatientAge($dobYMD, $nowYMD=null)
1045     // strip any dashes from the DOB
1046     $dobYMD = preg_replace("/-/", "", $dobYMD);
1047     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1048     
1049     // set the 'now' date values
1050     if ($nowYMD == null) {
1051         $nowDay = date("d");
1052         $nowMonth = date("m");
1053         $nowYear = date("Y");
1054     }
1055     else {
1056         $nowDay = substr($nowYMD,6,2);
1057         $nowMonth = substr($nowYMD,4,2);
1058         $nowYear = substr($nowYMD,0,4);
1059     }
1061     $dayDiff = $nowDay - $dobDay;
1062     $monthDiff = $nowMonth - $dobMonth;
1063     $yearDiff = $nowYear - $dobYear;
1065     $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1067     if ( $ageInMonths > 24 ) {
1068         $age = $yearDiff;
1069         if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1070         else if ($monthDiff < 0) { $age -= 1; }
1071     }
1072     else  {
1073         $age = "$ageInMonths month"; 
1074     }
1076     return $age;
1079 function dateToDB ($date)
1081     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1082     return $date;
1086 // ----------------------------------------------------------------------------
1088  * DROPDOWN FOR COUNTRIES
1089  * 
1090  * build a dropdown with all countries from geo_country_reference
1091  * 
1092  * @param int $selected - id for selected record
1093  * @param string $name - the name/id for select form
1094  * @return void - just echo the html encoded string
1095  */
1096 function dropdown_countries($selected = 0, $name = 'country_code') {
1097     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1099     $string = "<select name='$name' id='$name'>";
1100     while ( $row = sqlFetchArray($r) ) {
1101         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1102         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1103     }
1105     $string .= '</select>';
1106     echo $string;
1110 // ----------------------------------------------------------------------------
1112  * DROPDOWN FOR YES/NO
1113  * 
1114  * build a dropdown with two options (yes - 1, no - 0)
1115  * 
1116  * @param int $selected - id for selected record
1117  * @param string $name - the name/id for select form
1118  * @return void - just echo the html encoded string 
1119  */
1120 function dropdown_yesno($selected = 0, $name = 'yesno') {
1121     $string = "<select name='$name' id='$name'>";
1123     $selected = (int)$selected;
1124     if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1125     else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1127     $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1128     $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1129     $string .= '</select>';
1131     echo $string;
1134 // ----------------------------------------------------------------------------
1136  * DROPDOWN FOR MALE/FEMALE options
1137  * 
1138  * build a dropdown with three options (unselected/male/female)
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_sex($selected = 0, $name = 'sex') {
1145     $string = "<select name='$name' id='$name'>";
1147     if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1148     else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1149     else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1151     $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1152     $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1153     $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1154     $string .= '</select>';
1156     echo $string;
1159 // ----------------------------------------------------------------------------
1161  * DROPDOWN FOR MARITAL STATUS
1162  * 
1163  * build a dropdown with marital status
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_marital($selected = 0, $name = 'status') {
1170     $string = "<select name='$name' id='$name'>";
1172     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1174     foreach ( $statii as $st ) {
1175         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1176         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1177     }
1179     $string .= '</select>';
1181     echo $string;
1184 // ----------------------------------------------------------------------------
1186  * DROPDOWN FOR PROVIDERS
1187  * 
1188  * build a dropdown with all providers
1189  * 
1190  * @param int $selected - id for selected record
1191  * @param string $name - the name/id for select form
1192  * @return void - just echo the html encoded string
1193  */
1194 function dropdown_providers($selected = 0, $name = 'status') {
1195     $provideri = getProviderInfo();
1197     $string = "<select name='$name' id='$name'>";
1198     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1199     foreach ( $provideri as $s ) {
1200         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1201         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1202     }
1204     $string .= '</select>';
1206     echo $string;
1209 // ----------------------------------------------------------------------------
1211  * DROPDOWN FOR INSURANCE COMPANIES
1212  * 
1213  * build a dropdown with all insurers
1214  * 
1215  * @param int $selected - id for selected record
1216  * @param string $name - the name/id for select form
1217  * @return void - just echo the html encoded string
1218  */
1219 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1220     $insurancei = getInsuranceProviders();
1222     $string = "<select name='$name' id='$name'>";
1223     $string .= '<option value="0">Onbekend</option>';
1224     foreach ( $insurancei as $iid => $iname ) {
1225         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1226         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1227     }
1229     $string .= '</select>';
1231     echo $string;
1235 // ----------------------------------------------------------------------------
1237  * COUNTRY CODE
1238  * 
1239  * return the name or the country code, function of arguments
1240  * 
1241  * @param int $country_code
1242  * @param string $country_name
1243  * @return string | int - name or code
1244  */
1245 function country_code($country_code = 0, $country_name = '') {
1246     $strint = '';
1247     if ( $country_code ) {
1248         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1249     } else {
1250         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1251     }
1253     $db = $GLOBALS['adodb']['db'];
1254     $result = $db->Execute($sql);
1255     if ($result && !$result->EOF) {
1256         $strint = $result->fields['res'];
1257     }
1259     return $strint;
1262 // ----------------------------------------------------------------------------
1264  * GET INSURANCE DATA
1265  * (Dutch usage)
1266  * 
1267  * return the insurer(s) and some patient
1268  * 
1269  * @param int $pid - patient id
1270  * @param int $current 1-current 0-all insurers
1271  * @return array
1272  */
1273 function get_insurers_nl($pid = 0, $current = 1) {
1274     if ( !$pid ) return FALSE;
1276     $join = 'insurance_companies ic ON ic.id = pi.pin_provider';
1277     $r = dsql_select('*', 'patient_insurers_NL pi', array('pin_pid' => $pid), 'pin_date DESC', $join);
1279     while ( $row = mysql_fetch_array($r) ) {
1280         $rez[] = $row;
1281     } // while
1283     return ( $current ? $rez[0] : $rez );
1287 // ----------------------------------------------------------------------------
1289  * SET INSURANCE DATA
1290  * (Dutch usage)
1291  * 
1292  * set the insurer for a patient
1293  * 
1294  * @param int $pid - patient id
1295  * @param int $insid - insurer id
1296  * @return void
1297  */
1298 function set_insurer_nl($pid = 0, $insid = 0, $date = '', $policy = '') {
1299     if ( !$pid || !$insid || ($date == '0000-00-00') ) return FALSE;
1301     $fields = array('pin_pid', 'pin_provider', 'pin_date', 'pin_policy');
1302     $values = array($pid, $insid, $date, $policy);
1303     dsql_insert('patient_insurers_NL', $fields, $values);
1306 // ----------------------------------------------------------------------------
1308  * FIND THE INSURERS STATUS FOR A PATIENT
1309  * (Dutch usage)
1310  * 
1311  * return the answer for the question: is this the first insurer or not?
1312  * 
1313  * @param int $pid - patient id
1314  * @return int - the number of insurer records ( 0 - no insurer; >0 some insurers)
1315  */
1316 function total_insurers($pid = 0) {
1317     if ( !$pid ) return FALSE;
1319     $r = dsql_select('COUNT(*) AS c', 'patient_insurers_NL', array('pin_pid' => $pid));
1320     $row = mysql_fetch_array($r);
1322     return $row['c'];
1325 function DBToDate ($date)
1327     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1328     return $date;
1331 function get_patient_balance($pid) {
1332   if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1333     $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1334       "pid = '$pid' AND activity = 1");
1335     $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1336       "pid = '$pid'");
1337     $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1338       "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1339       "pid = '$pid'");
1340     return sprintf('%01.2f', $brow['amount'] + $srow['amount']
1341       - $drow['payments'] - $drow['adjustments']);
1342   }
1343   else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1344     // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1345     $conn = $GLOBALS['adodb']['db'];
1346     $customer_info['id'] = 0;
1347     $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1348       "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1349       "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1350       "im.foreign_table = 'customer'";
1351     $result = $conn->Execute($sql);
1352     if($result && !$result->EOF) {
1353       $customer_info['id'] = $result->fields['foreign_id'];
1354     }
1355     $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1356     $ws = new WSWrapper($function);
1357     if(is_numeric($ws->value)) {
1358       return sprintf('%01.2f', $ws->value);
1359     }
1360   }
1361   return '';