bug fix by visolveemr: the don't save link fix
[openemr.git] / library / patient.inc
blobeeb0b57384f8fb1a29f437ca55e67f007799ffd8
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);
96 // Get one facility row.  If the ID is not specified, then get either the
97 // "main" (billing) facility, or the default facility of the currently
98 // logged-in user.  This was created to support genFacilityTitle() but
99 // may find additional uses.
101 function getFacility($facid=0) {
102   if ($facid > 0) {
103     $query = "SELECT * FROM facility WHERE id = '$facid'";
104   }
105   else if ($facid == 0) {
106     $query = "SELECT * FROM facility ORDER BY " .
107       "billing_location DESC, service_location, id LIMIT 1";
108   }
109   else {
110     $query = "SELECT facility.* FROM users, facility WHERE " .
111       "users.id = '" . $_SESSION['authUserID'] . "' AND " .
112       "facility.id = users.facility_id";
113   }
114   return sqlQuery($query);
117 // Generate a report title including report name and facility name, address
118 // and phone.
120 function genFacilityTitle($repname='', $facid=0) {
121   $s = '';
122   $s .= "<table class='ftitletable'>\n";
123   $s .= " <tr>\n";
124   $s .= "  <td class='ftitlecell1'>$repname</td>\n";
125   $s .= "  <td class='ftitlecell2'>\n";
126   $r = getFacility($facid);
127   if (!empty($r)) {
128     $s .= "<b>" . $r['name'] . "</b>\n";
129     if ($r['street']) $s .= "<br />" . $r['street'] . "\n";
130     if ($r['city'] || $r['state'] || $r['postal_code']) {
131       $s .= "<br />";
132       if ($r['city']) $s .= $r['city'];
133       if ($r['state']) {
134         if ($r['city']) $s .= ", \n";
135         $s .= $r['state'];
136       }
137       if ($r['postal_code']) $s .= " " . $r['postal_code'];
138       $s .= "\n";
139     }
140     if ($r['country_code']) $s .= "<br />" . $r['country_code'] . "\n";
141     if (preg_match('/[1-9]/', $r['phone'])) $s .= "<br />" . $r['phone'] . "\n";
142   }
143   $s .= "  </td>\n";
144   $s .= " </tr>\n";
145   $s .= "</table>\n";
146   return $s;
150 GET FACILITIES
152 returns all facilities or just the id for the first one
153 (FACILITY FILTERING (lemonsoftware))
155 @param string - if 'first' return first facility ordered by id
156 @return array | int for 'first' case
158 function getFacilities($first = '') {
159     $r = sqlStatement("SELECT * FROM facility ORDER BY id");
160     $ret = array();
161     while ( $row = sqlFetchArray($r) ) {
162        $ret[] = $row;
165         if ( $first == 'first') {
166             return $ret[0]['id'];
167         } else {
168             return $ret;
169         }
173 GET SERVICE FACILITIES
175 returns all service_location facilities or just the id for the first one
176 (FACILITY FILTERING (CHEMED))
178 @param string - if 'first' return first facility ordered by id
179 @return array | int for 'first' case
181 function getServiceFacilities($first = '') {
182     $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
183     $ret = array();
184     while ( $row = sqlFetchArray($r) ) {
185        $ret[] = $row;
188         if ( $first == 'first') {
189             return $ret[0]['id'];
190         } else {
191             return $ret;
192         }
195 //(CHEMED) facility filter
196 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
197     $param1 = "";
198     if ($providers_only) {
199       // $param1 = " AND authorized=1 AND ( info IS NULL OR info NOT LIKE '%Nocalendar%' ) ";
200       $param1 = " AND authorized = 1 AND calendar = 1 ";
201     }
203     //--------------------------------
204     //(CHEMED) facility filter
205     $param2 = "";
206     if ($facility) {
207         // $param2 = " AND facility_id = $facility ";
208         $param2 = " AND (facility_id = $facility 
209           OR  $facility IN
210                 (select facility_id 
211                 from users_facility
212                 where tablename = 'users'
213                 and table_id = id)
214                 )
215           ";
216     }
217     //--------------------------------
219     $command = "=";
220     if ($providerID == "%") {
221         $command = "like";
222     }
223     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
224         "from users where username != '' and active = 1 and id $command '" .
225         mysql_real_escape_string($providerID) . "' " . $param1 . $param2;
226     // sort by last name -- JRM June 2008
227     $query .= " ORDER BY lname, fname ";
228     $rez = sqlStatement($query);
229     for($iter=0; $row=sqlFetchArray($rez); $iter++)
230         $returnval[$iter]=$row;
232     //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
233     //accessible from $resultval['key']
235     if($iter==1) {
236         $akeys = array_keys($returnval[0]);
237         foreach($akeys as $key) {
239             $returnval[0][$key] = $returnval[0][$key];
240         }
241     }
242     return $returnval;
245 //same as above but does not reduce if only 1 row returned
246 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
247     $param1 = "";
248     if ($providers_only) {
249         $param1 = "AND authorized=1";
250     }
251     $command = "=";
252     if ($providerID == "%") {
253         $command = "like";
254     }
255     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
256         "from users where active = 1 and username != '' and id $command '" .
257         mysql_real_escape_string($providerID) . "' " . $param1;
259     $rez = sqlStatement($query);
260     for($iter=0; $row=sqlFetchArray($rez); $iter++)
261         $returnval[$iter]=$row;
263     return $returnval;
266 function getProviderName($providerID) {
267     $pi = getProviderInfo($providerID);
268     if (strlen($pi[0]["lname"]) > 0) {
269         return $pi[0]['fname'] . " " . $pi[0]['lname'];
270     }
271     return "";
274 function getProviderId($providerName) {
275     $query = "select id from users where username = '". mysql_real_escape_string($providerName)."'";
276     $rez = sqlStatement($query);
277     for($iter=0; $row=sqlFetchArray($rez); $iter++)
278         $returnval[$iter]=$row;
279     return $returnval;
282 function getEthnoRacials() {
283     $returnval = array("");
284     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
285     $rez = sqlStatement($sql);
286     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
287         if (($row["ethnoracial"] != "")) {
288             array_push($returnval, $row["ethnoracial"]);
289         }
290     }
291     return $returnval;
294 function getHistoryData($pid, $given = "*")
296     $sql = "select $given from history_data where pid='$pid' order by date DESC limit 0,1";
297     return sqlQuery($sql);
300 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
301 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
303   $sql = "select $given from insurance_data as insd " .
304     "left join insurance_companies as ic on ic.id = insd.provider " .
305     "where pid = '$pid' and type = '$type' order by date DESC limit 1";
306   return sqlQuery($sql);
309 function getInsuranceDataByDate($pid, $date, $type,
310   $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
311 { // this must take the date in the following manner: YYYY-MM-DD
312   // this function recalls the insurance value that was most recently enterred from the
313   // given date. it will call up most recent records up to and on the date given,
314   // but not records enterred after the given date
315   $sql = "select $given from insurance_data as insd " .
316     "left join insurance_companies as ic on ic.id = provider " .
317     "where pid = '$pid' and date_format(date,'%Y-%m-%d') <= '$date' and " .
318     "type='$type' order by date DESC limit 1";
319   return sqlQuery($sql);
322 function getEmployerData($pid, $given = "*")
324     $sql = "select $given from employer_data where pid='$pid' order by date DESC limit 0,1";
325     return sqlQuery($sql);
328 function _set_patient_inc_count($limit, $count, $where) {
329   // When the limit is exceeded, find out what the unlimited count would be.
330   $GLOBALS['PATIENT_INC_COUNT'] = $count;
331   // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
332   if ($limit != "all") {
333     $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where");
334     $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
335   }
338 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")
340     // Allow the last name to be followed by a comma and some part of a first name.
341     // New behavior for searches:
342     // Allows comma alone followed by some part of a first name
343     // If the first letter of either name is capital, searches for name starting
344     // with given substring (the expected behavior).  If it is lower case, it
345     // it searches for the substring anywhere in the name.  This applies to either
346     // last name or first name or both.  The arbitrary limit of 100 results is set
347     // in the sql query below. --Mark Leeds
348     $lname = trim($lname);
349     $fname = '';
350      if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
351          $lname = trim($matches[1]);
352          $fname = trim($matches[2]);
353     }
354     $search_for_pieces1 = '';
355     $search_for_pieces2 = '';
356     if ($lname{0} != strtoupper($lname{0})) {$search_for_pieces1 = '%';}
357     if ($fname{0} != strtoupper($fname{0})) {$search_for_pieces2 = '%';}
359     $where = "lname LIKE '" . $search_for_pieces1 . "$lname%' " .
360         "AND fname LIKE '" . $search_for_pieces2 . "$fname%' ";
361         if (!empty($GLOBALS['pt_restrict_field'])) {
362                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
363                         $where .= "AND ( patient_data.".$GLOBALS['pt_restrict_field']." = ( SELECT facility_id FROM users WHERE username = '".$_SESSION{"authUser"}."') OR patient_data.".$GLOBALS['pt_restrict_field']." = '' ) ";
364                 }
365         }
367     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
368     if ($limit != "all") $sql .= " LIMIT $start, $limit";
370     $rez = sqlStatement($sql);
372     for($iter=0; $row=sqlFetchArray($rez); $iter++)
373         $returnval[$iter] = $row;
375     _set_patient_inc_count($limit, count($returnval), $where);
376     return $returnval;
379 function 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")
381     
382     $where = "pubpid LIKE '$pid%' ";
383         if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
384                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
385                         $where .= "AND ( patient_data.".$GLOBALS['pt_restrict_field']." = ( SELECT facility_id FROM users WHERE username = '".$_SESSION{"authUser"}."') OR patient_data.".$GLOBALS['pt_restrict_field']." = '' ) ";
386                 }
387         }
389     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
390     if ($limit != "all") $sql .= " limit $start, $limit";
391     $rez = sqlStatement($sql);
392     for($iter=0; $row=sqlFetchArray($rez); $iter++)
393         $returnval[$iter]=$row;
395     _set_patient_inc_count($limit, count($returnval), $where);
396     return $returnval;
399 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")
401         $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like ('%Employer%' ) AND uor !=0" );
403     $where = "";
404     for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
405         if ( $iter > 0 ) {
406            $where .= " or ";
407         }
408         $where .= " ".$row["field_id"]." like '%".$searchTerm."%' ";
409     }
411     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
412     if ($limit != "all") $sql .= " limit $start, $limit";
413     $rez = sqlStatement($sql);
414     for($iter=0; $row=sqlFetchArray($rez); $iter++)
415         $returnval[$iter]=$row;
417     _set_patient_inc_count($limit, count($returnval), $where);
418     return $returnval;
421 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" )
423         $layoutCols = split( '~', $searchFields );
425     $where = "";
426     $i = 0;
427     foreach ($layoutCols as $val ) {
428                 if ( $i > 0 ) {
429                    $where .= " or ";
430                 }
431                 $where .= " ".$val." like '%".$searchTerm."%' ";
432                 $i++;
433         }
435     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
436     if ($limit != "all") $sql .= " limit $start, $limit";
437     $rez = sqlStatement($sql);
438     for($iter=0; $row=sqlFetchArray($rez); $iter++)
439         $returnval[$iter]=$row;
441     _set_patient_inc_count($limit, count($returnval), $where);
442     return $returnval;
446 // return a collection of Patient PIDs
447 // new arg style by JRM March 2008
448 // 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")
449 function getPatientPID($args)
451     $pid = "%";
452     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
453     $orderby = "lname ASC, fname ASC";
454     $limit="all";
455     $start="0";
457     // alter default values if defined in the passed in args
458     if (isset($args['pid'])) { $pid = $args['pid']; }
459     if (isset($args['given'])) { $given = $args['given']; }
460     if (isset($args['orderby'])) { $orderby = $args['orderby']; }
461     if (isset($args['limit'])) { $limit = $args['limit']; }
462     if (isset($args['start'])) { $start = $args['start']; }
464     $command = "=";
465     if ($pid == -1) $pid = "%";
466     elseif (empty($pid)) $pid = "NULL";
468     if (strstr($pid,"%")) $command = "like";
470     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
471     if ($limit != "all") $sql .= " limit $start, $limit";
473     $rez = sqlStatement($sql);
474     for($iter=0; $row=sqlFetchArray($rez); $iter++)
475         $returnval[$iter]=$row;
477     return $returnval;
480 /* return a patient's name in the format LAST, FIRST */
481 function getPatientName($pid) {
482     if (empty($pid)) return "";
483     $patientData = getPatientPID(array("pid"=>$pid));
484     if (empty($patientData[0]['lname'])) return "";
485     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
486     return $patientName;
489 /* find patient data by DOB */
490 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
492     $DOB = fixDate($DOB, $DOB);
493     $where = "DOB like '$DOB%' ";
494         if (!empty($GLOBALS['pt_restrict_field'])) {
495                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
496                         $where .= "AND ( patient_data.".$GLOBALS['pt_restrict_field']." = ( SELECT facility_id FROM users WHERE username = '".$_SESSION{"authUser"}."') OR patient_data.".$GLOBALS['pt_restrict_field']." = '' ) ";
497                 }
498         }
500     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
502     if ($limit != "all") $sql .= " LIMIT $start, $limit";
504     $rez = sqlStatement($sql);
505     for($iter=0; $row=sqlFetchArray($rez); $iter++)
506         $returnval[$iter]=$row;
508     _set_patient_inc_count($limit, count($returnval), $where);
509     return $returnval;
512 /* find patient data by SSN */
513 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
515     $where = "ss LIKE '$ss%'";
516     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
517     if ($limit != "all") $sql .= " LIMIT $start, $limit";
519     $rez = sqlStatement($sql);
520     for($iter=0; $row=sqlFetchArray($rez); $iter++)
521         $returnval[$iter]=$row;
523     _set_patient_inc_count($limit, count($returnval), $where);
524     return $returnval;
527 //(CHEMED) Search by phone number
528 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
530     $phone = ereg_replace( "[[:punct:]]","", $phone );
531     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP '$phone'";
532     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
533     if ($limit != "all") $sql .= " LIMIT $start, $limit";
535     $rez = sqlStatement($sql);
536     for($iter=0; $row=sqlFetchArray($rez); $iter++)
537         $returnval[$iter]=$row;
539     _set_patient_inc_count($limit, count($returnval), $where);
540     return $returnval;
543 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
545     $sql="select $given from patient_data order by $orderby";
547     if ($limit != "all")
548         $sql .= " limit $start, $limit";
550     $rez = sqlStatement($sql);
551     for($iter=0; $row=sqlFetchArray($rez); $iter++)
552         $returnval[$iter]=$row;
554     return $returnval;
557 //----------------------input functions
558 function newPatientData(    $db_id="",
559                 $title = "",
560                 $fname = "",
561                 $lname = "",
562                 $mname = "",
563                 $sex = "",
564                 $DOB = "",
565                 $street = "",
566                 // DBC dutch use
567                 $nstreet = "",
568                 $nnr = "",
569                 $nadd = "",
570                 // EOS DBC
571                 $postal_code = "",
572                 $city = "",
573                 $state = "",
574                 $country_code = "",
575                 $ss = "",
576                 $occupation = "",
577                 $phone_home = "",
578                 $phone_biz = "",
579                 $phone_contact = "",
580                 $status = "",
581                 $contact_relationship = "",
582                 $referrer = "",
583                 $referrerID = "",
584                 $email = "",
585                 $language = "",
586                 $ethnoracial = "",
587                 $interpretter = "",
588                 $migrantseasonal = "",
589                 $family_size = "",
590                 $monthly_income = "",
591                 $homeless = "",
592                 $financial_review = "",
593                 $pubpid = "",
594                 $pid = "MAX(pid)+1",
595                 $providerID = "",
596                 $genericname1 = "",
597                 $genericval1 = "",
598                 $genericname2 = "",
599                 $genericval2 = "",
600                 $phone_cell = "",
601                 $hipaa_mail = "",
602                 $hipaa_voice = "",
603                 $squad = 0,
604                 $pharmacy_id = 0,
605                 $drivers_license = "",
606                 $hipaa_notice = "",
607                 $hipaa_message = "",
608                 $regdate = "",
609                 // dutch specific
610                 $prefixlast = "",
611                 $prefixlastpartner = "",
612                 $lastpartner = "",
613                 $initials = "",
614                 $provider_data = array(),
615                 $referer_data = array()
616                 // DBC Dutch System
618             )
620     $DOB = fixDate($DOB);
621     $regdate = fixDate($regdate);
623     $fitness = 0;
624     $referral_source = '';
625     if ($pid) {
626         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
627         // Check for brain damage:
628         if ($db_id != $rez['id']) {
629             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
630               $rez['id'] . "' to '$db_id' for pid '$pid'";
631             die($errmsg);
632         }
633         $fitness = $rez['fitness'];
634         $referral_source = $rez['referral_source'];
635     }
637     // Get the default price level.
638     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
639       "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
640     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
642     $query = ("replace into patient_data set
643         id='$db_id',
644         title='$title',
645         fname='$fname',
646         lname='$lname',
647         mname='$mname',
648         sex='$sex',
649         DOB='$DOB',
650         street='$street',
651         postal_code='$postal_code',
652         city='$city',
653         state='$state',
654         country_code='$country_code',
655         drivers_license='$drivers_license',
656         ss='$ss',
657         occupation='$occupation',
658         phone_home='$phone_home',
659         phone_biz='$phone_biz',
660         phone_contact='$phone_contact',
661         status='$status',
662         contact_relationship='$contact_relationship',
663         referrer='$referrer',
664         referrerID='$referrerID',
665         email='$email',
666         language='$language',
667         ethnoracial='$ethnoracial',
668         interpretter='$interpretter',
669         migrantseasonal='$migrantseasonal',
670         family_size='$family_size',
671         monthly_income='$monthly_income',
672         homeless='$homeless',
673         financial_review='$financial_review',
674         pubpid='$pubpid',
675         pid = $pid,
676         providerID = '$providerID',
677         genericname1 = '$genericname1',
678         genericval1 = '$genericval1',
679         genericname2 = '$genericname2',
680         genericval2 = '$genericval2',
681         phone_cell = '$phone_cell',
682         pharmacy_id = '$pharmacy_id',
683         hipaa_mail = '$hipaa_mail',
684         hipaa_voice = '$hipaa_voice',
685         hipaa_notice = '$hipaa_notice',
686         hipaa_message = '$hipaa_message',
687         squad = '$squad',
688         fitness='$fitness',
689         referral_source='$referral_source',
690         regdate='$regdate',
691         pricelevel='$pricelevel',
692         date=NOW()");
694     $id = sqlInsert($query);
696     // DBC 
697     if ( !$db_id ) {
698       // find the last inserted id for new patient case
699       $db_id = empty($GLOBALS['dutchpc']) ? mysql_insert_id() : dsql_lastid();
700     }
701     // EOS DBC
703     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
705          // dutch use
706         if ( $GLOBALS['dutchpc'] ) {
707                 $init = strtoupper(preg_replace('/[\s\.\-_0-9]/','',$initials));
708                 
709             $querynl = ("REPLACE INTO patient_data_NL SET
710                     pdn_id = '$db_id',
711                     pdn_pxlast = '$prefixlast',
712                     pdn_pxlastpar = '$prefixlastpartner',
713                     pdn_lastpar = '$lastpartner',
714                     pdn_street = '$nstreet',
715                     pdn_number = '$nnr',
716                     pdn_addition = '$nadd',
717                     pdn_initials = '$init'
718             ");
720             if ( $db_id ) $idnl = sqlInsert($querynl); // only if exists
721         }
722         // EOS dutch use
725        // DBC Dutch System
726         // provider first
727         if ( $GLOBALS['dutchpc'] && $db_id && $provider_data && $referer_data) {
728            $querypr = ("INSERT INTO cl_providers(pro_pid, pro_company, pro_initials, pro_prefix, pro_lname,
729                    pro_street, pro_number, pro_addition, pro_city, pro_zipcode,  pro_phone, pro_fax, pro_email, pro_referer ) 
730                    VALUES ($db_id, '{$provider_data['pro_company']}', '{$provider_data['pro_initials']}',
731                   '{$provider_data['pro_prefix']}', '{$provider_data['pro_lname']}',  
732                   '{$provider_data['pro_street']}', '{$provider_data['pro_number']}', '{$provider_data['pro_addition']}', 
733                   '{$provider_data['pro_city']}',  '{$provider_data['pro_zipcode']}',
734                   '{$provider_data['pro_phone']}', '{$provider_data['pro_fax']}',  '{$provider_data['pro_email']}', 
735                   '{$provider_data['pro_referer']}') 
736                   ON DUPLICATE KEY UPDATE  pro_referer = '{$provider_data['pro_referer']}',
737                   pro_company = '{$provider_data['pro_company']}', pro_initials = '{$provider_data['pro_initials']}',
738                   pro_prefix = '{$provider_data['pro_prefix']}',
739                   pro_lname = '{$provider_data['pro_lname']}', pro_street = '{$provider_data['pro_street']}',
740                   pro_number = '{$provider_data['pro_number']}', pro_addition = '{$provider_data['pro_addition']}',
741                   pro_city = '{$provider_data['pro_city']}', pro_zipcode = '{$provider_data['pro_zipcode']}',
742                   pro_phone = '{$provider_data['pro_phone']}', pro_fax = '{$provider_data['pro_fax']}',
743                   pro_email = '{$provider_data['pro_email']}'
744             ");
745            $idpr = sqlInsert($querypr);
747         // referer if it's the case
748         if ( $referer_data['ref_code'] ) {
749            $queryre = ("INSERT INTO cl_referers(ref_pid, ref_code, ref_company, ref_initials, ref_prefix,
750                    ref_lname, ref_street, ref_number, ref_addition, ref_city, ref_zipcode,  ref_phone, ref_fax,
751                    ref_email) 
752                    VALUES ($db_id, {$referer_data['ref_code']}, '{$referer_data['ref_company']}', 
753                    '{$referer_data['ref_initials']}', '{$referer_data['ref_prefix']}',
754                    '{$referer_data['ref_lname']}', '{$referer_data['ref_street']}', '{$referer_data['ref_number']}', 
755                    '{$referer_data['ref_addition']}', '{$referer_data['ref_city']}', '{$referer_data['ref_zipcode']}',
756                   '{$referer_data['ref_phone']}', '{$referer_data['ref_fax']}',  '{$referer_data['ref_email']}')
757                   ON DUPLICATE KEY UPDATE ref_code = {$referer_data['ref_code']},
758                   ref_company = '{$referer_data['ref_company']}', ref_initials = '{$referer_data['ref_initials']}',
759                   ref_prefix = '{$referer_data['ref_prefix']}',
760                   ref_lname = '{$referer_data['ref_lname']}', ref_street = '{$referer_data['ref_street']}',
761                   ref_number = '{$referer_data['ref_number']}', ref_addition = '{$referer_data['ref_addition']}',
762                   ref_city = '{$referer_data['ref_city']}', ref_zipcode = '{$referer_data['ref_zipcode']}',
763                   ref_phone = '{$referer_data['ref_phone']}', ref_fax = '{$referer_data['ref_fax']}',
764                   ref_email = '{$referer_data['ref_email']}'
765             ");
766            $idre = sqlInsert($queryre);
767         } 
768         } // if globals
769         // EOS DBC
771     sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
772                 $phone_biz,$phone_cell,$email,$pid);
774     return $foo['pid'];
777 // Supported input date formats are:
778 //   mm/dd/yyyy
779 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
780 //   yyyy/mm/dd
781 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
783 function fixDate($date, $default="0000-00-00") {
784     $fixed_date = $default;
785     $date = trim($date);
786     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
787         $dmy = preg_split("'[/.-]'", $date);
788         if ($dmy[0] > 99) {
789             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
790         } else {
791             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
792               if ($dmy[2] < 1000) $dmy[2] += 1900;
793               if ($dmy[2] < 1910) $dmy[2] += 100;
794             }
795             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
796         }
797     }
799     return $fixed_date;
802 // Create or update patient data from an array.
804 function updatePatientData($pid, $new, $create=false)
806   /*******************************************************************
807     $real = getPatientData($pid);
808     $new['DOB'] = fixDate($new['DOB']);
809     while(list($key, $value) = each ($new))
810         $real[$key] = $value;
811     $real['date'] = "'+NOW()+'";
812     $real['id'] = "";
813     $sql = "insert into patient_data set ";
814     while(list($key, $value) = each($real))
815         $sql .= $key." = '$value', ";
816     $sql = substr($sql, 0, -2);
817     return sqlInsert($sql);
818   *******************************************************************/
820   // The above was broken, though seems intent to insert a new patient_data
821   // row for each update.  A good idea, but nothing is doing that yet so
822   // the code below does not yet attempt it.
824   $new['DOB'] = fixDate($new['DOB']);
826   if ($create) {
827     $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
828     foreach ($new as $key => $value) {
829       if ($key == 'id') continue;
830       $sql .= ", $key = '$value'";
831     }
832     $db_id = sqlInsert($sql);
833   }
834   else {
835     $db_id = $new['id'];
836     $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
837     // Check for brain damage:
838     if ($pid != $rez['pid']) {
839       $errmsg = "Internal error: Attempt to change patient data with pid = '" .
840         $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
841       die($errmsg);
842     }
843     $sql = "UPDATE patient_data SET date = NOW()";
844     foreach ($new as $key => $value) {
845       $sql .= ", $key = '$value'";
846     }
847     $sql .= " WHERE id = '$db_id'";
848     sqlStatement($sql);
849   }
851   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
852   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
853     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
854     $rez['phone_cell'],$rez['email'],$rez['pid']);
856   return $db_id;
859 function newEmployerData(    $pid,
860                 $name = "",
861                 $street = "",
862                 $postal_code = "",
863                 $city = "",
864                 $state = "",
865                 $country = ""
866             )
868     return sqlInsert("insert into employer_data set
869         name='$name',
870         street='$street',
871         postal_code='$postal_code',
872         city='$city',
873         state='$state',
874         country='$country',
875         pid='$pid',
876         date=NOW()
877         ");
880 // Create or update employer data from an array.
882 function updateEmployerData($pid, $new, $create=false)
884   $colnames = array('name','street','city','state','postal_code','country');
886   if ($create) {
887     $set .= "pid = '$pid', date = NOW()";
888     foreach ($colnames as $key) {
889       $value = isset($new[$key]) ? $new[$key] : '';
890       $set .= ", $key = '$value'";
891     }
892     return sqlInsert("INSERT INTO employer_data SET $set");
893   }
894   else {
895     $set = '';
896     $old = getEmployerData($pid);
897     $modified = false;
898     foreach ($colnames as $key) {
899       $value = empty($old[$key]) ? '' : addslashes($old[$key]);
900       if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
901         $value = $new[$key];
902         $modified = true;
903       }
904       $set .= "$key = '$value', ";
905     }
906     if ($modified) {
907       $set .= "pid = '$pid', date = NOW()";
908       return sqlInsert("INSERT INTO employer_data SET $set");
909     }
910     return $old['id'];
911   }
914 // This updates or adds the given insurance data info, while retaining any
915 // previously added insurance_data rows that should be preserved.
916 // This does not directly support the maintenance of non-current insurance.
918 function newInsuranceData(
919   $pid,
920   $type = "",
921   $provider = "",
922   $policy_number = "",
923   $group_number = "",
924   $plan_name = "",
925   $subscriber_lname = "",
926   $subscriber_mname = "",
927   $subscriber_fname = "",
928   $subscriber_relationship = "",
929   $subscriber_ss = "",
930   $subscriber_DOB = "",
931   $subscriber_street = "",
932   $subscriber_postal_code = "",
933   $subscriber_city = "",
934   $subscriber_state = "",
935   $subscriber_country = "",
936   $subscriber_phone = "",
937   $subscriber_employer = "",
938   $subscriber_employer_street = "",
939   $subscriber_employer_city = "",
940   $subscriber_employer_postal_code = "",
941   $subscriber_employer_state = "",
942   $subscriber_employer_country = "",
943   $copay = "",
944   $subscriber_sex = "",
945   $effective_date = "0000-00-00",
946   $accept_assignment = "TRUE")
948   if (strlen($type) <= 0) return FALSE;
950   // If a bad date was passed, err on the side of caution.
951   $effective_date = fixDate($effective_date, date('Y-m-d'));
953   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
954     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
955   $idrow = sqlFetchArray($idres);
957   // Replace the most recent entry in any of the following cases:
958   // * Its effective date is >= this effective date.
959   // * It is the first entry and it has no (insurance) provider.
960   // * There is no encounter that is earlier than the new effective date but
961   //   on or after the old effective date.
962   // Otherwise insert a new entry.
964   $replace = false;
965   if ($idrow) {
966     if (strcmp($idrow['date'], $effective_date) > 0) {
967       $replace = true;
968     }
969     else {
970       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
971         $replace = true;
972       }
973       else {
974         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
975           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
976           "date >= '" . $idrow['date'] . " 00:00:00'");
977         if ($ferow['count'] == 0) $replace = true;
978       }
979     }
980   }
982   if ($replace) {
984     // TBD: This is a bit dangerous in that a typo in entering the effective
985     // date can wipe out previous insurance history.  So we want some data
986     // entry validation somewhere.
987     sqlStatement("DELETE FROM insurance_data WHERE " .
988       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
989       "id != " . $idrow['id']);
991     $data = array();
992     $data['type'] = $type;
993     $data['provider'] = $provider;
994     $data['policy_number'] = $policy_number;
995     $data['group_number'] = $group_number;
996     $data['plan_name'] = $plan_name;
997     $data['subscriber_lname'] = $subscriber_lname;
998     $data['subscriber_mname'] = $subscriber_mname;
999     $data['subscriber_fname'] = $subscriber_fname;
1000     $data['subscriber_relationship'] = $subscriber_relationship;
1001     $data['subscriber_ss'] = $subscriber_ss;
1002     $data['subscriber_DOB'] = $subscriber_DOB;
1003     $data['subscriber_street'] = $subscriber_street;
1004     $data['subscriber_postal_code'] = $subscriber_postal_code;
1005     $data['subscriber_city'] = $subscriber_city;
1006     $data['subscriber_state'] = $subscriber_state;
1007     $data['subscriber_country'] = $subscriber_country;
1008     $data['subscriber_phone'] = $subscriber_phone;
1009     $data['subscriber_employer'] = $subscriber_employer;
1010     $data['subscriber_employer_city'] = $subscriber_employer_city;
1011     $data['subscriber_employer_street'] = $subscriber_employer_street;
1012     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1013     $data['subscriber_employer_state'] = $subscriber_employer_state;
1014     $data['subscriber_employer_country'] = $subscriber_employer_country;
1015     $data['copay'] = $copay;
1016     $data['subscriber_sex'] = $subscriber_sex;
1017     $data['pid'] = $pid;
1018     $data['date'] = $effective_date;
1019     $data['accept_assignment'] = $accept_assignment;
1020     updateInsuranceData($idrow['id'], $data);
1021     return $idrow['id'];
1022   }
1023   else {
1024     return sqlInsert("INSERT INTO insurance_data SET
1025       type = '$type',
1026       provider = '$provider',
1027       policy_number = '$policy_number',
1028       group_number = '$group_number',
1029       plan_name = '$plan_name',
1030       subscriber_lname = '$subscriber_lname',
1031       subscriber_mname = '$subscriber_mname',
1032       subscriber_fname = '$subscriber_fname',
1033       subscriber_relationship = '$subscriber_relationship',
1034       subscriber_ss = '$subscriber_ss',
1035       subscriber_DOB = '$subscriber_DOB',
1036       subscriber_street = '$subscriber_street',
1037       subscriber_postal_code = '$subscriber_postal_code',
1038       subscriber_city = '$subscriber_city',
1039       subscriber_state = '$subscriber_state',
1040       subscriber_country = '$subscriber_country',
1041       subscriber_phone = '$subscriber_phone',
1042       subscriber_employer = '$subscriber_employer',
1043       subscriber_employer_city = '$subscriber_employer_city',
1044       subscriber_employer_street = '$subscriber_employer_street',
1045       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1046       subscriber_employer_state = '$subscriber_employer_state',
1047       subscriber_employer_country = '$subscriber_employer_country',
1048       copay = '$copay',
1049       subscriber_sex = '$subscriber_sex',
1050       pid = '$pid',
1051       date = '$effective_date',
1052       accept_assignment = '$accept_assignment'
1053     ");
1054   }
1057 // This is used internally only.
1058 function updateInsuranceData($id, $new)
1060   $fields = sqlListFields("insurance_data");
1061   $use = array();
1063   while(list($key, $value) = each ($new)) {
1064     if (in_array($key, $fields)) {
1065       $use[$key] = $value;
1066     }
1067   }
1069   $sql = "UPDATE insurance_data SET ";
1070   while(list($key, $value) = each($use))
1071     $sql .= $key . " = '$value', ";
1072   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1074   sqlStatement($sql);
1077 function newHistoryData($pid, $new=false) {
1078   $sql = "insert into history_data set pid = '$pid', date = NOW()";
1079   if ($new) {
1080     while(list($key, $value) = each($new)) {
1081       if (!get_magic_quotes_gpc()) $value = addslashes($value);
1082       $sql .= ", $key = '$value'";
1083     }
1084   }
1085   return sqlInsert($sql);
1088 function updateHistoryData($pid,$new)
1090         $real = getHistoryData($pid);
1091         while(list($key, $value) = each ($new))
1092                 $real[$key] = $value;
1093         $real['date'] = "'+NOW()+'";
1094         $real['id'] = "";
1096         $sql = "insert into history_data set ";
1097         while(list($key, $value) = each($real))
1098                 $sql .= $key." = '$value', ";
1099         $sql = substr($sql, 0, -2);
1102         return sqlInsert($sql);
1105 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1106                 $phone_biz,$phone_cell,$email,$pid="")
1108     if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1109     if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1111     $db = $GLOBALS['adodb']['db'];
1112     $customer_info = array();
1114     $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1115     $result = $db->Execute($sql);
1116     if ($result && !$result->EOF) {
1117         $customer_info['foreign_update'] = true;
1118         $customer_info['foreign_id'] = $result->fields['foreign_id'];
1119         $customer_info['foreign_table'] = $result->fields['foreign_table'];
1120     }
1122     ///xml rpc code to connect to accounting package and add user to it
1123     $customer_info['firstname'] = $fname;
1124     $customer_info['lastname'] = $lname;
1125     $customer_info['address'] = $street;
1126     $customer_info['suburb'] = $city;
1127     $customer_info['state'] = $state;
1128     $customer_info['postcode'] = $postal_code;
1130     //ezybiz wants state as a code rather than abbreviation
1131     $customer_info['geo_zone_id'] = "";
1132     $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1133     $db = $GLOBALS['adodb']['db'];
1134     $result = $db->Execute($sql);
1135     if ($result && !$result->EOF) {
1136         $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1137     }
1139     //ezybiz wants country as a code rather than abbreviation
1140     $customer_info['geo_country_id'] = "";
1141     $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1142     $db = $GLOBALS['adodb']['db'];
1143     $result = $db->Execute($sql);
1144     if ($result && !$result->EOF) {
1145         $customer_info['geo_country_id'] = $result->fields['countries_id'];
1146     }
1148     $customer_info['phone1'] = $phone_home;
1149     $customer_info['phone1comment'] = "Home Phone";
1150     $customer_info['phone2'] = $phone_biz;
1151     $customer_info['phone2comment'] = "Business Phone";
1152     $customer_info['phone3'] = $phone_cell;
1153     $customer_info['phone3comment'] = "Cell Phone";
1154     $customer_info['email'] = $email;
1155     $customer_info['customernumber'] = $pid;
1157     $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1158     $ws = new WSWrapper($function);
1160     // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1161     if (is_numeric($ws->value)) {
1162         $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1163         $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1164     }
1167 // Returns Age 
1168 //   in months if < 2 years old
1169 //   in years  if > 2 years old
1170 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1171 // (optional) nowYMD is a date in YYYYMMDD format
1172 function getPatientAge($dobYMD, $nowYMD=null)
1174     // strip any dashes from the DOB
1175     $dobYMD = preg_replace("/-/", "", $dobYMD);
1176     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1177     
1178     // set the 'now' date values
1179     if ($nowYMD == null) {
1180         $nowDay = date("d");
1181         $nowMonth = date("m");
1182         $nowYear = date("Y");
1183     }
1184     else {
1185         $nowDay = substr($nowYMD,6,2);
1186         $nowMonth = substr($nowYMD,4,2);
1187         $nowYear = substr($nowYMD,0,4);
1188     }
1190     $dayDiff = $nowDay - $dobDay;
1191     $monthDiff = $nowMonth - $dobMonth;
1192     $yearDiff = $nowYear - $dobYear;
1194     $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1196     if ( $ageInMonths > 24 ) {
1197         $age = $yearDiff;
1198         if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1199         else if ($monthDiff < 0) { $age -= 1; }
1200     }
1201     else  {
1202         $age = "$ageInMonths month"; 
1203     }
1205     return $age;
1209 // Returns Age in days
1210 //   in months if < 2 years old
1211 //   in years  if > 2 years old
1212 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1213 // (optional) nowYMD is a date in YYYYMMDD format
1214 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1215     $age = -1;
1217     // strip any dashes from the DOB
1218     $dobYMD = preg_replace("/-/", "", $dobYMD);
1219     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1220     
1221     // set the 'now' date values
1222     if ($nowYMD == null) {
1223         $nowDay = date("d");
1224         $nowMonth = date("m");
1225         $nowYear = date("Y");
1226     }
1227     else {
1228         $nowDay = substr($nowYMD,6,2);
1229         $nowMonth = substr($nowYMD,4,2);
1230         $nowYear = substr($nowYMD,0,4);
1231     }
1233     // do the date math
1234     $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1235     $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1236     $timediff = $nowtime - $dobtime;
1237     $age = $timediff / 86400;
1239     return $age;
1242 function dateToDB ($date)
1244     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1245     return $date;
1249 // ----------------------------------------------------------------------------
1251  * DROPDOWN FOR COUNTRIES
1252  * 
1253  * build a dropdown with all countries from geo_country_reference
1254  * 
1255  * @param int $selected - id for selected record
1256  * @param string $name - the name/id for select form
1257  * @return void - just echo the html encoded string
1258  */
1259 function dropdown_countries($selected = 0, $name = 'country_code') {
1260     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1262     $string = "<select name='$name' id='$name'>";
1263     while ( $row = sqlFetchArray($r) ) {
1264         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1265         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1266     }
1268     $string .= '</select>';
1269     echo $string;
1273 // ----------------------------------------------------------------------------
1275  * DROPDOWN FOR YES/NO
1276  * 
1277  * build a dropdown with two options (yes - 1, no - 0)
1278  * 
1279  * @param int $selected - id for selected record
1280  * @param string $name - the name/id for select form
1281  * @return void - just echo the html encoded string 
1282  */
1283 function dropdown_yesno($selected = 0, $name = 'yesno') {
1284     $string = "<select name='$name' id='$name'>";
1286     $selected = (int)$selected;
1287     if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1288     else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1290     $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1291     $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1292     $string .= '</select>';
1294     echo $string;
1297 // ----------------------------------------------------------------------------
1299  * DROPDOWN FOR MALE/FEMALE options
1300  * 
1301  * build a dropdown with three options (unselected/male/female)
1302  * 
1303  * @param int $selected - id for selected record
1304  * @param string $name - the name/id for select form
1305  * @return void - just echo the html encoded string
1306  */
1307 function dropdown_sex($selected = 0, $name = 'sex') {
1308     $string = "<select name='$name' id='$name'>";
1310     if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1311     else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1312     else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1314     $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1315     $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1316     $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1317     $string .= '</select>';
1319     echo $string;
1322 // ----------------------------------------------------------------------------
1324  * DROPDOWN FOR MARITAL STATUS
1325  * 
1326  * build a dropdown with marital status
1327  * 
1328  * @param int $selected - id for selected record
1329  * @param string $name - the name/id for select form
1330  * @return void - just echo the html encoded string
1331  */
1332 function dropdown_marital($selected = 0, $name = 'status') {
1333     $string = "<select name='$name' id='$name'>";
1335     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1337     foreach ( $statii as $st ) {
1338         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1339         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1340     }
1342     $string .= '</select>';
1344     echo $string;
1347 // ----------------------------------------------------------------------------
1349  * DROPDOWN FOR PROVIDERS
1350  * 
1351  * build a dropdown with all providers
1352  * 
1353  * @param int $selected - id for selected record
1354  * @param string $name - the name/id for select form
1355  * @return void - just echo the html encoded string
1356  */
1357 function dropdown_providers($selected = 0, $name = 'status') {
1358     $provideri = getProviderInfo();
1360     $string = "<select name='$name' id='$name'>";
1361     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1362     foreach ( $provideri as $s ) {
1363         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1364         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1365     }
1367     $string .= '</select>';
1369     echo $string;
1372 // ----------------------------------------------------------------------------
1374  * DROPDOWN FOR INSURANCE COMPANIES
1375  * 
1376  * build a dropdown with all insurers
1377  * 
1378  * @param int $selected - id for selected record
1379  * @param string $name - the name/id for select form
1380  * @return void - just echo the html encoded string
1381  */
1382 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1383     $insurancei = getInsuranceProviders();
1385     $string = "<select name='$name' id='$name'>";
1386     $string .= '<option value="0">Onbekend</option>';
1387     foreach ( $insurancei as $iid => $iname ) {
1388         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1389         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1390     }
1392     $string .= '</select>';
1394     echo $string;
1398 // ----------------------------------------------------------------------------
1400  * COUNTRY CODE
1401  * 
1402  * return the name or the country code, function of arguments
1403  * 
1404  * @param int $country_code
1405  * @param string $country_name
1406  * @return string | int - name or code
1407  */
1408 function country_code($country_code = 0, $country_name = '') {
1409     $strint = '';
1410     if ( $country_code ) {
1411         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1412     } else {
1413         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1414     }
1416     $db = $GLOBALS['adodb']['db'];
1417     $result = $db->Execute($sql);
1418     if ($result && !$result->EOF) {
1419         $strint = $result->fields['res'];
1420     }
1422     return $strint;
1425 // ----------------------------------------------------------------------------
1427  * GET INSURANCE DATA
1428  * (Dutch usage)
1429  * 
1430  * return the insurer(s) and some patient
1431  * 
1432  * @param int $pid - patient id
1433  * @param int $current 1-current 0-all insurers
1434  * @return array
1435  */
1436 function get_insurers_nl($pid = 0, $current = 1) {
1437     if ( !$pid ) return FALSE;
1439     $join = 'insurance_companies ic ON ic.id = pi.pin_provider';
1440     $r = dsql_select('*', 'patient_insurers_NL pi', array('pin_pid' => $pid), 'pin_date DESC', $join);
1442     while ( $row = mysql_fetch_array($r) ) {
1443         $rez[] = $row;
1444     } // while
1446     return ( $current ? $rez[0] : $rez );
1450 // ----------------------------------------------------------------------------
1452  * SET INSURANCE DATA
1453  * (Dutch usage)
1454  * 
1455  * set the insurer for a patient
1456  * 
1457  * @param int $pid - patient id
1458  * @param int $insid - insurer id
1459  * @return void
1460  */
1461 function set_insurer_nl($pid = 0, $insid = 0, $date = '', $policy = '') {
1462     if ( !$pid || !$insid || ($date == '0000-00-00') ) return FALSE;
1464     $fields = array('pin_pid', 'pin_provider', 'pin_date', 'pin_policy');
1465     $values = array($pid, $insid, $date, $policy);
1466     dsql_insert('patient_insurers_NL', $fields, $values);
1469 // ----------------------------------------------------------------------------
1471  * FIND THE INSURERS STATUS FOR A PATIENT
1472  * (Dutch usage)
1473  * 
1474  * return the answer for the question: is this the first insurer or not?
1475  * 
1476  * @param int $pid - patient id
1477  * @return int - the number of insurer records ( 0 - no insurer; >0 some insurers)
1478  */
1479 function total_insurers($pid = 0) {
1480     if ( !$pid ) return FALSE;
1482     $r = dsql_select('COUNT(*) AS c', 'patient_insurers_NL', array('pin_pid' => $pid));
1483     $row = mysql_fetch_array($r);
1485     return $row['c'];
1488 function DBToDate ($date)
1490     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1491     return $date;
1494 function get_patient_balance($pid) {
1495   if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1496     $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1497       "pid = '$pid' AND activity = 1");
1498     $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1499       "pid = '$pid'");
1500     $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1501       "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1502       "pid = '$pid'");
1503     return sprintf('%01.2f', $brow['amount'] + $srow['amount']
1504       - $drow['payments'] - $drow['adjustments']);
1505   }
1506   else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1507     // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1508     $conn = $GLOBALS['adodb']['db'];
1509     $customer_info['id'] = 0;
1510     $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1511       "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1512       "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1513       "im.foreign_table = 'customer'";
1514     $result = $conn->Execute($sql);
1515     if($result && !$result->EOF) {
1516       $customer_info['id'] = $result->fields['foreign_id'];
1517     }
1518     $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1519     $ws = new WSWrapper($function);
1520     if(is_numeric($ws->value)) {
1521       return sprintf('%01.2f', $ws->value);
1522     }
1523   }
1524   return '';