fixed undo of checkouts
[openemr.git] / library / patient.inc
blobeff236e3db51d97c2b8d65ad0767e0dd47beb5de
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       if ($GLOBALS['restrict_user_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       else {
218         $param2 = " AND facility_id = $facility ";
219       }
220     }
221     //--------------------------------
223     $command = "=";
224     if ($providerID == "%") {
225         $command = "like";
226     }
227     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
228         "from users where username != '' and active = 1 and id $command '" .
229         mysql_real_escape_string($providerID) . "' " . $param1 . $param2;
230     // sort by last name -- JRM June 2008
231     $query .= " ORDER BY lname, fname ";
232     $rez = sqlStatement($query);
233     for($iter=0; $row=sqlFetchArray($rez); $iter++)
234         $returnval[$iter]=$row;
236     //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
237     //accessible from $resultval['key']
239     if($iter==1) {
240         $akeys = array_keys($returnval[0]);
241         foreach($akeys as $key) {
243             $returnval[0][$key] = $returnval[0][$key];
244         }
245     }
246     return $returnval;
249 //same as above but does not reduce if only 1 row returned
250 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
251     $param1 = "";
252     if ($providers_only) {
253         $param1 = "AND authorized=1";
254     }
255     $command = "=";
256     if ($providerID == "%") {
257         $command = "like";
258     }
259     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
260         "from users where active = 1 and username != '' and id $command '" .
261         mysql_real_escape_string($providerID) . "' " . $param1;
263     $rez = sqlStatement($query);
264     for($iter=0; $row=sqlFetchArray($rez); $iter++)
265         $returnval[$iter]=$row;
267     return $returnval;
270 function getProviderName($providerID) {
271     $pi = getProviderInfo($providerID);
272     if (strlen($pi[0]["lname"]) > 0) {
273         return $pi[0]['fname'] . " " . $pi[0]['lname'];
274     }
275     return "";
278 function getProviderId($providerName) {
279     $query = "select id from users where username = '". mysql_real_escape_string($providerName)."'";
280     $rez = sqlStatement($query);
281     for($iter=0; $row=sqlFetchArray($rez); $iter++)
282         $returnval[$iter]=$row;
283     return $returnval;
286 function getEthnoRacials() {
287     $returnval = array("");
288     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
289     $rez = sqlStatement($sql);
290     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
291         if (($row["ethnoracial"] != "")) {
292             array_push($returnval, $row["ethnoracial"]);
293         }
294     }
295     return $returnval;
298 function getHistoryData($pid, $given = "*")
300     $sql = "select $given from history_data where pid='$pid' order by date DESC limit 0,1";
301     return sqlQuery($sql);
304 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
305 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
307   $sql = "select $given from insurance_data as insd " .
308     "left join insurance_companies as ic on ic.id = insd.provider " .
309     "where pid = '$pid' and type = '$type' order by date DESC limit 1";
310   return sqlQuery($sql);
313 function getInsuranceDataByDate($pid, $date, $type,
314   $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
315 { // this must take the date in the following manner: YYYY-MM-DD
316   // this function recalls the insurance value that was most recently enterred from the
317   // given date. it will call up most recent records up to and on the date given,
318   // but not records enterred after the given date
319   $sql = "select $given from insurance_data as insd " .
320     "left join insurance_companies as ic on ic.id = provider " .
321     "where pid = '$pid' and date_format(date,'%Y-%m-%d') <= '$date' and " .
322     "type='$type' order by date DESC limit 1";
323   return sqlQuery($sql);
326 function getEmployerData($pid, $given = "*")
328     $sql = "select $given from employer_data where pid='$pid' order by date DESC limit 0,1";
329     return sqlQuery($sql);
332 function _set_patient_inc_count($limit, $count, $where) {
333   // When the limit is exceeded, find out what the unlimited count would be.
334   $GLOBALS['PATIENT_INC_COUNT'] = $count;
335   // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
336   if ($limit != "all") {
337     $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where");
338     $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
339   }
342 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")
344     // Allow the last name to be followed by a comma and some part of a first name.
345     // New behavior for searches:
346     // Allows comma alone followed by some part of a first name
347     // If the first letter of either name is capital, searches for name starting
348     // with given substring (the expected behavior).  If it is lower case, it
349     // it searches for the substring anywhere in the name.  This applies to either
350     // last name or first name or both.  The arbitrary limit of 100 results is set
351     // in the sql query below. --Mark Leeds
352     $lname = trim($lname);
353     $fname = '';
354      if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
355          $lname = trim($matches[1]);
356          $fname = trim($matches[2]);
357     }
358     $search_for_pieces1 = '';
359     $search_for_pieces2 = '';
360     if ($lname{0} != strtoupper($lname{0})) {$search_for_pieces1 = '%';}
361     if ($fname{0} != strtoupper($fname{0})) {$search_for_pieces2 = '%';}
363     $where = "lname LIKE '" . $search_for_pieces1 . "$lname%' " .
364         "AND fname LIKE '" . $search_for_pieces2 . "$fname%' ";
365         if (!empty($GLOBALS['pt_restrict_field'])) {
366                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
367                         $where .= "AND ( patient_data.".$GLOBALS['pt_restrict_field']." = ( SELECT facility_id FROM users WHERE username = '".$_SESSION{"authUser"}."') OR patient_data.".$GLOBALS['pt_restrict_field']." = '' ) ";
368                 }
369         }
371     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
372     if ($limit != "all") $sql .= " LIMIT $start, $limit";
374     $rez = sqlStatement($sql);
376     for($iter=0; $row=sqlFetchArray($rez); $iter++)
377         $returnval[$iter] = $row;
379     _set_patient_inc_count($limit, count($returnval), $where);
380     return $returnval;
383 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")
385     
386     $where = "pubpid LIKE '$pid%' ";
387         if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
388                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
389                         $where .= "AND ( patient_data.".$GLOBALS['pt_restrict_field']." = ( SELECT facility_id FROM users WHERE username = '".$_SESSION{"authUser"}."') OR patient_data.".$GLOBALS['pt_restrict_field']." = '' ) ";
390                 }
391         }
393     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
394     if ($limit != "all") $sql .= " limit $start, $limit";
395     $rez = sqlStatement($sql);
396     for($iter=0; $row=sqlFetchArray($rez); $iter++)
397         $returnval[$iter]=$row;
399     _set_patient_inc_count($limit, count($returnval), $where);
400     return $returnval;
403 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")
405         $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like ('%Employer%' ) AND uor !=0" );
407     $where = "";
408     for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
409         if ( $iter > 0 ) {
410            $where .= " or ";
411         }
412         $where .= " ".$row["field_id"]." like '%".$searchTerm."%' ";
413     }
415     $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
416     if ($limit != "all") $sql .= " limit $start, $limit";
417     $rez = sqlStatement($sql);
418     for($iter=0; $row=sqlFetchArray($rez); $iter++)
419         $returnval[$iter]=$row;
421     _set_patient_inc_count($limit, count($returnval), $where);
422     return $returnval;
425 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" )
427         $layoutCols = split( '~', $searchFields );
428   $where = "";
429   $i = 0;
430   foreach ($layoutCols as $val ) {
431                 if ( $i > 0 ) {
432                    $where .= " or ";
433                 }
434     if ($val == 'pid') {
435                 $where .= " $val = '$searchTerm' ";
436     }
437     else {
438                 $where .= " $val like '$searchTerm%' ";
439     }
440                 $i++;
441         }
442   $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
443   if ($limit != "all") $sql .= " limit $start, $limit";
444   $rez = sqlStatement($sql);
445   for($iter=0; $row=sqlFetchArray($rez); $iter++)
446       $returnval[$iter]=$row;
447   _set_patient_inc_count($limit, count($returnval), $where);
448   return $returnval;
451 // return a collection of Patient PIDs
452 // new arg style by JRM March 2008
453 // 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")
454 function getPatientPID($args)
456     $pid = "%";
457     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
458     $orderby = "lname ASC, fname ASC";
459     $limit="all";
460     $start="0";
462     // alter default values if defined in the passed in args
463     if (isset($args['pid'])) { $pid = $args['pid']; }
464     if (isset($args['given'])) { $given = $args['given']; }
465     if (isset($args['orderby'])) { $orderby = $args['orderby']; }
466     if (isset($args['limit'])) { $limit = $args['limit']; }
467     if (isset($args['start'])) { $start = $args['start']; }
469     $command = "=";
470     if ($pid == -1) $pid = "%";
471     elseif (empty($pid)) $pid = "NULL";
473     if (strstr($pid,"%")) $command = "like";
475     $sql="select $given from patient_data where pid $command '$pid' 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     return $returnval;
485 /* return a patient's name in the format LAST, FIRST */
486 function getPatientName($pid) {
487     if (empty($pid)) return "";
488     $patientData = getPatientPID(array("pid"=>$pid));
489     if (empty($patientData[0]['lname'])) return "";
490     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
491     return $patientName;
494 /* find patient data by DOB */
495 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
497     $DOB = fixDate($DOB, $DOB);
498     $where = "DOB like '$DOB%' ";
499         if (!empty($GLOBALS['pt_restrict_field'])) {
500                 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
501                         $where .= "AND ( patient_data.".$GLOBALS['pt_restrict_field']." = ( SELECT facility_id FROM users WHERE username = '".$_SESSION{"authUser"}."') OR patient_data.".$GLOBALS['pt_restrict_field']." = '' ) ";
502                 }
503         }
505     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
507     if ($limit != "all") $sql .= " LIMIT $start, $limit";
509     $rez = sqlStatement($sql);
510     for($iter=0; $row=sqlFetchArray($rez); $iter++)
511         $returnval[$iter]=$row;
513     _set_patient_inc_count($limit, count($returnval), $where);
514     return $returnval;
517 /* find patient data by SSN */
518 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
520     $where = "ss LIKE '$ss%'";
521     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
522     if ($limit != "all") $sql .= " LIMIT $start, $limit";
524     $rez = sqlStatement($sql);
525     for($iter=0; $row=sqlFetchArray($rez); $iter++)
526         $returnval[$iter]=$row;
528     _set_patient_inc_count($limit, count($returnval), $where);
529     return $returnval;
532 //(CHEMED) Search by phone number
533 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
535     $phone = ereg_replace( "[[:punct:]]","", $phone );
536     $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP '$phone'";
537     $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
538     if ($limit != "all") $sql .= " LIMIT $start, $limit";
540     $rez = sqlStatement($sql);
541     for($iter=0; $row=sqlFetchArray($rez); $iter++)
542         $returnval[$iter]=$row;
544     _set_patient_inc_count($limit, count($returnval), $where);
545     return $returnval;
548 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
550     $sql="select $given from patient_data order by $orderby";
552     if ($limit != "all")
553         $sql .= " limit $start, $limit";
555     $rez = sqlStatement($sql);
556     for($iter=0; $row=sqlFetchArray($rez); $iter++)
557         $returnval[$iter]=$row;
559     return $returnval;
562 //----------------------input functions
563 function newPatientData(    $db_id="",
564                 $title = "",
565                 $fname = "",
566                 $lname = "",
567                 $mname = "",
568                 $sex = "",
569                 $DOB = "",
570                 $street = "",
571                 // DBC dutch use
572                 $nstreet = "",
573                 $nnr = "",
574                 $nadd = "",
575                 // EOS DBC
576                 $postal_code = "",
577                 $city = "",
578                 $state = "",
579                 $country_code = "",
580                 $ss = "",
581                 $occupation = "",
582                 $phone_home = "",
583                 $phone_biz = "",
584                 $phone_contact = "",
585                 $status = "",
586                 $contact_relationship = "",
587                 $referrer = "",
588                 $referrerID = "",
589                 $email = "",
590                 $language = "",
591                 $ethnoracial = "",
592                 $interpretter = "",
593                 $migrantseasonal = "",
594                 $family_size = "",
595                 $monthly_income = "",
596                 $homeless = "",
597                 $financial_review = "",
598                 $pubpid = "",
599                 $pid = "MAX(pid)+1",
600                 $providerID = "",
601                 $genericname1 = "",
602                 $genericval1 = "",
603                 $genericname2 = "",
604                 $genericval2 = "",
605                 $phone_cell = "",
606                 $hipaa_mail = "",
607                 $hipaa_voice = "",
608                 $squad = 0,
609                 $pharmacy_id = 0,
610                 $drivers_license = "",
611                 $hipaa_notice = "",
612                 $hipaa_message = "",
613                 $regdate = "",
614                 // dutch specific
615                 $prefixlast = "",
616                 $prefixlastpartner = "",
617                 $lastpartner = "",
618                 $initials = "",
619                 $provider_data = array(),
620                 $referer_data = array()
621                 // DBC Dutch System
623             )
625     $DOB = fixDate($DOB);
626     $regdate = fixDate($regdate);
628     $fitness = 0;
629     $referral_source = '';
630     if ($pid) {
631         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
632         // Check for brain damage:
633         if ($db_id != $rez['id']) {
634             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
635               $rez['id'] . "' to '$db_id' for pid '$pid'";
636             die($errmsg);
637         }
638         $fitness = $rez['fitness'];
639         $referral_source = $rez['referral_source'];
640     }
642     // Get the default price level.
643     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
644       "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
645     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
647     $query = ("replace into patient_data set
648         id='$db_id',
649         title='$title',
650         fname='$fname',
651         lname='$lname',
652         mname='$mname',
653         sex='$sex',
654         DOB='$DOB',
655         street='$street',
656         postal_code='$postal_code',
657         city='$city',
658         state='$state',
659         country_code='$country_code',
660         drivers_license='$drivers_license',
661         ss='$ss',
662         occupation='$occupation',
663         phone_home='$phone_home',
664         phone_biz='$phone_biz',
665         phone_contact='$phone_contact',
666         status='$status',
667         contact_relationship='$contact_relationship',
668         referrer='$referrer',
669         referrerID='$referrerID',
670         email='$email',
671         language='$language',
672         ethnoracial='$ethnoracial',
673         interpretter='$interpretter',
674         migrantseasonal='$migrantseasonal',
675         family_size='$family_size',
676         monthly_income='$monthly_income',
677         homeless='$homeless',
678         financial_review='$financial_review',
679         pubpid='$pubpid',
680         pid = $pid,
681         providerID = '$providerID',
682         genericname1 = '$genericname1',
683         genericval1 = '$genericval1',
684         genericname2 = '$genericname2',
685         genericval2 = '$genericval2',
686         phone_cell = '$phone_cell',
687         pharmacy_id = '$pharmacy_id',
688         hipaa_mail = '$hipaa_mail',
689         hipaa_voice = '$hipaa_voice',
690         hipaa_notice = '$hipaa_notice',
691         hipaa_message = '$hipaa_message',
692         squad = '$squad',
693         fitness='$fitness',
694         referral_source='$referral_source',
695         regdate='$regdate',
696         pricelevel='$pricelevel',
697         date=NOW()");
699     $id = sqlInsert($query);
701     // DBC 
702     if ( !$db_id ) {
703       // find the last inserted id for new patient case
704       $db_id = empty($GLOBALS['dutchpc']) ? mysql_insert_id() : dsql_lastid();
705     }
706     // EOS DBC
708     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
710          // dutch use
711         if ( $GLOBALS['dutchpc'] ) {
712                 $init = strtoupper(preg_replace('/[\s\.\-_0-9]/','',$initials));
713                 
714             $querynl = ("REPLACE INTO patient_data_NL SET
715                     pdn_id = '$db_id',
716                     pdn_pxlast = '$prefixlast',
717                     pdn_pxlastpar = '$prefixlastpartner',
718                     pdn_lastpar = '$lastpartner',
719                     pdn_street = '$nstreet',
720                     pdn_number = '$nnr',
721                     pdn_addition = '$nadd',
722                     pdn_initials = '$init'
723             ");
725             if ( $db_id ) $idnl = sqlInsert($querynl); // only if exists
726         }
727         // EOS dutch use
730        // DBC Dutch System
731         // provider first
732         if ( $GLOBALS['dutchpc'] && $db_id && $provider_data && $referer_data) {
733            $querypr = ("INSERT INTO cl_providers(pro_pid, pro_company, pro_initials, pro_prefix, pro_lname,
734                    pro_street, pro_number, pro_addition, pro_city, pro_zipcode,  pro_phone, pro_fax, pro_email, pro_referer ) 
735                    VALUES ($db_id, '{$provider_data['pro_company']}', '{$provider_data['pro_initials']}',
736                   '{$provider_data['pro_prefix']}', '{$provider_data['pro_lname']}',  
737                   '{$provider_data['pro_street']}', '{$provider_data['pro_number']}', '{$provider_data['pro_addition']}', 
738                   '{$provider_data['pro_city']}',  '{$provider_data['pro_zipcode']}',
739                   '{$provider_data['pro_phone']}', '{$provider_data['pro_fax']}',  '{$provider_data['pro_email']}', 
740                   '{$provider_data['pro_referer']}') 
741                   ON DUPLICATE KEY UPDATE  pro_referer = '{$provider_data['pro_referer']}',
742                   pro_company = '{$provider_data['pro_company']}', pro_initials = '{$provider_data['pro_initials']}',
743                   pro_prefix = '{$provider_data['pro_prefix']}',
744                   pro_lname = '{$provider_data['pro_lname']}', pro_street = '{$provider_data['pro_street']}',
745                   pro_number = '{$provider_data['pro_number']}', pro_addition = '{$provider_data['pro_addition']}',
746                   pro_city = '{$provider_data['pro_city']}', pro_zipcode = '{$provider_data['pro_zipcode']}',
747                   pro_phone = '{$provider_data['pro_phone']}', pro_fax = '{$provider_data['pro_fax']}',
748                   pro_email = '{$provider_data['pro_email']}'
749             ");
750            $idpr = sqlInsert($querypr);
752         // referer if it's the case
753         if ( $referer_data['ref_code'] ) {
754            $queryre = ("INSERT INTO cl_referers(ref_pid, ref_code, ref_company, ref_initials, ref_prefix,
755                    ref_lname, ref_street, ref_number, ref_addition, ref_city, ref_zipcode,  ref_phone, ref_fax,
756                    ref_email) 
757                    VALUES ($db_id, {$referer_data['ref_code']}, '{$referer_data['ref_company']}', 
758                    '{$referer_data['ref_initials']}', '{$referer_data['ref_prefix']}',
759                    '{$referer_data['ref_lname']}', '{$referer_data['ref_street']}', '{$referer_data['ref_number']}', 
760                    '{$referer_data['ref_addition']}', '{$referer_data['ref_city']}', '{$referer_data['ref_zipcode']}',
761                   '{$referer_data['ref_phone']}', '{$referer_data['ref_fax']}',  '{$referer_data['ref_email']}')
762                   ON DUPLICATE KEY UPDATE ref_code = {$referer_data['ref_code']},
763                   ref_company = '{$referer_data['ref_company']}', ref_initials = '{$referer_data['ref_initials']}',
764                   ref_prefix = '{$referer_data['ref_prefix']}',
765                   ref_lname = '{$referer_data['ref_lname']}', ref_street = '{$referer_data['ref_street']}',
766                   ref_number = '{$referer_data['ref_number']}', ref_addition = '{$referer_data['ref_addition']}',
767                   ref_city = '{$referer_data['ref_city']}', ref_zipcode = '{$referer_data['ref_zipcode']}',
768                   ref_phone = '{$referer_data['ref_phone']}', ref_fax = '{$referer_data['ref_fax']}',
769                   ref_email = '{$referer_data['ref_email']}'
770             ");
771            $idre = sqlInsert($queryre);
772         } 
773         } // if globals
774         // EOS DBC
776     sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
777                 $phone_biz,$phone_cell,$email,$pid);
779     return $foo['pid'];
782 // Supported input date formats are:
783 //   mm/dd/yyyy
784 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
785 //   yyyy/mm/dd
786 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
788 function fixDate($date, $default="0000-00-00") {
789     $fixed_date = $default;
790     $date = trim($date);
791     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
792         $dmy = preg_split("'[/.-]'", $date);
793         if ($dmy[0] > 99) {
794             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
795         } else {
796             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
797               if ($dmy[2] < 1000) $dmy[2] += 1900;
798               if ($dmy[2] < 1910) $dmy[2] += 100;
799             }
800             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
801         }
802     }
804     return $fixed_date;
807 // Create or update patient data from an array.
809 function updatePatientData($pid, $new, $create=false)
811   /*******************************************************************
812     $real = getPatientData($pid);
813     $new['DOB'] = fixDate($new['DOB']);
814     while(list($key, $value) = each ($new))
815         $real[$key] = $value;
816     $real['date'] = "'+NOW()+'";
817     $real['id'] = "";
818     $sql = "insert into patient_data set ";
819     while(list($key, $value) = each($real))
820         $sql .= $key." = '$value', ";
821     $sql = substr($sql, 0, -2);
822     return sqlInsert($sql);
823   *******************************************************************/
825   // The above was broken, though seems intent to insert a new patient_data
826   // row for each update.  A good idea, but nothing is doing that yet so
827   // the code below does not yet attempt it.
829   $new['DOB'] = fixDate($new['DOB']);
831   if ($create) {
832     $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
833     foreach ($new as $key => $value) {
834       if ($key == 'id') continue;
835       $sql .= ", $key = '$value'";
836     }
837     $db_id = sqlInsert($sql);
838   }
839   else {
840     $db_id = $new['id'];
841     $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
842     // Check for brain damage:
843     if ($pid != $rez['pid']) {
844       $errmsg = "Internal error: Attempt to change patient data with pid = '" .
845         $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
846       die($errmsg);
847     }
848     $sql = "UPDATE patient_data SET date = NOW()";
849     foreach ($new as $key => $value) {
850       $sql .= ", $key = '$value'";
851     }
852     $sql .= " WHERE id = '$db_id'";
853     sqlStatement($sql);
854   }
856   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
857   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
858     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
859     $rez['phone_cell'],$rez['email'],$rez['pid']);
861   return $db_id;
864 function newEmployerData(    $pid,
865                 $name = "",
866                 $street = "",
867                 $postal_code = "",
868                 $city = "",
869                 $state = "",
870                 $country = ""
871             )
873     return sqlInsert("insert into employer_data set
874         name='$name',
875         street='$street',
876         postal_code='$postal_code',
877         city='$city',
878         state='$state',
879         country='$country',
880         pid='$pid',
881         date=NOW()
882         ");
885 // Create or update employer data from an array.
887 function updateEmployerData($pid, $new, $create=false)
889   $colnames = array('name','street','city','state','postal_code','country');
891   if ($create) {
892     $set .= "pid = '$pid', date = NOW()";
893     foreach ($colnames as $key) {
894       $value = isset($new[$key]) ? $new[$key] : '';
895       $set .= ", $key = '$value'";
896     }
897     return sqlInsert("INSERT INTO employer_data SET $set");
898   }
899   else {
900     $set = '';
901     $old = getEmployerData($pid);
902     $modified = false;
903     foreach ($colnames as $key) {
904       $value = empty($old[$key]) ? '' : addslashes($old[$key]);
905       if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
906         $value = $new[$key];
907         $modified = true;
908       }
909       $set .= "$key = '$value', ";
910     }
911     if ($modified) {
912       $set .= "pid = '$pid', date = NOW()";
913       return sqlInsert("INSERT INTO employer_data SET $set");
914     }
915     return $old['id'];
916   }
919 // This updates or adds the given insurance data info, while retaining any
920 // previously added insurance_data rows that should be preserved.
921 // This does not directly support the maintenance of non-current insurance.
923 function newInsuranceData(
924   $pid,
925   $type = "",
926   $provider = "",
927   $policy_number = "",
928   $group_number = "",
929   $plan_name = "",
930   $subscriber_lname = "",
931   $subscriber_mname = "",
932   $subscriber_fname = "",
933   $subscriber_relationship = "",
934   $subscriber_ss = "",
935   $subscriber_DOB = "",
936   $subscriber_street = "",
937   $subscriber_postal_code = "",
938   $subscriber_city = "",
939   $subscriber_state = "",
940   $subscriber_country = "",
941   $subscriber_phone = "",
942   $subscriber_employer = "",
943   $subscriber_employer_street = "",
944   $subscriber_employer_city = "",
945   $subscriber_employer_postal_code = "",
946   $subscriber_employer_state = "",
947   $subscriber_employer_country = "",
948   $copay = "",
949   $subscriber_sex = "",
950   $effective_date = "0000-00-00",
951   $accept_assignment = "TRUE")
953   if (strlen($type) <= 0) return FALSE;
955   // If a bad date was passed, err on the side of caution.
956   $effective_date = fixDate($effective_date, date('Y-m-d'));
958   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
959     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
960   $idrow = sqlFetchArray($idres);
962   // Replace the most recent entry in any of the following cases:
963   // * Its effective date is >= this effective date.
964   // * It is the first entry and it has no (insurance) provider.
965   // * There is no encounter that is earlier than the new effective date but
966   //   on or after the old effective date.
967   // Otherwise insert a new entry.
969   $replace = false;
970   if ($idrow) {
971     if (strcmp($idrow['date'], $effective_date) > 0) {
972       $replace = true;
973     }
974     else {
975       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
976         $replace = true;
977       }
978       else {
979         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
980           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
981           "date >= '" . $idrow['date'] . " 00:00:00'");
982         if ($ferow['count'] == 0) $replace = true;
983       }
984     }
985   }
987   if ($replace) {
989     // TBD: This is a bit dangerous in that a typo in entering the effective
990     // date can wipe out previous insurance history.  So we want some data
991     // entry validation somewhere.
992     sqlStatement("DELETE FROM insurance_data WHERE " .
993       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
994       "id != " . $idrow['id']);
996     $data = array();
997     $data['type'] = $type;
998     $data['provider'] = $provider;
999     $data['policy_number'] = $policy_number;
1000     $data['group_number'] = $group_number;
1001     $data['plan_name'] = $plan_name;
1002     $data['subscriber_lname'] = $subscriber_lname;
1003     $data['subscriber_mname'] = $subscriber_mname;
1004     $data['subscriber_fname'] = $subscriber_fname;
1005     $data['subscriber_relationship'] = $subscriber_relationship;
1006     $data['subscriber_ss'] = $subscriber_ss;
1007     $data['subscriber_DOB'] = $subscriber_DOB;
1008     $data['subscriber_street'] = $subscriber_street;
1009     $data['subscriber_postal_code'] = $subscriber_postal_code;
1010     $data['subscriber_city'] = $subscriber_city;
1011     $data['subscriber_state'] = $subscriber_state;
1012     $data['subscriber_country'] = $subscriber_country;
1013     $data['subscriber_phone'] = $subscriber_phone;
1014     $data['subscriber_employer'] = $subscriber_employer;
1015     $data['subscriber_employer_city'] = $subscriber_employer_city;
1016     $data['subscriber_employer_street'] = $subscriber_employer_street;
1017     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1018     $data['subscriber_employer_state'] = $subscriber_employer_state;
1019     $data['subscriber_employer_country'] = $subscriber_employer_country;
1020     $data['copay'] = $copay;
1021     $data['subscriber_sex'] = $subscriber_sex;
1022     $data['pid'] = $pid;
1023     $data['date'] = $effective_date;
1024     $data['accept_assignment'] = $accept_assignment;
1025     updateInsuranceData($idrow['id'], $data);
1026     return $idrow['id'];
1027   }
1028   else {
1029     return sqlInsert("INSERT INTO insurance_data SET
1030       type = '$type',
1031       provider = '$provider',
1032       policy_number = '$policy_number',
1033       group_number = '$group_number',
1034       plan_name = '$plan_name',
1035       subscriber_lname = '$subscriber_lname',
1036       subscriber_mname = '$subscriber_mname',
1037       subscriber_fname = '$subscriber_fname',
1038       subscriber_relationship = '$subscriber_relationship',
1039       subscriber_ss = '$subscriber_ss',
1040       subscriber_DOB = '$subscriber_DOB',
1041       subscriber_street = '$subscriber_street',
1042       subscriber_postal_code = '$subscriber_postal_code',
1043       subscriber_city = '$subscriber_city',
1044       subscriber_state = '$subscriber_state',
1045       subscriber_country = '$subscriber_country',
1046       subscriber_phone = '$subscriber_phone',
1047       subscriber_employer = '$subscriber_employer',
1048       subscriber_employer_city = '$subscriber_employer_city',
1049       subscriber_employer_street = '$subscriber_employer_street',
1050       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1051       subscriber_employer_state = '$subscriber_employer_state',
1052       subscriber_employer_country = '$subscriber_employer_country',
1053       copay = '$copay',
1054       subscriber_sex = '$subscriber_sex',
1055       pid = '$pid',
1056       date = '$effective_date',
1057       accept_assignment = '$accept_assignment'
1058     ");
1059   }
1062 // This is used internally only.
1063 function updateInsuranceData($id, $new)
1065   $fields = sqlListFields("insurance_data");
1066   $use = array();
1068   while(list($key, $value) = each ($new)) {
1069     if (in_array($key, $fields)) {
1070       $use[$key] = $value;
1071     }
1072   }
1074   $sql = "UPDATE insurance_data SET ";
1075   while(list($key, $value) = each($use))
1076     $sql .= $key . " = '$value', ";
1077   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1079   sqlStatement($sql);
1082 function newHistoryData($pid, $new=false) {
1083   $sql = "insert into history_data set pid = '$pid', date = NOW()";
1084   if ($new) {
1085     while(list($key, $value) = each($new)) {
1086       if (!get_magic_quotes_gpc()) $value = addslashes($value);
1087       $sql .= ", $key = '$value'";
1088     }
1089   }
1090   return sqlInsert($sql);
1093 function updateHistoryData($pid,$new)
1095         $real = getHistoryData($pid);
1096         while(list($key, $value) = each ($new))
1097                 $real[$key] = $value;
1098         $real['date'] = "'+NOW()+'";
1099         $real['id'] = "";
1101         $sql = "insert into history_data set ";
1102         while(list($key, $value) = each($real))
1103                 $sql .= $key." = '$value', ";
1104         $sql = substr($sql, 0, -2);
1107         return sqlInsert($sql);
1110 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1111                 $phone_biz,$phone_cell,$email,$pid="")
1113     if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1114     if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1116     $db = $GLOBALS['adodb']['db'];
1117     $customer_info = array();
1119     $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1120     $result = $db->Execute($sql);
1121     if ($result && !$result->EOF) {
1122         $customer_info['foreign_update'] = true;
1123         $customer_info['foreign_id'] = $result->fields['foreign_id'];
1124         $customer_info['foreign_table'] = $result->fields['foreign_table'];
1125     }
1127     ///xml rpc code to connect to accounting package and add user to it
1128     $customer_info['firstname'] = $fname;
1129     $customer_info['lastname'] = $lname;
1130     $customer_info['address'] = $street;
1131     $customer_info['suburb'] = $city;
1132     $customer_info['state'] = $state;
1133     $customer_info['postcode'] = $postal_code;
1135     //ezybiz wants state as a code rather than abbreviation
1136     $customer_info['geo_zone_id'] = "";
1137     $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1138     $db = $GLOBALS['adodb']['db'];
1139     $result = $db->Execute($sql);
1140     if ($result && !$result->EOF) {
1141         $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1142     }
1144     //ezybiz wants country as a code rather than abbreviation
1145     $customer_info['geo_country_id'] = "";
1146     $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1147     $db = $GLOBALS['adodb']['db'];
1148     $result = $db->Execute($sql);
1149     if ($result && !$result->EOF) {
1150         $customer_info['geo_country_id'] = $result->fields['countries_id'];
1151     }
1153     $customer_info['phone1'] = $phone_home;
1154     $customer_info['phone1comment'] = "Home Phone";
1155     $customer_info['phone2'] = $phone_biz;
1156     $customer_info['phone2comment'] = "Business Phone";
1157     $customer_info['phone3'] = $phone_cell;
1158     $customer_info['phone3comment'] = "Cell Phone";
1159     $customer_info['email'] = $email;
1160     $customer_info['customernumber'] = $pid;
1162     $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1163     $ws = new WSWrapper($function);
1165     // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1166     if (is_numeric($ws->value)) {
1167         $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1168         $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1169     }
1172 // Returns Age 
1173 //   in months if < 2 years old
1174 //   in years  if > 2 years old
1175 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1176 // (optional) nowYMD is a date in YYYYMMDD format
1177 function getPatientAge($dobYMD, $nowYMD=null)
1179     // strip any dashes from the DOB
1180     $dobYMD = preg_replace("/-/", "", $dobYMD);
1181     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1182     
1183     // set the 'now' date values
1184     if ($nowYMD == null) {
1185         $nowDay = date("d");
1186         $nowMonth = date("m");
1187         $nowYear = date("Y");
1188     }
1189     else {
1190         $nowDay = substr($nowYMD,6,2);
1191         $nowMonth = substr($nowYMD,4,2);
1192         $nowYear = substr($nowYMD,0,4);
1193     }
1195     $dayDiff = $nowDay - $dobDay;
1196     $monthDiff = $nowMonth - $dobMonth;
1197     $yearDiff = $nowYear - $dobYear;
1199     $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1201     if ( $ageInMonths > 24 ) {
1202         $age = $yearDiff;
1203         if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1204         else if ($monthDiff < 0) { $age -= 1; }
1205     }
1206     else  {
1207         $age = "$ageInMonths month"; 
1208     }
1210     return $age;
1214 // Returns Age in days
1215 //   in months if < 2 years old
1216 //   in years  if > 2 years old
1217 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1218 // (optional) nowYMD is a date in YYYYMMDD format
1219 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1220     $age = -1;
1222     // strip any dashes from the DOB
1223     $dobYMD = preg_replace("/-/", "", $dobYMD);
1224     $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1225     
1226     // set the 'now' date values
1227     if ($nowYMD == null) {
1228         $nowDay = date("d");
1229         $nowMonth = date("m");
1230         $nowYear = date("Y");
1231     }
1232     else {
1233         $nowDay = substr($nowYMD,6,2);
1234         $nowMonth = substr($nowYMD,4,2);
1235         $nowYear = substr($nowYMD,0,4);
1236     }
1238     // do the date math
1239     $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1240     $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1241     $timediff = $nowtime - $dobtime;
1242     $age = $timediff / 86400;
1244     return $age;
1247 function dateToDB ($date)
1249     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1250     return $date;
1254 // ----------------------------------------------------------------------------
1256  * DROPDOWN FOR COUNTRIES
1257  * 
1258  * build a dropdown with all countries from geo_country_reference
1259  * 
1260  * @param int $selected - id for selected record
1261  * @param string $name - the name/id for select form
1262  * @return void - just echo the html encoded string
1263  */
1264 function dropdown_countries($selected = 0, $name = 'country_code') {
1265     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1267     $string = "<select name='$name' id='$name'>";
1268     while ( $row = sqlFetchArray($r) ) {
1269         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1270         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1271     }
1273     $string .= '</select>';
1274     echo $string;
1278 // ----------------------------------------------------------------------------
1280  * DROPDOWN FOR YES/NO
1281  * 
1282  * build a dropdown with two options (yes - 1, no - 0)
1283  * 
1284  * @param int $selected - id for selected record
1285  * @param string $name - the name/id for select form
1286  * @return void - just echo the html encoded string 
1287  */
1288 function dropdown_yesno($selected = 0, $name = 'yesno') {
1289     $string = "<select name='$name' id='$name'>";
1291     $selected = (int)$selected;
1292     if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1293     else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1295     $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1296     $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1297     $string .= '</select>';
1299     echo $string;
1302 // ----------------------------------------------------------------------------
1304  * DROPDOWN FOR MALE/FEMALE options
1305  * 
1306  * build a dropdown with three options (unselected/male/female)
1307  * 
1308  * @param int $selected - id for selected record
1309  * @param string $name - the name/id for select form
1310  * @return void - just echo the html encoded string
1311  */
1312 function dropdown_sex($selected = 0, $name = 'sex') {
1313     $string = "<select name='$name' id='$name'>";
1315     if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1316     else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1317     else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1319     $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1320     $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1321     $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1322     $string .= '</select>';
1324     echo $string;
1327 // ----------------------------------------------------------------------------
1329  * DROPDOWN FOR MARITAL STATUS
1330  * 
1331  * build a dropdown with marital status
1332  * 
1333  * @param int $selected - id for selected record
1334  * @param string $name - the name/id for select form
1335  * @return void - just echo the html encoded string
1336  */
1337 function dropdown_marital($selected = 0, $name = 'status') {
1338     $string = "<select name='$name' id='$name'>";
1340     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1342     foreach ( $statii as $st ) {
1343         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1344         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1345     }
1347     $string .= '</select>';
1349     echo $string;
1352 // ----------------------------------------------------------------------------
1354  * DROPDOWN FOR PROVIDERS
1355  * 
1356  * build a dropdown with all providers
1357  * 
1358  * @param int $selected - id for selected record
1359  * @param string $name - the name/id for select form
1360  * @return void - just echo the html encoded string
1361  */
1362 function dropdown_providers($selected = 0, $name = 'status') {
1363     $provideri = getProviderInfo();
1365     $string = "<select name='$name' id='$name'>";
1366     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1367     foreach ( $provideri as $s ) {
1368         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1369         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1370     }
1372     $string .= '</select>';
1374     echo $string;
1377 // ----------------------------------------------------------------------------
1379  * DROPDOWN FOR INSURANCE COMPANIES
1380  * 
1381  * build a dropdown with all insurers
1382  * 
1383  * @param int $selected - id for selected record
1384  * @param string $name - the name/id for select form
1385  * @return void - just echo the html encoded string
1386  */
1387 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1388     $insurancei = getInsuranceProviders();
1390     $string = "<select name='$name' id='$name'>";
1391     $string .= '<option value="0">Onbekend</option>';
1392     foreach ( $insurancei as $iid => $iname ) {
1393         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1394         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1395     }
1397     $string .= '</select>';
1399     echo $string;
1403 // ----------------------------------------------------------------------------
1405  * COUNTRY CODE
1406  * 
1407  * return the name or the country code, function of arguments
1408  * 
1409  * @param int $country_code
1410  * @param string $country_name
1411  * @return string | int - name or code
1412  */
1413 function country_code($country_code = 0, $country_name = '') {
1414     $strint = '';
1415     if ( $country_code ) {
1416         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1417     } else {
1418         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1419     }
1421     $db = $GLOBALS['adodb']['db'];
1422     $result = $db->Execute($sql);
1423     if ($result && !$result->EOF) {
1424         $strint = $result->fields['res'];
1425     }
1427     return $strint;
1430 // ----------------------------------------------------------------------------
1432  * GET INSURANCE DATA
1433  * (Dutch usage)
1434  * 
1435  * return the insurer(s) and some patient
1436  * 
1437  * @param int $pid - patient id
1438  * @param int $current 1-current 0-all insurers
1439  * @return array
1440  */
1441 function get_insurers_nl($pid = 0, $current = 1) {
1442     if ( !$pid ) return FALSE;
1444     $join = 'insurance_companies ic ON ic.id = pi.pin_provider';
1445     $r = dsql_select('*', 'patient_insurers_NL pi', array('pin_pid' => $pid), 'pin_date DESC', $join);
1447     while ( $row = mysql_fetch_array($r) ) {
1448         $rez[] = $row;
1449     } // while
1451     return ( $current ? $rez[0] : $rez );
1455 // ----------------------------------------------------------------------------
1457  * SET INSURANCE DATA
1458  * (Dutch usage)
1459  * 
1460  * set the insurer for a patient
1461  * 
1462  * @param int $pid - patient id
1463  * @param int $insid - insurer id
1464  * @return void
1465  */
1466 function set_insurer_nl($pid = 0, $insid = 0, $date = '', $policy = '') {
1467     if ( !$pid || !$insid || ($date == '0000-00-00') ) return FALSE;
1469     $fields = array('pin_pid', 'pin_provider', 'pin_date', 'pin_policy');
1470     $values = array($pid, $insid, $date, $policy);
1471     dsql_insert('patient_insurers_NL', $fields, $values);
1474 // ----------------------------------------------------------------------------
1476  * FIND THE INSURERS STATUS FOR A PATIENT
1477  * (Dutch usage)
1478  * 
1479  * return the answer for the question: is this the first insurer or not?
1480  * 
1481  * @param int $pid - patient id
1482  * @return int - the number of insurer records ( 0 - no insurer; >0 some insurers)
1483  */
1484 function total_insurers($pid = 0) {
1485     if ( !$pid ) return FALSE;
1487     $r = dsql_select('COUNT(*) AS c', 'patient_insurers_NL', array('pin_pid' => $pid));
1488     $row = mysql_fetch_array($r);
1490     return $row['c'];
1493 function DBToDate ($date)
1495     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1496     return $date;
1499 function get_patient_balance($pid) {
1500   if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1501     $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1502       "pid = '$pid' AND activity = 1");
1503     $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1504       "pid = '$pid'");
1505     $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1506       "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1507       "pid = '$pid'");
1508     return sprintf('%01.2f', $brow['amount'] + $srow['amount']
1509       - $drow['payments'] - $drow['adjustments']);
1510   }
1511   else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1512     // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1513     $conn = $GLOBALS['adodb']['db'];
1514     $customer_info['id'] = 0;
1515     $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1516       "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1517       "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1518       "im.foreign_table = 'customer'";
1519     $result = $conn->Execute($sql);
1520     if($result && !$result->EOF) {
1521       $customer_info['id'] = $result->fields['foreign_id'];
1522     }
1523     $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1524     $ws = new WSWrapper($function);
1525     if(is_numeric($ws->value)) {
1526       return sprintf('%01.2f', $ws->value);
1527     }
1528   }
1529   return '';