separating facility from user maintenance, improved support for multiple facilities...
[openemr.git] / library / patient.inc
blob1fe3e6ad8fd419d78ddf014658cc79ae185de5e6
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         $param2 = " AND (facility_id = $facility 
156           OR  $facility IN
157                 (select facility_id 
158                 from users_facility
159                 where tablename = 'users'
160                 and table_id = id)
161                 )
162           ";
163     }
164     //--------------------------------
166     $command = "=";
167     if ($providerID == "%") {
168         $command = "like";
169     }
170     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
171         "from users where username != '' and active = 1 and id $command '" .
172         mysql_real_escape_string($providerID) . "' " . $param1 . $param2;
173     // sort by last name -- JRM June 2008
174     $query .= " ORDER BY lname, fname ";
175     $rez = sqlStatement($query);
176     for($iter=0; $row=sqlFetchArray($rez); $iter++)
177         $returnval[$iter]=$row;
179     //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
180     //accessible from $resultval['key']
182     if($iter==1) {
183         $akeys = array_keys($returnval[0]);
184         foreach($akeys as $key) {
186             $returnval[0][$key] = $returnval[0][$key];
187         }
188     }
189     return $returnval;
192 //same as above but does not reduce if only 1 row returned
193 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
194     $param1 = "";
195     if ($providers_only) {
196         $param1 = "AND authorized=1";
197     }
198     $command = "=";
199     if ($providerID == "%") {
200         $command = "like";
201     }
202     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
203         "from users where active = 1 and username != '' and id $command '" .
204         mysql_real_escape_string($providerID) . "' " . $param1;
206     $rez = sqlStatement($query);
207     for($iter=0; $row=sqlFetchArray($rez); $iter++)
208         $returnval[$iter]=$row;
210     return $returnval;
213 function getProviderName($providerID) {
214     $pi = getProviderInfo($providerID);
215     if (strlen($pi[0]["lname"]) > 0) {
216         return $pi[0]['fname'] . " " . $pi[0]['lname'];
217     }
218     return "";
221 function getProviderId($providerName) {
222     $query = "select id from users where username = '". mysql_real_escape_string($providerName)."'";
223     $rez = sqlStatement($query);
224     for($iter=0; $row=sqlFetchArray($rez); $iter++)
225         $returnval[$iter]=$row;
226     return $returnval;
229 function getEthnoRacials() {
230     $returnval = array("");
231     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
232     $rez = sqlStatement($sql);
233     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
234         if (($row["ethnoracial"] != "")) {
235             array_push($returnval, $row["ethnoracial"]);
236         }
237     }
238     return $returnval;
241 function getHistoryData($pid, $given = "*")
243     $sql = "select $given from history_data where pid='$pid' order by date DESC limit 0,1";
244     return sqlQuery($sql);
247 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
248 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
250   $sql = "select $given from insurance_data as insd " .
251     "left join insurance_companies as ic on ic.id = insd.provider " .
252     "where pid = '$pid' and type = '$type' order by date DESC limit 1";
253   return sqlQuery($sql);
256 function getInsuranceDataByDate($pid, $date, $type,
257   $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
258 { // this must take the date in the following manner: YYYY-MM-DD
259   // this function recalls the insurance value that was most recently enterred from the
260   // given date. it will call up most recent records up to and on the date given,
261   // but not records enterred after the given date
262   $sql = "select $given from insurance_data as insd " .
263     "left join insurance_companies as ic on ic.id = provider " .
264     "where pid = '$pid' and date_format(date,'%Y-%m-%d') <= '$date' and " .
265     "type='$type' order by date DESC limit 1";
266   return sqlQuery($sql);
269 function getEmployerData($pid, $given = "*")
271     $sql = "select $given from employer_data where pid='$pid' order by date DESC limit 0,1";
272     return sqlQuery($sql);
275 function _set_patient_inc_count($limit, $count, $where) {
276   // When the limit is exceeded, find out what the unlimited count would be.
277   $GLOBALS['PATIENT_INC_COUNT'] = $count;
278   if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
279     $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where");
280     $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
281   }
284 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")
286     // Allow the last name to be followed by a comma and some part of a first name.
287     // New behavior for searches:
288     // Allows comma alone followed by some part of a first name
289     // If the first letter of either name is capital, searches for name starting
290     // with given substring (the expected behavior).  If it is lower case, it
291     // it searches for the substring anywhere in the name.  This applies to either
292     // last name or first name or both.  The arbitrary limit of 100 results is set
293     // in the sql query below. --Mark Leeds
294     $lname = trim($lname);
295     $fname = '';
296      if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
297          $lname = trim($matches[1]);
298          $fname = trim($matches[2]);
299     }
300     $search_for_pieces1 = '';
301     $search_for_pieces2 = '';
302     if ($lname{0} != strtoupper($lname{0})) {$search_for_pieces1 = '%';}
303     if ($fname{0} != strtoupper($fname{0})) {$search_for_pieces2 = '%';}
305     $where = "lname LIKE '" . $search_for_pieces1 . "$lname%' " .
306         "AND fname LIKE '" . $search_for_pieces2 . "$fname%' ";
307         if (!empty($GLOBALS['pt_restrict_field'])) {
308                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
309                         $where .= "AND ( patient_data.".$GLOBALS['pt_restrict_field']." = ( SELECT facility_id FROM users WHERE username = '".$_SESSION{"authUser"}."') OR patient_data.".$GLOBALS['pt_restrict_field']." = '' ) ";
310                 }
311         }
313     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
314     if ($limit != "all") $sql .= " LIMIT $start, $limit";
316     $rez = sqlStatement($sql);
318     for($iter=0; $row=sqlFetchArray($rez); $iter++)
319         $returnval[$iter] = $row;
321     _set_patient_inc_count($limit, count($returnval), $where);
322     return $returnval;
325 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")
327     
328     $where = "pubpid LIKE '$pid%' ";
329         if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
330                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
331                         $where .= "AND ( patient_data.".$GLOBALS['pt_restrict_field']." = ( SELECT facility_id FROM users WHERE username = '".$_SESSION{"authUser"}."') OR patient_data.".$GLOBALS['pt_restrict_field']." = '' ) ";
332                 }
333         }
335     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
336     if ($limit != "all") $sql .= " limit $start, $limit";
337     $rez = sqlStatement($sql);
338     for($iter=0; $row=sqlFetchArray($rez); $iter++)
339         $returnval[$iter]=$row;
341     _set_patient_inc_count($limit, count($returnval), $where);
342     return $returnval;
345 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")
347         $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like ('%Employer%' ) AND uor !=0" );
349     $where = "";
350     for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
351         if ( $iter > 0 ) {
352            $where .= " or ";
353         }
354         $where .= " ".$row["field_id"]." like '%".$searchTerm."%' ";
355     }
357     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
358     if ($limit != "all") $sql .= " limit $start, $limit";
359     $rez = sqlStatement($sql);
360     for($iter=0; $row=sqlFetchArray($rez); $iter++)
361         $returnval[$iter]=$row;
363     _set_patient_inc_count($limit, count($returnval), $where);
364     return $returnval;
367 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" )
369         $layoutCols = split( '~', $searchFields );
371     $where = "";
372     $i = 0;
373     foreach ($layoutCols as $val ) {
374                 if ( $i > 0 ) {
375                    $where .= " or ";
376                 }
377                 $where .= " ".$val." like '%".$searchTerm."%' ";
378                 $i++;
379         }
381     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
382     if ($limit != "all") $sql .= " limit $start, $limit";
383     $rez = sqlStatement($sql);
384     for($iter=0; $row=sqlFetchArray($rez); $iter++)
385         $returnval[$iter]=$row;
387     _set_patient_inc_count($limit, count($returnval), $where);
388     return $returnval;
392 // return a collection of Patient PIDs
393 // new arg style by JRM March 2008
394 // 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")
395 function getPatientPID($args)
397     $pid = "%";
398     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
399     $orderby = "lname ASC, fname ASC";
400     $limit="all";
401     $start="0";
403     // alter default values if defined in the passed in args
404     if (isset($args['pid'])) { $pid = $args['pid']; }
405     if (isset($args['given'])) { $given = $args['given']; }
406     if (isset($args['orderby'])) { $orderby = $args['orderby']; }
407     if (isset($args['limit'])) { $limit = $args['limit']; }
408     if (isset($args['start'])) { $start = $args['start']; }
410     $command = "=";
411     if ($pid == -1) $pid = "%";
412     elseif (empty($pid)) $pid = "NULL";
414     if (strstr($pid,"%")) $command = "like";
416     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
417     if ($limit != "all") $sql .= " limit $start, $limit";
419     $rez = sqlStatement($sql);
420     for($iter=0; $row=sqlFetchArray($rez); $iter++)
421         $returnval[$iter]=$row;
423     return $returnval;
426 function getPatientName($pid) {
427     if (empty($pid)) return "";
428     $patientData = getPatientPID(array("pid"=>$pid));
429     if (empty($patientData[0]['lname'])) return "";
430     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
431     return $patientName;
434 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
436     $DOB = fixDate($DOB, $DOB);
437     $where = "DOB like '$DOB%' ";
438         if (!empty($GLOBALS['pt_restrict_field'])) {
439                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
440                         $where .= "AND ( patient_data.".$GLOBALS['pt_restrict_field']." = ( SELECT facility_id FROM users WHERE username = '".$_SESSION{"authUser"}."') OR patient_data.".$GLOBALS['pt_restrict_field']." = '' ) ";
441                 }
442         }
444     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
446     if ($limit != "all") $sql .= " LIMIT $start, $limit";
448     $rez = sqlStatement($sql);
449     for($iter=0; $row=sqlFetchArray($rez); $iter++)
450         $returnval[$iter]=$row;
452     _set_patient_inc_count($limit, count($returnval), $where);
453     return $returnval;
456 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
458     $where = "ss LIKE '$ss%'";
459     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
460     if ($limit != "all") $sql .= " LIMIT $start, $limit";
462     $rez = sqlStatement($sql);
463     for($iter=0; $row=sqlFetchArray($rez); $iter++)
464         $returnval[$iter]=$row;
466     _set_patient_inc_count($limit, count($returnval), $where);
467     return $returnval;
470 //(CHEMED) Search by phone number
471 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
473     $phone = ereg_replace( "[[:punct:]]","", $phone );
474     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP '$phone'";
475     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
476     if ($limit != "all") $sql .= " LIMIT $start, $limit";
478     $rez = sqlStatement($sql);
479     for($iter=0; $row=sqlFetchArray($rez); $iter++)
480         $returnval[$iter]=$row;
482     _set_patient_inc_count($limit, count($returnval), $where);
483     return $returnval;
486 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
488     $sql="select $given from patient_data order by $orderby";
490     if ($limit != "all")
491         $sql .= " limit $start, $limit";
493     $rez = sqlStatement($sql);
494     for($iter=0; $row=sqlFetchArray($rez); $iter++)
495         $returnval[$iter]=$row;
497     return $returnval;
500 //----------------------input functions
501 function newPatientData(    $db_id="",
502                 $title = "",
503                 $fname = "",
504                 $lname = "",
505                 $mname = "",
506                 $sex = "",
507                 $DOB = "",
508                 $street = "",
509                 // DBC dutch use
510                 $nstreet = "",
511                 $nnr = "",
512                 $nadd = "",
513                 // EOS DBC
514                 $postal_code = "",
515                 $city = "",
516                 $state = "",
517                 $country_code = "",
518                 $ss = "",
519                 $occupation = "",
520                 $phone_home = "",
521                 $phone_biz = "",
522                 $phone_contact = "",
523                 $status = "",
524                 $contact_relationship = "",
525                 $referrer = "",
526                 $referrerID = "",
527                 $email = "",
528                 $language = "",
529                 $ethnoracial = "",
530                 $interpretter = "",
531                 $migrantseasonal = "",
532                 $family_size = "",
533                 $monthly_income = "",
534                 $homeless = "",
535                 $financial_review = "",
536                 $pubpid = "",
537                 $pid = "MAX(pid)+1",
538                 $providerID = "",
539                 $genericname1 = "",
540                 $genericval1 = "",
541                 $genericname2 = "",
542                 $genericval2 = "",
543                 $phone_cell = "",
544                 $hipaa_mail = "",
545                 $hipaa_voice = "",
546                 $squad = 0,
547                 $pharmacy_id = 0,
548                 $drivers_license = "",
549                 $hipaa_notice = "",
550                 $hipaa_message = "",
551                 $regdate = "",
552                 // dutch specific
553                 $prefixlast = "",
554                 $prefixlastpartner = "",
555                 $lastpartner = "",
556                 $initials = "",
557                 $provider_data = array(),
558                 $referer_data = array()
559                 // DBC Dutch System
561             )
563     $DOB = fixDate($DOB);
564     $regdate = fixDate($regdate);
566     $fitness = 0;
567     $referral_source = '';
568     if ($pid) {
569         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
570         // Check for brain damage:
571         if ($db_id != $rez['id']) {
572             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
573               $rez['id'] . "' to '$db_id' for pid '$pid'";
574             die($errmsg);
575         }
576         $fitness = $rez['fitness'];
577         $referral_source = $rez['referral_source'];
578     }
580     // Get the default price level.
581     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
582       "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
583     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
585     $query = ("replace into patient_data set
586         id='$db_id',
587         title='$title',
588         fname='$fname',
589         lname='$lname',
590         mname='$mname',
591         sex='$sex',
592         DOB='$DOB',
593         street='$street',
594         postal_code='$postal_code',
595         city='$city',
596         state='$state',
597         country_code='$country_code',
598         drivers_license='$drivers_license',
599         ss='$ss',
600         occupation='$occupation',
601         phone_home='$phone_home',
602         phone_biz='$phone_biz',
603         phone_contact='$phone_contact',
604         status='$status',
605         contact_relationship='$contact_relationship',
606         referrer='$referrer',
607         referrerID='$referrerID',
608         email='$email',
609         language='$language',
610         ethnoracial='$ethnoracial',
611         interpretter='$interpretter',
612         migrantseasonal='$migrantseasonal',
613         family_size='$family_size',
614         monthly_income='$monthly_income',
615         homeless='$homeless',
616         financial_review='$financial_review',
617         pubpid='$pubpid',
618         pid = $pid,
619         providerID = '$providerID',
620         genericname1 = '$genericname1',
621         genericval1 = '$genericval1',
622         genericname2 = '$genericname2',
623         genericval2 = '$genericval2',
624         phone_cell = '$phone_cell',
625         pharmacy_id = '$pharmacy_id',
626         hipaa_mail = '$hipaa_mail',
627         hipaa_voice = '$hipaa_voice',
628         hipaa_notice = '$hipaa_notice',
629         hipaa_message = '$hipaa_message',
630         squad = '$squad',
631         fitness='$fitness',
632         referral_source='$referral_source',
633         regdate='$regdate',
634         pricelevel='$pricelevel',
635         date=NOW()");
637     $id = sqlInsert($query);
639     // DBC 
640     if ( !$db_id ) {
641       // find the last inserted id for new patient case
642       $db_id = empty($GLOBALS['dutchpc']) ? mysql_insert_id() : dsql_lastid();
643     }
644     // EOS DBC
646     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
648          // dutch use
649         if ( $GLOBALS['dutchpc'] ) {
650                 $init = strtoupper(preg_replace('/[\s\.\-_0-9]/','',$initials));
651                 
652             $querynl = ("REPLACE INTO patient_data_NL SET
653                     pdn_id = '$db_id',
654                     pdn_pxlast = '$prefixlast',
655                     pdn_pxlastpar = '$prefixlastpartner',
656                     pdn_lastpar = '$lastpartner',
657                     pdn_street = '$nstreet',
658                     pdn_number = '$nnr',
659                     pdn_addition = '$nadd',
660                     pdn_initials = '$init'
661             ");
663             if ( $db_id ) $idnl = sqlInsert($querynl); // only if exists
664         }
665         // EOS dutch use
668        // DBC Dutch System
669         // provider first
670         if ( $GLOBALS['dutchpc'] && $db_id && $provider_data && $referer_data) {
671            $querypr = ("INSERT INTO cl_providers(pro_pid, pro_company, pro_initials, pro_prefix, pro_lname,
672                    pro_street, pro_number, pro_addition, pro_city, pro_zipcode,  pro_phone, pro_fax, pro_email, pro_referer ) 
673                    VALUES ($db_id, '{$provider_data['pro_company']}', '{$provider_data['pro_initials']}',
674                   '{$provider_data['pro_prefix']}', '{$provider_data['pro_lname']}',  
675                   '{$provider_data['pro_street']}', '{$provider_data['pro_number']}', '{$provider_data['pro_addition']}', 
676                   '{$provider_data['pro_city']}',  '{$provider_data['pro_zipcode']}',
677                   '{$provider_data['pro_phone']}', '{$provider_data['pro_fax']}',  '{$provider_data['pro_email']}', 
678                   '{$provider_data['pro_referer']}') 
679                   ON DUPLICATE KEY UPDATE  pro_referer = '{$provider_data['pro_referer']}',
680                   pro_company = '{$provider_data['pro_company']}', pro_initials = '{$provider_data['pro_initials']}',
681                   pro_prefix = '{$provider_data['pro_prefix']}',
682                   pro_lname = '{$provider_data['pro_lname']}', pro_street = '{$provider_data['pro_street']}',
683                   pro_number = '{$provider_data['pro_number']}', pro_addition = '{$provider_data['pro_addition']}',
684                   pro_city = '{$provider_data['pro_city']}', pro_zipcode = '{$provider_data['pro_zipcode']}',
685                   pro_phone = '{$provider_data['pro_phone']}', pro_fax = '{$provider_data['pro_fax']}',
686                   pro_email = '{$provider_data['pro_email']}'
687             ");
688            $idpr = sqlInsert($querypr);
690         // referer if it's the case
691         if ( $referer_data['ref_code'] ) {
692            $queryre = ("INSERT INTO cl_referers(ref_pid, ref_code, ref_company, ref_initials, ref_prefix,
693                    ref_lname, ref_street, ref_number, ref_addition, ref_city, ref_zipcode,  ref_phone, ref_fax,
694                    ref_email) 
695                    VALUES ($db_id, {$referer_data['ref_code']}, '{$referer_data['ref_company']}', 
696                    '{$referer_data['ref_initials']}', '{$referer_data['ref_prefix']}',
697                    '{$referer_data['ref_lname']}', '{$referer_data['ref_street']}', '{$referer_data['ref_number']}', 
698                    '{$referer_data['ref_addition']}', '{$referer_data['ref_city']}', '{$referer_data['ref_zipcode']}',
699                   '{$referer_data['ref_phone']}', '{$referer_data['ref_fax']}',  '{$referer_data['ref_email']}')
700                   ON DUPLICATE KEY UPDATE ref_code = {$referer_data['ref_code']},
701                   ref_company = '{$referer_data['ref_company']}', ref_initials = '{$referer_data['ref_initials']}',
702                   ref_prefix = '{$referer_data['ref_prefix']}',
703                   ref_lname = '{$referer_data['ref_lname']}', ref_street = '{$referer_data['ref_street']}',
704                   ref_number = '{$referer_data['ref_number']}', ref_addition = '{$referer_data['ref_addition']}',
705                   ref_city = '{$referer_data['ref_city']}', ref_zipcode = '{$referer_data['ref_zipcode']}',
706                   ref_phone = '{$referer_data['ref_phone']}', ref_fax = '{$referer_data['ref_fax']}',
707                   ref_email = '{$referer_data['ref_email']}'
708             ");
709            $idre = sqlInsert($queryre);
710         } 
711         } // if globals
712         // EOS DBC
714     sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
715                 $phone_biz,$phone_cell,$email,$pid);
717     return $foo['pid'];
720 // Supported input date formats are:
721 //   mm/dd/yyyy
722 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
723 //   yyyy/mm/dd
724 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
726 function fixDate($date, $default="0000-00-00") {
727     $fixed_date = $default;
728     $date = trim($date);
729     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
730         $dmy = preg_split("'[/.-]'", $date);
731         if ($dmy[0] > 99) {
732             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
733         } else {
734             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
735               if ($dmy[2] < 1000) $dmy[2] += 1900;
736               if ($dmy[2] < 1910) $dmy[2] += 100;
737             }
738             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
739         }
740     }
742     return $fixed_date;
745 function updatePatientData($pid,$new)
747   /*******************************************************************
748     $real = getPatientData($pid);
749     $new['DOB'] = fixDate($new['DOB']);
750     while(list($key, $value) = each ($new))
751         $real[$key] = $value;
752     $real['date'] = "'+NOW()+'";
753     $real['id'] = "";
754     $sql = "insert into patient_data set ";
755     while(list($key, $value) = each($real))
756         $sql .= $key." = '$value', ";
757     $sql = substr($sql, 0, -2);
758     return sqlInsert($sql);
759   *******************************************************************/
761   // The above was broken, though seems intent to insert a new patient_data
762   // row for each update.  A good idea, but nothing is doing that yet so
763   // the code below does not yet attempt it.
765   $new['DOB'] = fixDate($new['DOB']);
766   $db_id = $new['id'];
768   $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
769   // Check for brain damage:
770   if ($pid != $rez['pid']) {
771     $errmsg = "Internal error: Attempt to change patient data with pid = '" .
772       $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
773     die($errmsg);
774   }
775   $sql = "UPDATE patient_data SET date = NOW()";
776   foreach ($new as $key => $value) {
777     $sql .= ", $key = '$value'";
778   }
779   $sql .= " WHERE id = '$db_id'";
780   sqlStatement($sql);
782   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
783   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
784     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
785     $rez['phone_cell'],$rez['email'],$rez['pid']);
787   return $db_id;
790 function newEmployerData(    $pid,
791                 $name = "",
792                 $street = "",
793                 $postal_code = "",
794                 $city = "",
795                 $state = "",
796                 $country = ""
797             )
799     return sqlInsert("insert into employer_data set
800         name='$name',
801         street='$street',
802         postal_code='$postal_code',
803         city='$city',
804         state='$state',
805         country='$country',
806         pid='$pid',
807         date=NOW()
808         ");
811 function updateEmployerData($pid, $new)
813   $old = getEmployerData($pid);
814   $set = '';
815   $modified = false;
816   foreach (array('name','street','city','state','postal_code','country') as $key) {
817     $value = empty($old[$key]) ? '' : addslashes($old[$key]);
818     if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
819       $value = $new[$key];
820       $modified = true;
821     }
822     $set .= "$key = '$value', ";
823   }
824   if ($modified) {
825     $set .= "pid = '$pid', date = NOW()";
826     return sqlInsert("INSERT INTO employer_data SET $set");
827   }
828   return $old['id'];
831 // This updates or adds the given insurance data info, while retaining any
832 // previously added insurance_data rows that should be preserved.
833 // This does not directly support the maintenance of non-current insurance.
835 function newInsuranceData(
836   $pid,
837   $type = "",
838   $provider = "",
839   $policy_number = "",
840   $group_number = "",
841   $plan_name = "",
842   $subscriber_lname = "",
843   $subscriber_mname = "",
844   $subscriber_fname = "",
845   $subscriber_relationship = "",
846   $subscriber_ss = "",
847   $subscriber_DOB = "",
848   $subscriber_street = "",
849   $subscriber_postal_code = "",
850   $subscriber_city = "",
851   $subscriber_state = "",
852   $subscriber_country = "",
853   $subscriber_phone = "",
854   $subscriber_employer = "",
855   $subscriber_employer_street = "",
856   $subscriber_employer_city = "",
857   $subscriber_employer_postal_code = "",
858   $subscriber_employer_state = "",
859   $subscriber_employer_country = "",
860   $copay = "",
861   $subscriber_sex = "",
862   $effective_date = "0000-00-00",
863   $accept_assignment = "TRUE")
865   if (strlen($type) <= 0) return FALSE;
867   // If a bad date was passed, err on the side of caution.
868   $effective_date = fixDate($effective_date, date('Y-m-d'));
870   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
871     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
872   $idrow = sqlFetchArray($idres);
874   // Replace the most recent entry in any of the following cases:
875   // * Its effective date is >= this effective date.
876   // * It is the first entry and it has no (insurance) provider.
877   // * There is no encounter that is earlier than the new effective date but
878   //   on or after the old effective date.
879   // Otherwise insert a new entry.
881   $replace = false;
882   if ($idrow) {
883     if (strcmp($idrow['date'], $effective_date) > 0) {
884       $replace = true;
885     }
886     else {
887       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
888         $replace = true;
889       }
890       else {
891         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
892           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
893           "date >= '" . $idrow['date'] . " 00:00:00'");
894         if ($ferow['count'] == 0) $replace = true;
895       }
896     }
897   }
899   if ($replace) {
901     // TBD: This is a bit dangerous in that a typo in entering the effective
902     // date can wipe out previous insurance history.  So we want some data
903     // entry validation somewhere.
904     sqlStatement("DELETE FROM insurance_data WHERE " .
905       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
906       "id != " . $idrow['id']);
908     $data = array();
909     $data['type'] = $type;
910     $data['provider'] = $provider;
911     $data['policy_number'] = $policy_number;
912     $data['group_number'] = $group_number;
913     $data['plan_name'] = $plan_name;
914     $data['subscriber_lname'] = $subscriber_lname;
915     $data['subscriber_mname'] = $subscriber_mname;
916     $data['subscriber_fname'] = $subscriber_fname;
917     $data['subscriber_relationship'] = $subscriber_relationship;
918     $data['subscriber_ss'] = $subscriber_ss;
919     $data['subscriber_DOB'] = $subscriber_DOB;
920     $data['subscriber_street'] = $subscriber_street;
921     $data['subscriber_postal_code'] = $subscriber_postal_code;
922     $data['subscriber_city'] = $subscriber_city;
923     $data['subscriber_state'] = $subscriber_state;
924     $data['subscriber_country'] = $subscriber_country;
925     $data['subscriber_phone'] = $subscriber_phone;
926     $data['subscriber_employer'] = $subscriber_employer;
927     $data['subscriber_employer_city'] = $subscriber_employer_city;
928     $data['subscriber_employer_street'] = $subscriber_employer_street;
929     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
930     $data['subscriber_employer_state'] = $subscriber_employer_state;
931     $data['subscriber_employer_country'] = $subscriber_employer_country;
932     $data['copay'] = $copay;
933     $data['subscriber_sex'] = $subscriber_sex;
934     $data['pid'] = $pid;
935     $data['date'] = $effective_date;
936     $data['accept_assignment'] = $accept_assignment;
937     updateInsuranceData($idrow['id'], $data);
938     return $idrow['id'];
939   }
940   else {
941     return sqlInsert("INSERT INTO insurance_data SET
942       type = '$type',
943       provider = '$provider',
944       policy_number = '$policy_number',
945       group_number = '$group_number',
946       plan_name = '$plan_name',
947       subscriber_lname = '$subscriber_lname',
948       subscriber_mname = '$subscriber_mname',
949       subscriber_fname = '$subscriber_fname',
950       subscriber_relationship = '$subscriber_relationship',
951       subscriber_ss = '$subscriber_ss',
952       subscriber_DOB = '$subscriber_DOB',
953       subscriber_street = '$subscriber_street',
954       subscriber_postal_code = '$subscriber_postal_code',
955       subscriber_city = '$subscriber_city',
956       subscriber_state = '$subscriber_state',
957       subscriber_country = '$subscriber_country',
958       subscriber_phone = '$subscriber_phone',
959       subscriber_employer = '$subscriber_employer',
960       subscriber_employer_city = '$subscriber_employer_city',
961       subscriber_employer_street = '$subscriber_employer_street',
962       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
963       subscriber_employer_state = '$subscriber_employer_state',
964       subscriber_employer_country = '$subscriber_employer_country',
965       copay = '$copay',
966       subscriber_sex = '$subscriber_sex',
967       pid = '$pid',
968       date = '$effective_date',
969       accept_assignment = '$accept_assignment'
970     ");
971   }
974 // This is used internally only.
975 function updateInsuranceData($id, $new)
977   $fields = sqlListFields("insurance_data");
978   $use = array();
980   while(list($key, $value) = each ($new)) {
981     if (in_array($key, $fields)) {
982       $use[$key] = $value;
983     }
984   }
986   $sql = "UPDATE insurance_data SET ";
987   while(list($key, $value) = each($use))
988     $sql .= $key . " = '$value', ";
989   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
991   sqlStatement($sql);
994 function newHistoryData($pid, $new=false) {
995   $sql = "insert into history_data set pid = '$pid', date = NOW()";
996   if ($new) {
997     while(list($key, $value) = each($new)) {
998       if (!get_magic_quotes_gpc()) $value = addslashes($value);
999       $sql .= ", $key = '$value'";
1000     }
1001   }
1002   return sqlInsert($sql);
1005 function updateHistoryData($pid,$new)
1007         $real = getHistoryData($pid);
1008         while(list($key, $value) = each ($new))
1009                 $real[$key] = $value;
1010         $real['date'] = "'+NOW()+'";
1011         $real['id'] = "";
1013         $sql = "insert into history_data set ";
1014         while(list($key, $value) = each($real))
1015                 $sql .= $key." = '$value', ";
1016         $sql = substr($sql, 0, -2);
1019         return sqlInsert($sql);
1022 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1023                 $phone_biz,$phone_cell,$email,$pid="")
1025     if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1026     if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1028     $db = $GLOBALS['adodb']['db'];
1029     $customer_info = array();
1031     $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1032     $result = $db->Execute($sql);
1033     if ($result && !$result->EOF) {
1034         $customer_info['foreign_update'] = true;
1035         $customer_info['foreign_id'] = $result->fields['foreign_id'];
1036         $customer_info['foreign_table'] = $result->fields['foreign_table'];
1037     }
1039     ///xml rpc code to connect to accounting package and add user to it
1040     $customer_info['firstname'] = $fname;
1041     $customer_info['lastname'] = $lname;
1042     $customer_info['address'] = $street;
1043     $customer_info['suburb'] = $city;
1044     $customer_info['state'] = $state;
1045     $customer_info['postcode'] = $postal_code;
1047     //ezybiz wants state as a code rather than abbreviation
1048     $customer_info['geo_zone_id'] = "";
1049     $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1050     $db = $GLOBALS['adodb']['db'];
1051     $result = $db->Execute($sql);
1052     if ($result && !$result->EOF) {
1053         $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1054     }
1056     //ezybiz wants country as a code rather than abbreviation
1057     $customer_info['geo_country_id'] = "";
1058     $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1059     $db = $GLOBALS['adodb']['db'];
1060     $result = $db->Execute($sql);
1061     if ($result && !$result->EOF) {
1062         $customer_info['geo_country_id'] = $result->fields['countries_id'];
1063     }
1065     $customer_info['phone1'] = $phone_home;
1066     $customer_info['phone1comment'] = "Home Phone";
1067     $customer_info['phone2'] = $phone_biz;
1068     $customer_info['phone2comment'] = "Business Phone";
1069     $customer_info['phone3'] = $phone_cell;
1070     $customer_info['phone3comment'] = "Cell Phone";
1071     $customer_info['email'] = $email;
1072     $customer_info['customernumber'] = $pid;
1074     $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1075     $ws = new WSWrapper($function);
1077     // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1078     if (is_numeric($ws->value)) {
1079         $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1080         $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1081     }
1084 // Returns Date of Birth given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1085 function getPatientAge($dobYMD)
1087     $tdyYMD=date("Ymd");
1088     $yearDiff = substr($tdyYMD,0,4) - substr($dobYMD,0,4);
1089     $ageInMonths = ((substr($tdyYMD,0,4)*12)+substr($tdyYMD,4,2)) -
1090                    ((substr($dobYMD,0,4)*12)+substr($dobYMD,4,2));
1091     $dayDiff = substr($tdyYMD,6,2) - substr($dobYMD,6,2);
1092     if ( $dayDiff < 0 ) {
1093         $ageInMonths -= 1;
1094     }
1095     if ( $ageInMonths > 24 ) {
1096         $age = intval($ageInMonths/12);
1097     }
1098     else  {
1099         $age = "$ageInMonths month";
1100     }
1101     return $age;
1104 function dateToDB ($date)
1106     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1107     return $date;
1111 // ----------------------------------------------------------------------------
1113  * DROPDOWN FOR COUNTRIES
1114  * 
1115  * build a dropdown with all countries from geo_country_reference
1116  * 
1117  * @param int $selected - id for selected record
1118  * @param string $name - the name/id for select form
1119  * @return void - just echo the html encoded string
1120  */
1121 function dropdown_countries($selected = 0, $name = 'country_code') {
1122     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1124     $string = "<select name='$name' id='$name'>";
1125     while ( $row = sqlFetchArray($r) ) {
1126         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1127         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1128     }
1130     $string .= '</select>';
1131     echo $string;
1135 // ----------------------------------------------------------------------------
1137  * DROPDOWN FOR YES/NO
1138  * 
1139  * build a dropdown with two options (yes - 1, no - 0)
1140  * 
1141  * @param int $selected - id for selected record
1142  * @param string $name - the name/id for select form
1143  * @return void - just echo the html encoded string 
1144  */
1145 function dropdown_yesno($selected = 0, $name = 'yesno') {
1146     $string = "<select name='$name' id='$name'>";
1148     $selected = (int)$selected;
1149     if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1150     else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1152     $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1153     $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1154     $string .= '</select>';
1156     echo $string;
1159 // ----------------------------------------------------------------------------
1161  * DROPDOWN FOR MALE/FEMALE options
1162  * 
1163  * build a dropdown with three options (unselected/male/female)
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_sex($selected = 0, $name = 'sex') {
1170     $string = "<select name='$name' id='$name'>";
1172     if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1173     else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1174     else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1176     $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1177     $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1178     $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1179     $string .= '</select>';
1181     echo $string;
1184 // ----------------------------------------------------------------------------
1186  * DROPDOWN FOR MARITAL STATUS
1187  * 
1188  * build a dropdown with marital status
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_marital($selected = 0, $name = 'status') {
1195     $string = "<select name='$name' id='$name'>";
1197     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1199     foreach ( $statii as $st ) {
1200         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1201         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1202     }
1204     $string .= '</select>';
1206     echo $string;
1209 // ----------------------------------------------------------------------------
1211  * DROPDOWN FOR PROVIDERS
1212  * 
1213  * build a dropdown with all providers
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_providers($selected = 0, $name = 'status') {
1220     $provideri = getProviderInfo();
1222     $string = "<select name='$name' id='$name'>";
1223     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1224     foreach ( $provideri as $s ) {
1225         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1226         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1227     }
1229     $string .= '</select>';
1231     echo $string;
1234 // ----------------------------------------------------------------------------
1236  * DROPDOWN FOR INSURANCE COMPANIES
1237  * 
1238  * build a dropdown with all insurers
1239  * 
1240  * @param int $selected - id for selected record
1241  * @param string $name - the name/id for select form
1242  * @return void - just echo the html encoded string
1243  */
1244 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1245     $insurancei = getInsuranceProviders();
1247     $string = "<select name='$name' id='$name'>";
1248     $string .= '<option value="0">Onbekend</option>';
1249     foreach ( $insurancei as $iid => $iname ) {
1250         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1251         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1252     }
1254     $string .= '</select>';
1256     echo $string;
1260 // ----------------------------------------------------------------------------
1262  * COUNTRY CODE
1263  * 
1264  * return the name or the country code, function of arguments
1265  * 
1266  * @param int $country_code
1267  * @param string $country_name
1268  * @return string | int - name or code
1269  */
1270 function country_code($country_code = 0, $country_name = '') {
1271     $strint = '';
1272     if ( $country_code ) {
1273         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1274     } else {
1275         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1276     }
1278     $db = $GLOBALS['adodb']['db'];
1279     $result = $db->Execute($sql);
1280     if ($result && !$result->EOF) {
1281         $strint = $result->fields['res'];
1282     }
1284     return $strint;
1287 // ----------------------------------------------------------------------------
1289  * GET INSURANCE DATA
1290  * (Dutch usage)
1291  * 
1292  * return the insurer(s) and some patient
1293  * 
1294  * @param int $pid - patient id
1295  * @param int $current 1-current 0-all insurers
1296  * @return array
1297  */
1298 function get_insurers_nl($pid = 0, $current = 1) {
1299     if ( !$pid ) return FALSE;
1301     $join = 'insurance_companies ic ON ic.id = pi.pin_provider';
1302     $r = dsql_select('*', 'patient_insurers_NL pi', array('pin_pid' => $pid), 'pin_date DESC', $join);
1304     while ( $row = mysql_fetch_array($r) ) {
1305         $rez[] = $row;
1306     } // while
1308     return ( $current ? $rez[0] : $rez );
1312 // ----------------------------------------------------------------------------
1314  * SET INSURANCE DATA
1315  * (Dutch usage)
1316  * 
1317  * set the insurer for a patient
1318  * 
1319  * @param int $pid - patient id
1320  * @param int $insid - insurer id
1321  * @return void
1322  */
1323 function set_insurer_nl($pid = 0, $insid = 0, $date = '', $policy = '') {
1324     if ( !$pid || !$insid || ($date == '0000-00-00') ) return FALSE;
1326     $fields = array('pin_pid', 'pin_provider', 'pin_date', 'pin_policy');
1327     $values = array($pid, $insid, $date, $policy);
1328     dsql_insert('patient_insurers_NL', $fields, $values);
1331 // ----------------------------------------------------------------------------
1333  * FIND THE INSURERS STATUS FOR A PATIENT
1334  * (Dutch usage)
1335  * 
1336  * return the answer for the question: is this the first insurer or not?
1337  * 
1338  * @param int $pid - patient id
1339  * @return int - the number of insurer records ( 0 - no insurer; >0 some insurers)
1340  */
1341 function total_insurers($pid = 0) {
1342     if ( !$pid ) return FALSE;
1344     $r = dsql_select('COUNT(*) AS c', 'patient_insurers_NL', array('pin_pid' => $pid));
1345     $row = mysql_fetch_array($r);
1347     return $row['c'];
1350 function DBToDate ($date)
1352     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1353     return $date;
1356 function get_patient_balance($pid) {
1357   if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1358     $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1359       "pid = '$pid' AND activity = 1");
1360     $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1361       "pid = '$pid'");
1362     $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1363       "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1364       "pid = '$pid'");
1365     return sprintf('%01.2f', $brow['amount'] + $srow['amount']
1366       - $drow['payments'] - $drow['adjustments']);
1367   }
1368   else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1369     // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1370     $conn = $GLOBALS['adodb']['db'];
1371     $customer_info['id'] = 0;
1372     $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1373       "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1374       "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1375       "im.foreign_table = 'customer'";
1376     $result = $conn->Execute($sql);
1377     if($result && !$result->EOF) {
1378       $customer_info['id'] = $result->fields['foreign_id'];
1379     }
1380     $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1381     $ws = new WSWrapper($function);
1382     if(is_numeric($ws->value)) {
1383       return sprintf('%01.2f', $ws->value);
1384     }
1385   }
1386   return '';