internationalization of referral form
[openemr.git] / library / patient.inc
blob983ac49757d1474f46c5ceb44aed2ba372f12a19
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       $param1 = " AND authorized = 1 AND calendar = 1 ";
149     }
151     //--------------------------------
152     //(CHEMED) facility filter
153     $param2 = "";
154     if ($facility) {
155         // $param2 = " AND facility_id = $facility ";
156         $param2 = " AND (facility_id = $facility 
157           OR  $facility IN
158                 (select facility_id 
159                 from users_facility
160                 where tablename = 'users'
161                 and table_id = id)
162                 )
163           ";
164     }
165     //--------------------------------
167     $command = "=";
168     if ($providerID == "%") {
169         $command = "like";
170     }
171     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
172         "from users where username != '' and active = 1 and id $command '" .
173         mysql_real_escape_string($providerID) . "' " . $param1 . $param2;
174     // sort by last name -- JRM June 2008
175     $query .= " ORDER BY lname, fname ";
176     $rez = sqlStatement($query);
177     for($iter=0; $row=sqlFetchArray($rez); $iter++)
178         $returnval[$iter]=$row;
180     //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
181     //accessible from $resultval['key']
183     if($iter==1) {
184         $akeys = array_keys($returnval[0]);
185         foreach($akeys as $key) {
187             $returnval[0][$key] = $returnval[0][$key];
188         }
189     }
190     return $returnval;
193 //same as above but does not reduce if only 1 row returned
194 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
195     $param1 = "";
196     if ($providers_only) {
197         $param1 = "AND authorized=1";
198     }
199     $command = "=";
200     if ($providerID == "%") {
201         $command = "like";
202     }
203     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
204         "from users where active = 1 and username != '' and id $command '" .
205         mysql_real_escape_string($providerID) . "' " . $param1;
207     $rez = sqlStatement($query);
208     for($iter=0; $row=sqlFetchArray($rez); $iter++)
209         $returnval[$iter]=$row;
211     return $returnval;
214 function getProviderName($providerID) {
215     $pi = getProviderInfo($providerID);
216     if (strlen($pi[0]["lname"]) > 0) {
217         return $pi[0]['fname'] . " " . $pi[0]['lname'];
218     }
219     return "";
222 function getProviderId($providerName) {
223     $query = "select id from users where username = '". mysql_real_escape_string($providerName)."'";
224     $rez = sqlStatement($query);
225     for($iter=0; $row=sqlFetchArray($rez); $iter++)
226         $returnval[$iter]=$row;
227     return $returnval;
230 function getEthnoRacials() {
231     $returnval = array("");
232     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
233     $rez = sqlStatement($sql);
234     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
235         if (($row["ethnoracial"] != "")) {
236             array_push($returnval, $row["ethnoracial"]);
237         }
238     }
239     return $returnval;
242 function getHistoryData($pid, $given = "*")
244     $sql = "select $given from history_data where pid='$pid' order by date DESC limit 0,1";
245     return sqlQuery($sql);
248 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
249 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
251   $sql = "select $given from insurance_data as insd " .
252     "left join insurance_companies as ic on ic.id = insd.provider " .
253     "where pid = '$pid' and type = '$type' order by date DESC limit 1";
254   return sqlQuery($sql);
257 function getInsuranceDataByDate($pid, $date, $type,
258   $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
259 { // this must take the date in the following manner: YYYY-MM-DD
260   // this function recalls the insurance value that was most recently enterred from the
261   // given date. it will call up most recent records up to and on the date given,
262   // but not records enterred after the given date
263   $sql = "select $given from insurance_data as insd " .
264     "left join insurance_companies as ic on ic.id = provider " .
265     "where pid = '$pid' and date_format(date,'%Y-%m-%d') <= '$date' and " .
266     "type='$type' order by date DESC limit 1";
267   return sqlQuery($sql);
270 function getEmployerData($pid, $given = "*")
272     $sql = "select $given from employer_data where pid='$pid' order by date DESC limit 0,1";
273     return sqlQuery($sql);
276 function _set_patient_inc_count($limit, $count, $where) {
277   // When the limit is exceeded, find out what the unlimited count would be.
278   $GLOBALS['PATIENT_INC_COUNT'] = $count;
279   // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
280   if ($limit != "all") {
281     $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where");
282     $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
283   }
286 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")
288     // Allow the last name to be followed by a comma and some part of a first name.
289     // New behavior for searches:
290     // Allows comma alone followed by some part of a first name
291     // If the first letter of either name is capital, searches for name starting
292     // with given substring (the expected behavior).  If it is lower case, it
293     // it searches for the substring anywhere in the name.  This applies to either
294     // last name or first name or both.  The arbitrary limit of 100 results is set
295     // in the sql query below. --Mark Leeds
296     $lname = trim($lname);
297     $fname = '';
298      if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
299          $lname = trim($matches[1]);
300          $fname = trim($matches[2]);
301     }
302     $search_for_pieces1 = '';
303     $search_for_pieces2 = '';
304     if ($lname{0} != strtoupper($lname{0})) {$search_for_pieces1 = '%';}
305     if ($fname{0} != strtoupper($fname{0})) {$search_for_pieces2 = '%';}
307     $where = "lname LIKE '" . $search_for_pieces1 . "$lname%' " .
308         "AND fname LIKE '" . $search_for_pieces2 . "$fname%' ";
309         if (!empty($GLOBALS['pt_restrict_field'])) {
310                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
311                         $where .= "AND ( patient_data.".$GLOBALS['pt_restrict_field']." = ( SELECT facility_id FROM users WHERE username = '".$_SESSION{"authUser"}."') OR patient_data.".$GLOBALS['pt_restrict_field']." = '' ) ";
312                 }
313         }
315     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
316     if ($limit != "all") $sql .= " LIMIT $start, $limit";
318     $rez = sqlStatement($sql);
320     for($iter=0; $row=sqlFetchArray($rez); $iter++)
321         $returnval[$iter] = $row;
323     _set_patient_inc_count($limit, count($returnval), $where);
324     return $returnval;
327 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")
329     
330     $where = "pubpid LIKE '$pid%' ";
331         if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
332                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
333                         $where .= "AND ( patient_data.".$GLOBALS['pt_restrict_field']." = ( SELECT facility_id FROM users WHERE username = '".$_SESSION{"authUser"}."') OR patient_data.".$GLOBALS['pt_restrict_field']." = '' ) ";
334                 }
335         }
337     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
338     if ($limit != "all") $sql .= " limit $start, $limit";
339     $rez = sqlStatement($sql);
340     for($iter=0; $row=sqlFetchArray($rez); $iter++)
341         $returnval[$iter]=$row;
343     _set_patient_inc_count($limit, count($returnval), $where);
344     return $returnval;
347 function getByPatientDemographics($searchTerm = "%", $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
349         $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like ('%Employer%' ) AND uor !=0" );
351     $where = "";
352     for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
353         if ( $iter > 0 ) {
354            $where .= " or ";
355         }
356         $where .= " ".$row["field_id"]." like '%".$searchTerm."%' ";
357     }
359     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
360     if ($limit != "all") $sql .= " limit $start, $limit";
361     $rez = sqlStatement($sql);
362     for($iter=0; $row=sqlFetchArray($rez); $iter++)
363         $returnval[$iter]=$row;
365     _set_patient_inc_count($limit, count($returnval), $where);
366     return $returnval;
369 function getByPatientDemographicsFilter($searchFields, $searchTerm = "%", $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS", $orderby = "lname ASC, fname ASC", $limit="all", $start="0" )
371         $layoutCols = split( '~', $searchFields );
373     $where = "";
374     $i = 0;
375     foreach ($layoutCols as $val ) {
376                 if ( $i > 0 ) {
377                    $where .= " or ";
378                 }
379                 $where .= " ".$val." like '%".$searchTerm."%' ";
380                 $i++;
381         }
383     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
384     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;
394 // return a collection of Patient PIDs
395 // new arg style by JRM March 2008
396 // 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")
397 function getPatientPID($args)
399     $pid = "%";
400     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
401     $orderby = "lname ASC, fname ASC";
402     $limit="all";
403     $start="0";
405     // alter default values if defined in the passed in args
406     if (isset($args['pid'])) { $pid = $args['pid']; }
407     if (isset($args['given'])) { $given = $args['given']; }
408     if (isset($args['orderby'])) { $orderby = $args['orderby']; }
409     if (isset($args['limit'])) { $limit = $args['limit']; }
410     if (isset($args['start'])) { $start = $args['start']; }
412     $command = "=";
413     if ($pid == -1) $pid = "%";
414     elseif (empty($pid)) $pid = "NULL";
416     if (strstr($pid,"%")) $command = "like";
418     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
419     if ($limit != "all") $sql .= " limit $start, $limit";
421     $rez = sqlStatement($sql);
422     for($iter=0; $row=sqlFetchArray($rez); $iter++)
423         $returnval[$iter]=$row;
425     return $returnval;
428 /* return a patient's name in the format LAST, FIRST */
429 function getPatientName($pid) {
430     if (empty($pid)) return "";
431     $patientData = getPatientPID(array("pid"=>$pid));
432     if (empty($patientData[0]['lname'])) return "";
433     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
434     return $patientName;
437 /* find patient data by DOB */
438 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
440     $DOB = fixDate($DOB, $DOB);
441     $where = "DOB like '$DOB%' ";
442         if (!empty($GLOBALS['pt_restrict_field'])) {
443                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
444                         $where .= "AND ( patient_data.".$GLOBALS['pt_restrict_field']." = ( SELECT facility_id FROM users WHERE username = '".$_SESSION{"authUser"}."') OR patient_data.".$GLOBALS['pt_restrict_field']." = '' ) ";
445                 }
446         }
448     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
450     if ($limit != "all") $sql .= " LIMIT $start, $limit";
452     $rez = sqlStatement($sql);
453     for($iter=0; $row=sqlFetchArray($rez); $iter++)
454         $returnval[$iter]=$row;
456     _set_patient_inc_count($limit, count($returnval), $where);
457     return $returnval;
460 /* find patient data by SSN */
461 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
463     $where = "ss LIKE '$ss%'";
464     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
465     if ($limit != "all") $sql .= " LIMIT $start, $limit";
467     $rez = sqlStatement($sql);
468     for($iter=0; $row=sqlFetchArray($rez); $iter++)
469         $returnval[$iter]=$row;
471     _set_patient_inc_count($limit, count($returnval), $where);
472     return $returnval;
475 //(CHEMED) Search by phone number
476 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
478     $phone = ereg_replace( "[[:punct:]]","", $phone );
479     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP '$phone'";
480     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
481     if ($limit != "all") $sql .= " LIMIT $start, $limit";
483     $rez = sqlStatement($sql);
484     for($iter=0; $row=sqlFetchArray($rez); $iter++)
485         $returnval[$iter]=$row;
487     _set_patient_inc_count($limit, count($returnval), $where);
488     return $returnval;
491 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
493     $sql="select $given from patient_data order by $orderby";
495     if ($limit != "all")
496         $sql .= " limit $start, $limit";
498     $rez = sqlStatement($sql);
499     for($iter=0; $row=sqlFetchArray($rez); $iter++)
500         $returnval[$iter]=$row;
502     return $returnval;
505 //----------------------input functions
506 function newPatientData(    $db_id="",
507                 $title = "",
508                 $fname = "",
509                 $lname = "",
510                 $mname = "",
511                 $sex = "",
512                 $DOB = "",
513                 $street = "",
514                 // DBC dutch use
515                 $nstreet = "",
516                 $nnr = "",
517                 $nadd = "",
518                 // EOS DBC
519                 $postal_code = "",
520                 $city = "",
521                 $state = "",
522                 $country_code = "",
523                 $ss = "",
524                 $occupation = "",
525                 $phone_home = "",
526                 $phone_biz = "",
527                 $phone_contact = "",
528                 $status = "",
529                 $contact_relationship = "",
530                 $referrer = "",
531                 $referrerID = "",
532                 $email = "",
533                 $language = "",
534                 $ethnoracial = "",
535                 $interpretter = "",
536                 $migrantseasonal = "",
537                 $family_size = "",
538                 $monthly_income = "",
539                 $homeless = "",
540                 $financial_review = "",
541                 $pubpid = "",
542                 $pid = "MAX(pid)+1",
543                 $providerID = "",
544                 $genericname1 = "",
545                 $genericval1 = "",
546                 $genericname2 = "",
547                 $genericval2 = "",
548                 $phone_cell = "",
549                 $hipaa_mail = "",
550                 $hipaa_voice = "",
551                 $squad = 0,
552                 $pharmacy_id = 0,
553                 $drivers_license = "",
554                 $hipaa_notice = "",
555                 $hipaa_message = "",
556                 $regdate = "",
557                 // dutch specific
558                 $prefixlast = "",
559                 $prefixlastpartner = "",
560                 $lastpartner = "",
561                 $initials = "",
562                 $provider_data = array(),
563                 $referer_data = array()
564                 // DBC Dutch System
566             )
568     $DOB = fixDate($DOB);
569     $regdate = fixDate($regdate);
571     $fitness = 0;
572     $referral_source = '';
573     if ($pid) {
574         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
575         // Check for brain damage:
576         if ($db_id != $rez['id']) {
577             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
578               $rez['id'] . "' to '$db_id' for pid '$pid'";
579             die($errmsg);
580         }
581         $fitness = $rez['fitness'];
582         $referral_source = $rez['referral_source'];
583     }
585     // Get the default price level.
586     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
587       "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
588     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
590     $query = ("replace into patient_data set
591         id='$db_id',
592         title='$title',
593         fname='$fname',
594         lname='$lname',
595         mname='$mname',
596         sex='$sex',
597         DOB='$DOB',
598         street='$street',
599         postal_code='$postal_code',
600         city='$city',
601         state='$state',
602         country_code='$country_code',
603         drivers_license='$drivers_license',
604         ss='$ss',
605         occupation='$occupation',
606         phone_home='$phone_home',
607         phone_biz='$phone_biz',
608         phone_contact='$phone_contact',
609         status='$status',
610         contact_relationship='$contact_relationship',
611         referrer='$referrer',
612         referrerID='$referrerID',
613         email='$email',
614         language='$language',
615         ethnoracial='$ethnoracial',
616         interpretter='$interpretter',
617         migrantseasonal='$migrantseasonal',
618         family_size='$family_size',
619         monthly_income='$monthly_income',
620         homeless='$homeless',
621         financial_review='$financial_review',
622         pubpid='$pubpid',
623         pid = $pid,
624         providerID = '$providerID',
625         genericname1 = '$genericname1',
626         genericval1 = '$genericval1',
627         genericname2 = '$genericname2',
628         genericval2 = '$genericval2',
629         phone_cell = '$phone_cell',
630         pharmacy_id = '$pharmacy_id',
631         hipaa_mail = '$hipaa_mail',
632         hipaa_voice = '$hipaa_voice',
633         hipaa_notice = '$hipaa_notice',
634         hipaa_message = '$hipaa_message',
635         squad = '$squad',
636         fitness='$fitness',
637         referral_source='$referral_source',
638         regdate='$regdate',
639         pricelevel='$pricelevel',
640         date=NOW()");
642     $id = sqlInsert($query);
644     // DBC 
645     if ( !$db_id ) {
646       // find the last inserted id for new patient case
647       $db_id = empty($GLOBALS['dutchpc']) ? mysql_insert_id() : dsql_lastid();
648     }
649     // EOS DBC
651     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
653          // dutch use
654         if ( $GLOBALS['dutchpc'] ) {
655                 $init = strtoupper(preg_replace('/[\s\.\-_0-9]/','',$initials));
656                 
657             $querynl = ("REPLACE INTO patient_data_NL SET
658                     pdn_id = '$db_id',
659                     pdn_pxlast = '$prefixlast',
660                     pdn_pxlastpar = '$prefixlastpartner',
661                     pdn_lastpar = '$lastpartner',
662                     pdn_street = '$nstreet',
663                     pdn_number = '$nnr',
664                     pdn_addition = '$nadd',
665                     pdn_initials = '$init'
666             ");
668             if ( $db_id ) $idnl = sqlInsert($querynl); // only if exists
669         }
670         // EOS dutch use
673        // DBC Dutch System
674         // provider first
675         if ( $GLOBALS['dutchpc'] && $db_id && $provider_data && $referer_data) {
676            $querypr = ("INSERT INTO cl_providers(pro_pid, pro_company, pro_initials, pro_prefix, pro_lname,
677                    pro_street, pro_number, pro_addition, pro_city, pro_zipcode,  pro_phone, pro_fax, pro_email, pro_referer ) 
678                    VALUES ($db_id, '{$provider_data['pro_company']}', '{$provider_data['pro_initials']}',
679                   '{$provider_data['pro_prefix']}', '{$provider_data['pro_lname']}',  
680                   '{$provider_data['pro_street']}', '{$provider_data['pro_number']}', '{$provider_data['pro_addition']}', 
681                   '{$provider_data['pro_city']}',  '{$provider_data['pro_zipcode']}',
682                   '{$provider_data['pro_phone']}', '{$provider_data['pro_fax']}',  '{$provider_data['pro_email']}', 
683                   '{$provider_data['pro_referer']}') 
684                   ON DUPLICATE KEY UPDATE  pro_referer = '{$provider_data['pro_referer']}',
685                   pro_company = '{$provider_data['pro_company']}', pro_initials = '{$provider_data['pro_initials']}',
686                   pro_prefix = '{$provider_data['pro_prefix']}',
687                   pro_lname = '{$provider_data['pro_lname']}', pro_street = '{$provider_data['pro_street']}',
688                   pro_number = '{$provider_data['pro_number']}', pro_addition = '{$provider_data['pro_addition']}',
689                   pro_city = '{$provider_data['pro_city']}', pro_zipcode = '{$provider_data['pro_zipcode']}',
690                   pro_phone = '{$provider_data['pro_phone']}', pro_fax = '{$provider_data['pro_fax']}',
691                   pro_email = '{$provider_data['pro_email']}'
692             ");
693            $idpr = sqlInsert($querypr);
695         // referer if it's the case
696         if ( $referer_data['ref_code'] ) {
697            $queryre = ("INSERT INTO cl_referers(ref_pid, ref_code, ref_company, ref_initials, ref_prefix,
698                    ref_lname, ref_street, ref_number, ref_addition, ref_city, ref_zipcode,  ref_phone, ref_fax,
699                    ref_email) 
700                    VALUES ($db_id, {$referer_data['ref_code']}, '{$referer_data['ref_company']}', 
701                    '{$referer_data['ref_initials']}', '{$referer_data['ref_prefix']}',
702                    '{$referer_data['ref_lname']}', '{$referer_data['ref_street']}', '{$referer_data['ref_number']}', 
703                    '{$referer_data['ref_addition']}', '{$referer_data['ref_city']}', '{$referer_data['ref_zipcode']}',
704                   '{$referer_data['ref_phone']}', '{$referer_data['ref_fax']}',  '{$referer_data['ref_email']}')
705                   ON DUPLICATE KEY UPDATE ref_code = {$referer_data['ref_code']},
706                   ref_company = '{$referer_data['ref_company']}', ref_initials = '{$referer_data['ref_initials']}',
707                   ref_prefix = '{$referer_data['ref_prefix']}',
708                   ref_lname = '{$referer_data['ref_lname']}', ref_street = '{$referer_data['ref_street']}',
709                   ref_number = '{$referer_data['ref_number']}', ref_addition = '{$referer_data['ref_addition']}',
710                   ref_city = '{$referer_data['ref_city']}', ref_zipcode = '{$referer_data['ref_zipcode']}',
711                   ref_phone = '{$referer_data['ref_phone']}', ref_fax = '{$referer_data['ref_fax']}',
712                   ref_email = '{$referer_data['ref_email']}'
713             ");
714            $idre = sqlInsert($queryre);
715         } 
716         } // if globals
717         // EOS DBC
719     sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
720                 $phone_biz,$phone_cell,$email,$pid);
722     return $foo['pid'];
725 // Supported input date formats are:
726 //   mm/dd/yyyy
727 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
728 //   yyyy/mm/dd
729 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
731 function fixDate($date, $default="0000-00-00") {
732     $fixed_date = $default;
733     $date = trim($date);
734     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
735         $dmy = preg_split("'[/.-]'", $date);
736         if ($dmy[0] > 99) {
737             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
738         } else {
739             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
740               if ($dmy[2] < 1000) $dmy[2] += 1900;
741               if ($dmy[2] < 1910) $dmy[2] += 100;
742             }
743             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
744         }
745     }
747     return $fixed_date;
750 // Create or update patient data from an array.
752 function updatePatientData($pid, $new, $create=false)
754   /*******************************************************************
755     $real = getPatientData($pid);
756     $new['DOB'] = fixDate($new['DOB']);
757     while(list($key, $value) = each ($new))
758         $real[$key] = $value;
759     $real['date'] = "'+NOW()+'";
760     $real['id'] = "";
761     $sql = "insert into patient_data set ";
762     while(list($key, $value) = each($real))
763         $sql .= $key." = '$value', ";
764     $sql = substr($sql, 0, -2);
765     return sqlInsert($sql);
766   *******************************************************************/
768   // The above was broken, though seems intent to insert a new patient_data
769   // row for each update.  A good idea, but nothing is doing that yet so
770   // the code below does not yet attempt it.
772   $new['DOB'] = fixDate($new['DOB']);
774   if ($create) {
775     $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
776     foreach ($new as $key => $value) {
777       if ($key == 'id') continue;
778       $sql .= ", $key = '$value'";
779     }
780     $db_id = sqlInsert($sql);
781   }
782   else {
783     $db_id = $new['id'];
784     $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
785     // Check for brain damage:
786     if ($pid != $rez['pid']) {
787       $errmsg = "Internal error: Attempt to change patient data with pid = '" .
788         $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
789       die($errmsg);
790     }
791     $sql = "UPDATE patient_data SET date = NOW()";
792     foreach ($new as $key => $value) {
793       $sql .= ", $key = '$value'";
794     }
795     $sql .= " WHERE id = '$db_id'";
796     sqlStatement($sql);
797   }
799   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
800   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
801     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
802     $rez['phone_cell'],$rez['email'],$rez['pid']);
804   return $db_id;
807 function newEmployerData(    $pid,
808                 $name = "",
809                 $street = "",
810                 $postal_code = "",
811                 $city = "",
812                 $state = "",
813                 $country = ""
814             )
816     return sqlInsert("insert into employer_data set
817         name='$name',
818         street='$street',
819         postal_code='$postal_code',
820         city='$city',
821         state='$state',
822         country='$country',
823         pid='$pid',
824         date=NOW()
825         ");
828 // Create or update employer data from an array.
830 function updateEmployerData($pid, $new, $create=false)
832   $colnames = array('name','street','city','state','postal_code','country');
834   if ($create) {
835     $set .= "pid = '$pid', date = NOW()";
836     foreach ($colnames as $key) {
837       $value = isset($new[$key]) ? $new[$key] : '';
838       $set .= ", $key = '$value'";
839     }
840     return sqlInsert("INSERT INTO employer_data SET $set");
841   }
842   else {
843     $set = '';
844     $old = getEmployerData($pid);
845     $modified = false;
846     foreach ($colnames as $key) {
847       $value = empty($old[$key]) ? '' : addslashes($old[$key]);
848       if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
849         $value = $new[$key];
850         $modified = true;
851       }
852       $set .= "$key = '$value', ";
853     }
854     if ($modified) {
855       $set .= "pid = '$pid', date = NOW()";
856       return sqlInsert("INSERT INTO employer_data SET $set");
857     }
858     return $old['id'];
859   }
862 // This updates or adds the given insurance data info, while retaining any
863 // previously added insurance_data rows that should be preserved.
864 // This does not directly support the maintenance of non-current insurance.
866 function newInsuranceData(
867   $pid,
868   $type = "",
869   $provider = "",
870   $policy_number = "",
871   $group_number = "",
872   $plan_name = "",
873   $subscriber_lname = "",
874   $subscriber_mname = "",
875   $subscriber_fname = "",
876   $subscriber_relationship = "",
877   $subscriber_ss = "",
878   $subscriber_DOB = "",
879   $subscriber_street = "",
880   $subscriber_postal_code = "",
881   $subscriber_city = "",
882   $subscriber_state = "",
883   $subscriber_country = "",
884   $subscriber_phone = "",
885   $subscriber_employer = "",
886   $subscriber_employer_street = "",
887   $subscriber_employer_city = "",
888   $subscriber_employer_postal_code = "",
889   $subscriber_employer_state = "",
890   $subscriber_employer_country = "",
891   $copay = "",
892   $subscriber_sex = "",
893   $effective_date = "0000-00-00",
894   $accept_assignment = "TRUE")
896   if (strlen($type) <= 0) return FALSE;
898   // If a bad date was passed, err on the side of caution.
899   $effective_date = fixDate($effective_date, date('Y-m-d'));
901   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
902     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
903   $idrow = sqlFetchArray($idres);
905   // Replace the most recent entry in any of the following cases:
906   // * Its effective date is >= this effective date.
907   // * It is the first entry and it has no (insurance) provider.
908   // * There is no encounter that is earlier than the new effective date but
909   //   on or after the old effective date.
910   // Otherwise insert a new entry.
912   $replace = false;
913   if ($idrow) {
914     if (strcmp($idrow['date'], $effective_date) > 0) {
915       $replace = true;
916     }
917     else {
918       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
919         $replace = true;
920       }
921       else {
922         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
923           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
924           "date >= '" . $idrow['date'] . " 00:00:00'");
925         if ($ferow['count'] == 0) $replace = true;
926       }
927     }
928   }
930   if ($replace) {
932     // TBD: This is a bit dangerous in that a typo in entering the effective
933     // date can wipe out previous insurance history.  So we want some data
934     // entry validation somewhere.
935     sqlStatement("DELETE FROM insurance_data WHERE " .
936       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
937       "id != " . $idrow['id']);
939     $data = array();
940     $data['type'] = $type;
941     $data['provider'] = $provider;
942     $data['policy_number'] = $policy_number;
943     $data['group_number'] = $group_number;
944     $data['plan_name'] = $plan_name;
945     $data['subscriber_lname'] = $subscriber_lname;
946     $data['subscriber_mname'] = $subscriber_mname;
947     $data['subscriber_fname'] = $subscriber_fname;
948     $data['subscriber_relationship'] = $subscriber_relationship;
949     $data['subscriber_ss'] = $subscriber_ss;
950     $data['subscriber_DOB'] = $subscriber_DOB;
951     $data['subscriber_street'] = $subscriber_street;
952     $data['subscriber_postal_code'] = $subscriber_postal_code;
953     $data['subscriber_city'] = $subscriber_city;
954     $data['subscriber_state'] = $subscriber_state;
955     $data['subscriber_country'] = $subscriber_country;
956     $data['subscriber_phone'] = $subscriber_phone;
957     $data['subscriber_employer'] = $subscriber_employer;
958     $data['subscriber_employer_city'] = $subscriber_employer_city;
959     $data['subscriber_employer_street'] = $subscriber_employer_street;
960     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
961     $data['subscriber_employer_state'] = $subscriber_employer_state;
962     $data['subscriber_employer_country'] = $subscriber_employer_country;
963     $data['copay'] = $copay;
964     $data['subscriber_sex'] = $subscriber_sex;
965     $data['pid'] = $pid;
966     $data['date'] = $effective_date;
967     $data['accept_assignment'] = $accept_assignment;
968     updateInsuranceData($idrow['id'], $data);
969     return $idrow['id'];
970   }
971   else {
972     return sqlInsert("INSERT INTO insurance_data SET
973       type = '$type',
974       provider = '$provider',
975       policy_number = '$policy_number',
976       group_number = '$group_number',
977       plan_name = '$plan_name',
978       subscriber_lname = '$subscriber_lname',
979       subscriber_mname = '$subscriber_mname',
980       subscriber_fname = '$subscriber_fname',
981       subscriber_relationship = '$subscriber_relationship',
982       subscriber_ss = '$subscriber_ss',
983       subscriber_DOB = '$subscriber_DOB',
984       subscriber_street = '$subscriber_street',
985       subscriber_postal_code = '$subscriber_postal_code',
986       subscriber_city = '$subscriber_city',
987       subscriber_state = '$subscriber_state',
988       subscriber_country = '$subscriber_country',
989       subscriber_phone = '$subscriber_phone',
990       subscriber_employer = '$subscriber_employer',
991       subscriber_employer_city = '$subscriber_employer_city',
992       subscriber_employer_street = '$subscriber_employer_street',
993       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
994       subscriber_employer_state = '$subscriber_employer_state',
995       subscriber_employer_country = '$subscriber_employer_country',
996       copay = '$copay',
997       subscriber_sex = '$subscriber_sex',
998       pid = '$pid',
999       date = '$effective_date',
1000       accept_assignment = '$accept_assignment'
1001     ");
1002   }
1005 // This is used internally only.
1006 function updateInsuranceData($id, $new)
1008   $fields = sqlListFields("insurance_data");
1009   $use = array();
1011   while(list($key, $value) = each ($new)) {
1012     if (in_array($key, $fields)) {
1013       $use[$key] = $value;
1014     }
1015   }
1017   $sql = "UPDATE insurance_data SET ";
1018   while(list($key, $value) = each($use))
1019     $sql .= $key . " = '$value', ";
1020   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1022   sqlStatement($sql);
1025 function newHistoryData($pid, $new=false) {
1026   $sql = "insert into history_data set pid = '$pid', date = NOW()";
1027   if ($new) {
1028     while(list($key, $value) = each($new)) {
1029       if (!get_magic_quotes_gpc()) $value = addslashes($value);
1030       $sql .= ", $key = '$value'";
1031     }
1032   }
1033   return sqlInsert($sql);
1036 function updateHistoryData($pid,$new)
1038         $real = getHistoryData($pid);
1039         while(list($key, $value) = each ($new))
1040                 $real[$key] = $value;
1041         $real['date'] = "'+NOW()+'";
1042         $real['id'] = "";
1044         $sql = "insert into history_data set ";
1045         while(list($key, $value) = each($real))
1046                 $sql .= $key." = '$value', ";
1047         $sql = substr($sql, 0, -2);
1050         return sqlInsert($sql);
1053 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1054                 $phone_biz,$phone_cell,$email,$pid="")
1056     if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1057     if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1059     $db = $GLOBALS['adodb']['db'];
1060     $customer_info = array();
1062     $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1063     $result = $db->Execute($sql);
1064     if ($result && !$result->EOF) {
1065         $customer_info['foreign_update'] = true;
1066         $customer_info['foreign_id'] = $result->fields['foreign_id'];
1067         $customer_info['foreign_table'] = $result->fields['foreign_table'];
1068     }
1070     ///xml rpc code to connect to accounting package and add user to it
1071     $customer_info['firstname'] = $fname;
1072     $customer_info['lastname'] = $lname;
1073     $customer_info['address'] = $street;
1074     $customer_info['suburb'] = $city;
1075     $customer_info['state'] = $state;
1076     $customer_info['postcode'] = $postal_code;
1078     //ezybiz wants state as a code rather than abbreviation
1079     $customer_info['geo_zone_id'] = "";
1080     $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1081     $db = $GLOBALS['adodb']['db'];
1082     $result = $db->Execute($sql);
1083     if ($result && !$result->EOF) {
1084         $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1085     }
1087     //ezybiz wants country as a code rather than abbreviation
1088     $customer_info['geo_country_id'] = "";
1089     $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1090     $db = $GLOBALS['adodb']['db'];
1091     $result = $db->Execute($sql);
1092     if ($result && !$result->EOF) {
1093         $customer_info['geo_country_id'] = $result->fields['countries_id'];
1094     }
1096     $customer_info['phone1'] = $phone_home;
1097     $customer_info['phone1comment'] = "Home Phone";
1098     $customer_info['phone2'] = $phone_biz;
1099     $customer_info['phone2comment'] = "Business Phone";
1100     $customer_info['phone3'] = $phone_cell;
1101     $customer_info['phone3comment'] = "Cell Phone";
1102     $customer_info['email'] = $email;
1103     $customer_info['customernumber'] = $pid;
1105     $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1106     $ws = new WSWrapper($function);
1108     // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1109     if (is_numeric($ws->value)) {
1110         $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1111         $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1112     }
1115 // Returns Age 
1116 //   in months if < 2 years old
1117 //   in years  if > 2 years old
1118 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1119 // (optional) nowYMD is a date in YYYYMMDD format
1120 function getPatientAge($dobYMD, $nowYMD=null)
1122     // strip any dashes from the DOB
1123     $dobYMD = preg_replace("/-/", "", $dobYMD);
1124     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1125     
1126     // set the 'now' date values
1127     if ($nowYMD == null) {
1128         $nowDay = date("d");
1129         $nowMonth = date("m");
1130         $nowYear = date("Y");
1131     }
1132     else {
1133         $nowDay = substr($nowYMD,6,2);
1134         $nowMonth = substr($nowYMD,4,2);
1135         $nowYear = substr($nowYMD,0,4);
1136     }
1138     $dayDiff = $nowDay - $dobDay;
1139     $monthDiff = $nowMonth - $dobMonth;
1140     $yearDiff = $nowYear - $dobYear;
1142     $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1144     if ( $ageInMonths > 24 ) {
1145         $age = $yearDiff;
1146         if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1147         else if ($monthDiff < 0) { $age -= 1; }
1148     }
1149     else  {
1150         $age = "$ageInMonths month"; 
1151     }
1153     return $age;
1157 // Returns Age in days
1158 //   in months if < 2 years old
1159 //   in years  if > 2 years old
1160 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1161 // (optional) nowYMD is a date in YYYYMMDD format
1162 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1163     $age = -1;
1165     // strip any dashes from the DOB
1166     $dobYMD = preg_replace("/-/", "", $dobYMD);
1167     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1168     
1169     // set the 'now' date values
1170     if ($nowYMD == null) {
1171         $nowDay = date("d");
1172         $nowMonth = date("m");
1173         $nowYear = date("Y");
1174     }
1175     else {
1176         $nowDay = substr($nowYMD,6,2);
1177         $nowMonth = substr($nowYMD,4,2);
1178         $nowYear = substr($nowYMD,0,4);
1179     }
1181     // do the date math
1182     $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1183     $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1184     $timediff = $nowtime - $dobtime;
1185     $age = $timediff / 86400;
1187     return $age;
1190 function dateToDB ($date)
1192     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1193     return $date;
1197 // ----------------------------------------------------------------------------
1199  * DROPDOWN FOR COUNTRIES
1200  * 
1201  * build a dropdown with all countries from geo_country_reference
1202  * 
1203  * @param int $selected - id for selected record
1204  * @param string $name - the name/id for select form
1205  * @return void - just echo the html encoded string
1206  */
1207 function dropdown_countries($selected = 0, $name = 'country_code') {
1208     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1210     $string = "<select name='$name' id='$name'>";
1211     while ( $row = sqlFetchArray($r) ) {
1212         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1213         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1214     }
1216     $string .= '</select>';
1217     echo $string;
1221 // ----------------------------------------------------------------------------
1223  * DROPDOWN FOR YES/NO
1224  * 
1225  * build a dropdown with two options (yes - 1, no - 0)
1226  * 
1227  * @param int $selected - id for selected record
1228  * @param string $name - the name/id for select form
1229  * @return void - just echo the html encoded string 
1230  */
1231 function dropdown_yesno($selected = 0, $name = 'yesno') {
1232     $string = "<select name='$name' id='$name'>";
1234     $selected = (int)$selected;
1235     if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1236     else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1238     $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1239     $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1240     $string .= '</select>';
1242     echo $string;
1245 // ----------------------------------------------------------------------------
1247  * DROPDOWN FOR MALE/FEMALE options
1248  * 
1249  * build a dropdown with three options (unselected/male/female)
1250  * 
1251  * @param int $selected - id for selected record
1252  * @param string $name - the name/id for select form
1253  * @return void - just echo the html encoded string
1254  */
1255 function dropdown_sex($selected = 0, $name = 'sex') {
1256     $string = "<select name='$name' id='$name'>";
1258     if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1259     else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1260     else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1262     $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1263     $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1264     $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1265     $string .= '</select>';
1267     echo $string;
1270 // ----------------------------------------------------------------------------
1272  * DROPDOWN FOR MARITAL STATUS
1273  * 
1274  * build a dropdown with marital status
1275  * 
1276  * @param int $selected - id for selected record
1277  * @param string $name - the name/id for select form
1278  * @return void - just echo the html encoded string
1279  */
1280 function dropdown_marital($selected = 0, $name = 'status') {
1281     $string = "<select name='$name' id='$name'>";
1283     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1285     foreach ( $statii as $st ) {
1286         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1287         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1288     }
1290     $string .= '</select>';
1292     echo $string;
1295 // ----------------------------------------------------------------------------
1297  * DROPDOWN FOR PROVIDERS
1298  * 
1299  * build a dropdown with all providers
1300  * 
1301  * @param int $selected - id for selected record
1302  * @param string $name - the name/id for select form
1303  * @return void - just echo the html encoded string
1304  */
1305 function dropdown_providers($selected = 0, $name = 'status') {
1306     $provideri = getProviderInfo();
1308     $string = "<select name='$name' id='$name'>";
1309     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1310     foreach ( $provideri as $s ) {
1311         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1312         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1313     }
1315     $string .= '</select>';
1317     echo $string;
1320 // ----------------------------------------------------------------------------
1322  * DROPDOWN FOR INSURANCE COMPANIES
1323  * 
1324  * build a dropdown with all insurers
1325  * 
1326  * @param int $selected - id for selected record
1327  * @param string $name - the name/id for select form
1328  * @return void - just echo the html encoded string
1329  */
1330 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1331     $insurancei = getInsuranceProviders();
1333     $string = "<select name='$name' id='$name'>";
1334     $string .= '<option value="0">Onbekend</option>';
1335     foreach ( $insurancei as $iid => $iname ) {
1336         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1337         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1338     }
1340     $string .= '</select>';
1342     echo $string;
1346 // ----------------------------------------------------------------------------
1348  * COUNTRY CODE
1349  * 
1350  * return the name or the country code, function of arguments
1351  * 
1352  * @param int $country_code
1353  * @param string $country_name
1354  * @return string | int - name or code
1355  */
1356 function country_code($country_code = 0, $country_name = '') {
1357     $strint = '';
1358     if ( $country_code ) {
1359         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1360     } else {
1361         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1362     }
1364     $db = $GLOBALS['adodb']['db'];
1365     $result = $db->Execute($sql);
1366     if ($result && !$result->EOF) {
1367         $strint = $result->fields['res'];
1368     }
1370     return $strint;
1373 // ----------------------------------------------------------------------------
1375  * GET INSURANCE DATA
1376  * (Dutch usage)
1377  * 
1378  * return the insurer(s) and some patient
1379  * 
1380  * @param int $pid - patient id
1381  * @param int $current 1-current 0-all insurers
1382  * @return array
1383  */
1384 function get_insurers_nl($pid = 0, $current = 1) {
1385     if ( !$pid ) return FALSE;
1387     $join = 'insurance_companies ic ON ic.id = pi.pin_provider';
1388     $r = dsql_select('*', 'patient_insurers_NL pi', array('pin_pid' => $pid), 'pin_date DESC', $join);
1390     while ( $row = mysql_fetch_array($r) ) {
1391         $rez[] = $row;
1392     } // while
1394     return ( $current ? $rez[0] : $rez );
1398 // ----------------------------------------------------------------------------
1400  * SET INSURANCE DATA
1401  * (Dutch usage)
1402  * 
1403  * set the insurer for a patient
1404  * 
1405  * @param int $pid - patient id
1406  * @param int $insid - insurer id
1407  * @return void
1408  */
1409 function set_insurer_nl($pid = 0, $insid = 0, $date = '', $policy = '') {
1410     if ( !$pid || !$insid || ($date == '0000-00-00') ) return FALSE;
1412     $fields = array('pin_pid', 'pin_provider', 'pin_date', 'pin_policy');
1413     $values = array($pid, $insid, $date, $policy);
1414     dsql_insert('patient_insurers_NL', $fields, $values);
1417 // ----------------------------------------------------------------------------
1419  * FIND THE INSURERS STATUS FOR A PATIENT
1420  * (Dutch usage)
1421  * 
1422  * return the answer for the question: is this the first insurer or not?
1423  * 
1424  * @param int $pid - patient id
1425  * @return int - the number of insurer records ( 0 - no insurer; >0 some insurers)
1426  */
1427 function total_insurers($pid = 0) {
1428     if ( !$pid ) return FALSE;
1430     $r = dsql_select('COUNT(*) AS c', 'patient_insurers_NL', array('pin_pid' => $pid));
1431     $row = mysql_fetch_array($r);
1433     return $row['c'];
1436 function DBToDate ($date)
1438     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1439     return $date;
1442 function get_patient_balance($pid) {
1443   if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1444     $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1445       "pid = '$pid' AND activity = 1");
1446     $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1447       "pid = '$pid'");
1448     $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1449       "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1450       "pid = '$pid'");
1451     return sprintf('%01.2f', $brow['amount'] + $srow['amount']
1452       - $drow['payments'] - $drow['adjustments']);
1453   }
1454   else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1455     // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1456     $conn = $GLOBALS['adodb']['db'];
1457     $customer_info['id'] = 0;
1458     $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1459       "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1460       "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1461       "im.foreign_table = 'customer'";
1462     $result = $conn->Execute($sql);
1463     if($result && !$result->EOF) {
1464       $customer_info['id'] = $result->fields['foreign_id'];
1465     }
1466     $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1467     $ws = new WSWrapper($function);
1468     if(is_numeric($ws->value)) {
1469       return sprintf('%01.2f', $ws->value);
1470     }
1471   }
1472   return '';