fix for the BACK link so it goes to the main notes screen, not the calendar
[openemr.git] / library / patient.inc
blob4730ea24c6639ad325c74095d510d454c6a5af7a
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 GET FACILITIES
84 returns all facilities or just the id for the first one
85 (FACILITY FILTERING (lemonsoftware))
87 @param string - if 'first' return first facility ordered by id
88 @return array | int for 'first' case
90 function getFacilities($first = '') {
91     $r = sqlStatement("SELECT * FROM facility ORDER BY id");
92     $ret = array();
93     while ( $row = sqlFetchArray($r) ) {
94        $ret[] = $row;
97         if ( $first == 'first') {
98             return $ret[0]['id'];
99         } else {
100             return $ret;
101         }
105 GET SERVICE FACILITIES
107 returns all service_location facilities or just the id for the first one
108 (FACILITY FILTERING (CHEMED))
110 @param string - if 'first' return first facility ordered by id
111 @return array | int for 'first' case
113 function getServiceFacilities($first = '') {
114     $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
115     $ret = array();
116     while ( $row = sqlFetchArray($r) ) {
117        $ret[] = $row;
120         if ( $first == 'first') {
121             return $ret[0]['id'];
122         } else {
123             return $ret;
124         }
127 //(CHEMED) facility filter
128 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
129     $param1 = "";
130     if ($providers_only) {
131         $param1 = " AND authorized=1 ";
132     }
134     //--------------------------------
135     //(CHEMED) facility filter
136     $param2 = "";
137     if ($facility) {
138         $param2 = " AND facility_id = $facility ";
139     }
140     //--------------------------------
142     $command = "=";
143     if ($providerID == "%") {
144         $command = "like";
145     }
146     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
147         "from users where username != '' and active = 1 and id $command '" .
148         mysql_real_escape_string($providerID) . "' " . $param1 . $param2;
149     $rez = sqlStatement($query);
150     for($iter=0; $row=sqlFetchArray($rez); $iter++)
151         $returnval[$iter]=$row;
153     //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
154     //accessible from $resultval['key']
156     if($iter==1) {
157         $akeys = array_keys($returnval[0]);
158         foreach($akeys as $key) {
160             $returnval[0][$key] = $returnval[0][$key];
161         }
162     }
163     return $returnval;
166 //same as above but does not reduce if only 1 row returned
167 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
168     $param1 = "";
169     if ($providers_only) {
170         $param1 = "AND authorized=1";
171     }
172     $command = "=";
173     if ($providerID == "%") {
174         $command = "like";
175     }
176     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
177         "from users where active = 1 and username != '' and id $command '" .
178         mysql_real_escape_string($providerID) . "' " . $param1;
180     $rez = sqlStatement($query);
181     for($iter=0; $row=sqlFetchArray($rez); $iter++)
182         $returnval[$iter]=$row;
184     return $returnval;
187 function getProviderName($providerID) {
188     $pi = getProviderInfo($providerID);
189     if (strlen($pi[0]["lname"]) > 0) {
190         return $pi[0]['fname'] . " " . $pi[0]['lname'];
191     }
192     return "";
195 function getProviderId($providerName) {
196     $query = "select id from users where username = '". mysql_real_escape_string($providerName)."'";
197     $rez = sqlStatement($query);
198     for($iter=0; $row=sqlFetchArray($rez); $iter++)
199         $returnval[$iter]=$row;
200     return $returnval;
203 function getEthnoRacials() {
204     $returnval = array("");
205     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
206     $rez = sqlStatement($sql);
207     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
208         if (($row["ethnoracial"] != "")) {
209             array_push($returnval, $row["ethnoracial"]);
210         }
211     }
212     return $returnval;
215 function getHistoryData($pid, $given = "*")
217     $sql = "select $given from history_data where pid='$pid' order by date DESC limit 0,1";
218     return sqlQuery($sql);
221 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
222 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
224   $sql = "select $given from insurance_data as insd " .
225     "left join insurance_companies as ic on ic.id = insd.provider " .
226     "where pid = '$pid' and type = '$type' order by date DESC limit 1";
227   return sqlQuery($sql);
230 function getInsuranceDataByDate($pid, $date, $type,
231   $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
232 { // this must take the date in the following manner: YYYY-MM-DD
233   // this function recalls the insurance value that was most recently enterred from the
234   // given date. it will call up most recent records up to and on the date given,
235   // but not records enterred after the given date
236   $sql = "select $given from insurance_data as insd " .
237     "left join insurance_companies as ic on ic.id = provider " .
238     "where pid = '$pid' and date_format(date,'%Y-%m-%d') <= '$date' and " .
239     "type='$type' order by date DESC limit 1";
240   return sqlQuery($sql);
243 function getEmployerData($pid, $given = "*")
245     $sql = "select $given from employer_data where pid='$pid' order by date DESC limit 0,1";
246     return sqlQuery($sql);
249 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")
251     // Allow the last name to be followed by a comma and some part of a first name.
252     // New behavior for searches:
253     // Allows comma alone followed by some part of a first name
254     // If the first letter of either name is capital, searches for name starting
255     // with given substring (the expected behavior).  If it is lower case, it
256     // it searches for the substring anywhere in the name.  This applies to either
257     // last name or first name or both.  The arbitrary limit of 100 results is set
258     // in the sql query below. --Mark Leeds
259     $lname = trim($lname);
260     $fname = '';
261      if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
262          $lname = trim($matches[1]);
263          $fname = trim($matches[2]);
264     }
265     $search_for_pieces1 = '';
266     $search_for_pieces2 = '';
267     if ($lname{0} != strtoupper($lname{0})) {$search_for_pieces1 = '%';}
268     if ($fname{0} != strtoupper($fname{0})) {$search_for_pieces2 = '%';}
269     $sql="select $given from patient_data where lname like '"
270         .$search_for_pieces1."$lname%' "
271         ."and fname like '"
272         .$search_for_pieces2."$fname%' "
273         ."order by $orderby limit 100";
275     if ($limit != "all")
276         $sql .= " limit $start, $limit";
277     $rez = sqlStatement($sql);
279     for($iter=0; $row=sqlFetchArray($rez); $iter++)
280         $returnval[$iter]=$row;
282     return $returnval;
285 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")
287     $sql = "select $given from patient_data where pubpid like '$pid%' " .
288         "order by $orderby";
290     if ($limit != "all")
291         $sql .= " limit $start, $limit";
292     $rez = sqlStatement($sql);
293     for($iter=0; $row=sqlFetchArray($rez); $iter++)
294         $returnval[$iter]=$row;
296     return $returnval;
299 // return a collection of Patient PIDs
300 // new arg style by JRM March 2008
301 // 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")
302 function getPatientPID($args)
304     $pid = "%";
305     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
306     $orderby = "lname ASC, fname ASC";
307     $limit="all";
308     $start="0";
310     // alter default values if defined in the passed in args
311     if (isset($args['pid'])) { $pid = $args['pid']; }
312     if (isset($args['given'])) { $given = $args['given']; }
313     if (isset($args['orderby'])) { $orderby = $args['orderby']; }
314     if (isset($args['limit'])) { $limit = $args['limit']; }
315     if (isset($args['start'])) { $start = $args['start']; }
317     $command = "=";
318     if ($pid == -1) $pid = "%";
319     elseif (empty($pid)) $pid = "NULL";
321     if (strstr($pid,"%")) $command = "like";
323     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
324     if ($limit != "all") $sql .= " limit $start, $limit";
326     $rez = sqlStatement($sql);
327     for($iter=0; $row=sqlFetchArray($rez); $iter++)
328         $returnval[$iter]=$row;
330     return $returnval;
333 function getPatientName($pid) {
334     if (empty($pid))
335         return "";
336     $patientData = getPatientPID($pid);
337     if (empty($patientData[0]['lname']))
338         return "";
339     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
340     return $patientName;
343 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
345     $DOB = fixDate($DOB, $DOB);
347     $sql="select $given from patient_data where DOB like '$DOB%' " .
348         "order by $orderby";
350     if ($limit != "all")
351         $sql .= " limit $start, $limit";
353     $rez = sqlStatement($sql);
354     for($iter=0; $row=sqlFetchArray($rez); $iter++)
355         $returnval[$iter]=$row;
357     return $returnval;
360 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
362     $sql="select $given from patient_data where ss like '$ss%' " .
363         "order by $orderby";
365     if ($limit != "all")
366         $sql .= " limit $start, $limit";
368     $rez = sqlStatement($sql);
369     for($iter=0; $row=sqlFetchArray($rez); $iter++)
370         $returnval[$iter]=$row;
372     return $returnval;
375 //(CHEMED) Search by phone number
376 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
378     $phone = ereg_replace( "[[:punct:]]","", $phone );
379     $sql="select $given from patient_data where REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP '$phone' " .
380         "order by $orderby";
382     if ($limit != "all")
383         $sql .= " limit $start, $limit";
385     $rez = sqlStatement($sql);
386     for($iter=0; $row=sqlFetchArray($rez); $iter++)
387         $returnval[$iter]=$row;
389     return $returnval;
392 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
394     $sql="select $given from patient_data order by $orderby";
396     if ($limit != "all")
397         $sql .= " limit $start, $limit";
399     $rez = sqlStatement($sql);
400     for($iter=0; $row=sqlFetchArray($rez); $iter++)
401         $returnval[$iter]=$row;
403     return $returnval;
406 //----------------------input functions
407 function newPatientData(    $db_id="",
408                 $title = "",
409                 $fname = "",
410                 $lname = "",
411                 $mname = "",
412                 $sex = "",
413                 $DOB = "",
414                 $street = "",
415                 $postal_code = "",
416                 $city = "",
417                 $state = "",
418                 $country_code = "",
419                 $ss = "",
420                 $occupation = "",
421                 $phone_home = "",
422                 $phone_biz = "",
423                 $phone_contact = "",
424                 $status = "",
425                 $contact_relationship = "",
426                 $referrer = "",
427                 $referrerID = "",
428                 $email = "",
429                 $language = "",
430                 $ethnoracial = "",
431                 $interpretter = "",
432                 $migrantseasonal = "",
433                 $family_size = "",
434                 $monthly_income = "",
435                 $homeless = "",
436                 $financial_review = "",
437                 $pubpid = "",
438                 $pid = "MAX(pid)+1",
439                 $providerID = "",
440                 $genericname1 = "",
441                 $genericval1 = "",
442                 $genericname2 = "",
443                 $genericval2 = "",
444                 $phone_cell = "",
445                 $hipaa_mail = "",
446                 $hipaa_voice = "",
447                 $squad = 0,
448                 $pharmacy_id = 0,
449                 $drivers_license = "",
450                 $hipaa_notice = "",
451                 $hipaa_message = ""
452             )
454     $DOB = fixDate($DOB);
456     $fitness = 0;
457     $referral_source = '';
458     if ($pid) {
459         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
460         // Check for brain damage:
461         if ($db_id != $rez['id']) {
462             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
463               $rez['id'] . "' to '$db_id' for pid '$pid'";
464             die($errmsg);
465         }
466         $fitness = $rez['fitness'];
467         $referral_source = $rez['referral_source'];
468     }
470     $query = ("replace into patient_data set
471         id='$db_id',
472         title='$title',
473         fname='$fname',
474         lname='$lname',
475         mname='$mname',
476         sex='$sex',
477         DOB='$DOB',
478         street='$street',
479         postal_code='$postal_code',
480         city='$city',
481         state='$state',
482         country_code='$country_code',
483         drivers_license='$drivers_license',
484         ss='$ss',
485         occupation='$occupation',
486         phone_home='$phone_home',
487         phone_biz='$phone_biz',
488         phone_contact='$phone_contact',
489         status='$status',
490         contact_relationship='$contact_relationship',
491         referrer='$referrer',
492         referrerID='$referrerID',
493         email='$email',
494         language='$language',
495         ethnoracial='$ethnoracial',
496         interpretter='$interpretter',
497         migrantseasonal='$migrantseasonal',
498         family_size='$family_size',
499         monthly_income='$monthly_income',
500         homeless='$homeless',
501         financial_review='$financial_review',
502         pubpid='$pubpid',
503         pid = $pid,
504         providerID = '$providerID',
505         genericname1 = '$genericname1',
506         genericval1 = '$genericval1',
507         genericname2 = '$genericname2',
508         genericval2 = '$genericval2',
509         phone_cell = '$phone_cell',
510         pharmacy_id = '$pharmacy_id',
511         hipaa_mail = '$hipaa_mail',
512         hipaa_voice = '$hipaa_voice',
513         hipaa_notice = '$hipaa_notice',
514         hipaa_message = '$hipaa_message',
515         squad = '$squad',
516         fitness='$fitness',
517         referral_source='$referral_source',
518         date=NOW()
519             ");
521     $id = sqlInsert($query);
522     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
524     sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
525                 $phone_biz,$phone_cell,$email,$pid);
527     return $foo['pid'];
530 // Supported input date formats are:
531 //   mm/dd/yyyy
532 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
533 //   yyyy/mm/dd
534 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
536 function fixDate($date, $default="0000-00-00") {
537     $fixed_date = $default;
538     $date = trim($date);
539     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
540         $dmy = preg_split("'[/.-]'", $date);
541         if ($dmy[0] > 99) {
542             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
543         } else {
544             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
545               if ($dmy[2] < 1000) $dmy[2] += 1900;
546               if ($dmy[2] < 1910) $dmy[2] += 100;
547             }
548             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
549         }
550     }
552     return $fixed_date;
555 function updatePatientData($pid,$new)
557   /*******************************************************************
558     $real = getPatientData($pid);
559     $new['DOB'] = fixDate($new['DOB']);
560     while(list($key, $value) = each ($new))
561         $real[$key] = $value;
562     $real['date'] = "'+NOW()+'";
563     $real['id'] = "";
564     $sql = "insert into patient_data set ";
565     while(list($key, $value) = each($real))
566         $sql .= $key." = '$value', ";
567     $sql = substr($sql, 0, -2);
568     return sqlInsert($sql);
569   *******************************************************************/
571   // The above was broken, though seems intent to insert a new patient_data
572   // row for each update.  A good idea, but nothing is doing that yet so
573   // the code below does not yet attempt it.
575   $new['DOB'] = fixDate($new['DOB']);
576   $db_id = $new['id'];
578   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
579   // Check for brain damage:
580   if ($pid != $rez['pid']) {
581     $errmsg = "Internal error: Attempt to change patient data with pid = '" .
582       $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
583     die($errmsg);
584   }
585   $sql = "UPDATE patient_data SET date = NOW()";
586   foreach ($new as $key => $value) {
587     $sql .= ", $key = '$value'";
588   }
589   $sql .= " WHERE id = '$db_id'";
590   $id = sqlInsert($sql);
592   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
593     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
594     $rez['phone_cell'],$rez['email'],$rez['pid']);
596   return $id;
599 function newEmployerData(    $pid,
600                 $name = "",
601                 $street = "",
602                 $postal_code = "",
603                 $city = "",
604                 $state = "",
605                 $country = ""
606             )
608     return sqlInsert("insert into employer_data set
609         name='$name',
610         street='$street',
611         postal_code='$postal_code',
612         city='$city',
613         state='$state',
614         country='$country',
615         pid='$pid',
616         date=NOW()
617         ");
620 function updateEmployerData($pid, $new)
622   $old = getEmployerData($pid);
623   $set = '';
624   $modified = false;
625   foreach (array('name','street','city','state','postal_code','country') as $key) {
626     $value = empty($old[$key]) ? '' : addslashes($old[$key]);
627     if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
628       $value = $new[$key];
629       $modified = true;
630     }
631     $set .= "$key = '$value', ";
632   }
633   if ($modified) {
634     $set .= "pid = '$pid', date = NOW()";
635     return sqlInsert("INSERT INTO employer_data SET $set");
636   }
637   return $old['id'];
640 // This updates or adds the given insurance data info, while retaining any
641 // previously added insurance_data rows that should be preserved.
642 // This does not directly support the maintenance of non-current insurance.
644 function newInsuranceData(
645   $pid,
646   $type = "",
647   $provider = "",
648   $policy_number = "",
649   $group_number = "",
650   $plan_name = "",
651   $subscriber_lname = "",
652   $subscriber_mname = "",
653   $subscriber_fname = "",
654   $subscriber_relationship = "",
655   $subscriber_ss = "",
656   $subscriber_DOB = "",
657   $subscriber_street = "",
658   $subscriber_postal_code = "",
659   $subscriber_city = "",
660   $subscriber_state = "",
661   $subscriber_country = "",
662   $subscriber_phone = "",
663   $subscriber_employer = "",
664   $subscriber_employer_street = "",
665   $subscriber_employer_city = "",
666   $subscriber_employer_postal_code = "",
667   $subscriber_employer_state = "",
668   $subscriber_employer_country = "",
669   $copay = "",
670   $subscriber_sex = "",
671   $effective_date = "0000-00-00")
673   if (strlen($type) <= 0) return FALSE;
675   // If a bad date was passed, err on the side of caution.
676   $effective_date = fixDate($effective_date, date('Y-m-d'));
678   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
679     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
680   $idrow = sqlFetchArray($idres);
682   // Replace the most recent entry in any of the following cases:
683   // * Its effective date is >= this effective date.
684   // * It is the first entry and it has no (insurance) provider.
685   // * There is no encounter that is earlier than the new effective date but
686   //   on or after the old effective date.
687   // Otherwise insert a new entry.
689   $replace = false;
690   if ($idrow) {
691     if (strcmp($idrow['date'], $effective_date) > 0) {
692       $replace = true;
693     }
694     else {
695       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
696         $replace = true;
697       }
698       else {
699         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
700           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
701           "date >= '" . $idrow['date'] . " 00:00:00'");
702         if ($ferow['count'] == 0) $replace = true;
703       }
704     }
705   }
707   if ($replace) {
709     // TBD: This is a bit dangerous in that a typo in entering the effective
710     // date can wipe out previous insurance history.  So we want some data
711     // entry validation somewhere.
712     sqlStatement("DELETE FROM insurance_data WHERE " .
713       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
714       "id != " . $idrow['id']);
716     $data = array();
717     $data['type'] = $type;
718     $data['provider'] = $provider;
719     $data['policy_number'] = $policy_number;
720     $data['group_number'] = $group_number;
721     $data['plan_name'] = $plan_name;
722     $data['subscriber_lname'] = $subscriber_lname;
723     $data['subscriber_mname'] = $subscriber_mname;
724     $data['subscriber_fname'] = $subscriber_fname;
725     $data['subscriber_relationship'] = $subscriber_relationship;
726     $data['subscriber_ss'] = $subscriber_ss;
727     $data['subscriber_DOB'] = $subscriber_DOB;
728     $data['subscriber_street'] = $subscriber_street;
729     $data['subscriber_postal_code'] = $subscriber_postal_code;
730     $data['subscriber_city'] = $subscriber_city;
731     $data['subscriber_state'] = $subscriber_state;
732     $data['subscriber_country'] = $subscriber_country;
733     $data['subscriber_phone'] = $subscriber_phone;
734     $data['subscriber_employer'] = $subscriber_employer;
735     $data['subscriber_employer_city'] = $subscriber_employer_city;
736     $data['subscriber_employer_street'] = $subscriber_employer_street;
737     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
738     $data['subscriber_employer_state'] = $subscriber_employer_state;
739     $data['subscriber_employer_country'] = $subscriber_employer_country;
740     $data['copay'] = $copay;
741     $data['subscriber_sex'] = $subscriber_sex;
742     $data['pid'] = $pid;
743     $data['date'] = $effective_date;
744     updateInsuranceData($idrow['id'], $data);
745     return $idrow['id'];
746   }
747   else {
748     return sqlInsert("INSERT INTO insurance_data SET
749       type = '$type',
750       provider = '$provider',
751       policy_number = '$policy_number',
752       group_number = '$group_number',
753       plan_name = '$plan_name',
754       subscriber_lname = '$subscriber_lname',
755       subscriber_mname = '$subscriber_mname',
756       subscriber_fname = '$subscriber_fname',
757       subscriber_relationship = '$subscriber_relationship',
758       subscriber_ss = '$subscriber_ss',
759       subscriber_DOB = '$subscriber_DOB',
760       subscriber_street = '$subscriber_street',
761       subscriber_postal_code = '$subscriber_postal_code',
762       subscriber_city = '$subscriber_city',
763       subscriber_state = '$subscriber_state',
764       subscriber_country = '$subscriber_country',
765       subscriber_phone = '$subscriber_phone',
766       subscriber_employer = '$subscriber_employer',
767       subscriber_employer_city = '$subscriber_employer_city',
768       subscriber_employer_street = '$subscriber_employer_street',
769       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
770       subscriber_employer_state = '$subscriber_employer_state',
771       subscriber_employer_country = '$subscriber_employer_country',
772       copay = '$copay',
773       subscriber_sex = '$subscriber_sex',
774       pid = '$pid',
775       date = '$effective_date'
776     ");
777   }
780 // This is used internally only.
781 function updateInsuranceData($id, $new)
783   $fields = sqlListFields("insurance_data");
784   $use = array();
786   while(list($key, $value) = each ($new)) {
787     if (in_array($key, $fields)) {
788       $use[$key] = $value;
789     }
790   }
792   $sql = "UPDATE insurance_data SET ";
793   while(list($key, $value) = each($use))
794     $sql .= $key . " = '$value', ";
795   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
797   sqlStatement($sql);
800 function newHistoryData($pid, $new=false) {
801   $sql = "insert into history_data set pid = '$pid', date = NOW()";
802   if ($new) {
803     while(list($key, $value) = each($new)) {
804       if (!get_magic_quotes_gpc()) $value = addslashes($value);
805       $sql .= ", $key = '$value'";
806     }
807   }
808   return sqlInsert($sql);
811 function updateHistoryData($pid,$new)
813         $real = getHistoryData($pid);
814         while(list($key, $value) = each ($new))
815                 $real[$key] = $value;
816         $real['date'] = "'+NOW()+'";
817         $real['id'] = "";
819         $sql = "insert into history_data set ";
820         while(list($key, $value) = each($real))
821                 $sql .= $key." = '$value', ";
822         $sql = substr($sql, 0, -2);
825         return sqlInsert($sql);
828 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
829                 $phone_biz,$phone_cell,$email,$pid="")
831     $db = $GLOBALS['adodb']['db'];
832     $customer_info = array();
834     $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
835     $result = $db->Execute($sql);
836     if ($result && !$result->EOF) {
837         $customer_info['foreign_update'] = true;
838         $customer_info['foreign_id'] = $result->fields['foreign_id'];
839         $customer_info['foreign_table'] = $result->fields['foreign_table'];
840     }
842     ///xml rpc code to connect to accounting package and add user to it
843     $customer_info['firstname'] = $fname;
844     $customer_info['lastname'] = $lname;
845     $customer_info['address'] = $street;
846     $customer_info['suburb'] = $city;
847     $customer_info['state'] = $state;
848     $customer_info['postcode'] = $postal_code;
850     //ezybiz wants state as a code rather than abbreviation
851     $customer_info['geo_zone_id'] = "";
852     $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
853     $db = $GLOBALS['adodb']['db'];
854     $result = $db->Execute($sql);
855     if ($result && !$result->EOF) {
856         $customer_info['geo_zone_id'] = $result->fields['zone_id'];
857     }
859     //ezybiz wants country as a code rather than abbreviation
860     $customer_info['geo_country_id'] = "";
861     $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
862     $db = $GLOBALS['adodb']['db'];
863     $result = $db->Execute($sql);
864     if ($result && !$result->EOF) {
865         $customer_info['geo_country_id'] = $result->fields['countries_id'];
866     }
868     $customer_info['phone1'] = $phone_home;
869     $customer_info['phone1comment'] = "Home Phone";
870     $customer_info['phone2'] = $phone_biz;
871     $customer_info['phone2comment'] = "Business Phone";
872   $customer_info['phone3'] = $phone_cell;
873   $customer_info['phone3comment'] = "Cell Phone";
874     $customer_info['email'] = $email;
875     $customer_info['customernumber'] = $pid;
877     $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
878     $ws = new WSWrapper($function);
880     // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
881     if (is_numeric($ws->value)) {
882         $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
883         $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
884     }
887 // Returns Date of Birth given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
888 function getPatientAge($dobYMD)
890     $tdyYMD=date("Ymd");
891     $yearDiff = substr($tdyYMD,0,4) - substr($dobYMD,0,4);
892     $ageInMonths = ((substr($tdyYMD,0,4)*12)+substr($tdyYMD,4,2)) -
893                    ((substr($dobYMD,0,4)*12)+substr($dobYMD,4,2));
894     $dayDiff = substr($tdyYMD,6,2) - substr($dobYMD,6,2);
895     if ( $dayDiff < 0 ) {
896         $ageInMonths -= 1;
897     }
898     if ( $ageInMonths > 24 ) {
899         $age = intval($ageInMonths/12);
900     }
901     else  {
902         $age = "$ageInMonths month";
903     }
904     return $age;
907 function dateToDB ($date)
909     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
910     return $date;
913 function DBToDate ($date)
915     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
916     return $date;