support a registration date
[openemr.git] / library / patient.inc
blobd14f268d2033b12b25f1130f5832fc4206e3da67
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                 $regdate = ""
453             )
455     $DOB = fixDate($DOB);
456     $regdate = fixDate($regdate);
458     $fitness = 0;
459     $referral_source = '';
460     if ($pid) {
461         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
462         // Check for brain damage:
463         if ($db_id != $rez['id']) {
464             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
465               $rez['id'] . "' to '$db_id' for pid '$pid'";
466             die($errmsg);
467         }
468         $fitness = $rez['fitness'];
469         $referral_source = $rez['referral_source'];
470     }
472     $query = ("replace into patient_data set
473         id='$db_id',
474         title='$title',
475         fname='$fname',
476         lname='$lname',
477         mname='$mname',
478         sex='$sex',
479         DOB='$DOB',
480         street='$street',
481         postal_code='$postal_code',
482         city='$city',
483         state='$state',
484         country_code='$country_code',
485         drivers_license='$drivers_license',
486         ss='$ss',
487         occupation='$occupation',
488         phone_home='$phone_home',
489         phone_biz='$phone_biz',
490         phone_contact='$phone_contact',
491         status='$status',
492         contact_relationship='$contact_relationship',
493         referrer='$referrer',
494         referrerID='$referrerID',
495         email='$email',
496         language='$language',
497         ethnoracial='$ethnoracial',
498         interpretter='$interpretter',
499         migrantseasonal='$migrantseasonal',
500         family_size='$family_size',
501         monthly_income='$monthly_income',
502         homeless='$homeless',
503         financial_review='$financial_review',
504         pubpid='$pubpid',
505         pid = $pid,
506         providerID = '$providerID',
507         genericname1 = '$genericname1',
508         genericval1 = '$genericval1',
509         genericname2 = '$genericname2',
510         genericval2 = '$genericval2',
511         phone_cell = '$phone_cell',
512         pharmacy_id = '$pharmacy_id',
513         hipaa_mail = '$hipaa_mail',
514         hipaa_voice = '$hipaa_voice',
515         hipaa_notice = '$hipaa_notice',
516         hipaa_message = '$hipaa_message',
517         squad = '$squad',
518         fitness='$fitness',
519         referral_source='$referral_source',
520         regdate='$regdate',
521         date=NOW()
522             ");
524     $id = sqlInsert($query);
525     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
527     sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
528                 $phone_biz,$phone_cell,$email,$pid);
530     return $foo['pid'];
533 // Supported input date formats are:
534 //   mm/dd/yyyy
535 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
536 //   yyyy/mm/dd
537 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
539 function fixDate($date, $default="0000-00-00") {
540     $fixed_date = $default;
541     $date = trim($date);
542     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
543         $dmy = preg_split("'[/.-]'", $date);
544         if ($dmy[0] > 99) {
545             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
546         } else {
547             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
548               if ($dmy[2] < 1000) $dmy[2] += 1900;
549               if ($dmy[2] < 1910) $dmy[2] += 100;
550             }
551             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
552         }
553     }
555     return $fixed_date;
558 function updatePatientData($pid,$new)
560   /*******************************************************************
561     $real = getPatientData($pid);
562     $new['DOB'] = fixDate($new['DOB']);
563     while(list($key, $value) = each ($new))
564         $real[$key] = $value;
565     $real['date'] = "'+NOW()+'";
566     $real['id'] = "";
567     $sql = "insert into patient_data set ";
568     while(list($key, $value) = each($real))
569         $sql .= $key." = '$value', ";
570     $sql = substr($sql, 0, -2);
571     return sqlInsert($sql);
572   *******************************************************************/
574   // The above was broken, though seems intent to insert a new patient_data
575   // row for each update.  A good idea, but nothing is doing that yet so
576   // the code below does not yet attempt it.
578   $new['DOB'] = fixDate($new['DOB']);
579   $db_id = $new['id'];
581   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
582   // Check for brain damage:
583   if ($pid != $rez['pid']) {
584     $errmsg = "Internal error: Attempt to change patient data with pid = '" .
585       $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
586     die($errmsg);
587   }
588   $sql = "UPDATE patient_data SET date = NOW()";
589   foreach ($new as $key => $value) {
590     $sql .= ", $key = '$value'";
591   }
592   $sql .= " WHERE id = '$db_id'";
593   $id = sqlInsert($sql);
595   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
596     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
597     $rez['phone_cell'],$rez['email'],$rez['pid']);
599   return $id;
602 function newEmployerData(    $pid,
603                 $name = "",
604                 $street = "",
605                 $postal_code = "",
606                 $city = "",
607                 $state = "",
608                 $country = ""
609             )
611     return sqlInsert("insert into employer_data set
612         name='$name',
613         street='$street',
614         postal_code='$postal_code',
615         city='$city',
616         state='$state',
617         country='$country',
618         pid='$pid',
619         date=NOW()
620         ");
623 function updateEmployerData($pid, $new)
625   $old = getEmployerData($pid);
626   $set = '';
627   $modified = false;
628   foreach (array('name','street','city','state','postal_code','country') as $key) {
629     $value = empty($old[$key]) ? '' : addslashes($old[$key]);
630     if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
631       $value = $new[$key];
632       $modified = true;
633     }
634     $set .= "$key = '$value', ";
635   }
636   if ($modified) {
637     $set .= "pid = '$pid', date = NOW()";
638     return sqlInsert("INSERT INTO employer_data SET $set");
639   }
640   return $old['id'];
643 // This updates or adds the given insurance data info, while retaining any
644 // previously added insurance_data rows that should be preserved.
645 // This does not directly support the maintenance of non-current insurance.
647 function newInsuranceData(
648   $pid,
649   $type = "",
650   $provider = "",
651   $policy_number = "",
652   $group_number = "",
653   $plan_name = "",
654   $subscriber_lname = "",
655   $subscriber_mname = "",
656   $subscriber_fname = "",
657   $subscriber_relationship = "",
658   $subscriber_ss = "",
659   $subscriber_DOB = "",
660   $subscriber_street = "",
661   $subscriber_postal_code = "",
662   $subscriber_city = "",
663   $subscriber_state = "",
664   $subscriber_country = "",
665   $subscriber_phone = "",
666   $subscriber_employer = "",
667   $subscriber_employer_street = "",
668   $subscriber_employer_city = "",
669   $subscriber_employer_postal_code = "",
670   $subscriber_employer_state = "",
671   $subscriber_employer_country = "",
672   $copay = "",
673   $subscriber_sex = "",
674   $effective_date = "0000-00-00")
676   if (strlen($type) <= 0) return FALSE;
678   // If a bad date was passed, err on the side of caution.
679   $effective_date = fixDate($effective_date, date('Y-m-d'));
681   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
682     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
683   $idrow = sqlFetchArray($idres);
685   // Replace the most recent entry in any of the following cases:
686   // * Its effective date is >= this effective date.
687   // * It is the first entry and it has no (insurance) provider.
688   // * There is no encounter that is earlier than the new effective date but
689   //   on or after the old effective date.
690   // Otherwise insert a new entry.
692   $replace = false;
693   if ($idrow) {
694     if (strcmp($idrow['date'], $effective_date) > 0) {
695       $replace = true;
696     }
697     else {
698       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
699         $replace = true;
700       }
701       else {
702         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
703           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
704           "date >= '" . $idrow['date'] . " 00:00:00'");
705         if ($ferow['count'] == 0) $replace = true;
706       }
707     }
708   }
710   if ($replace) {
712     // TBD: This is a bit dangerous in that a typo in entering the effective
713     // date can wipe out previous insurance history.  So we want some data
714     // entry validation somewhere.
715     sqlStatement("DELETE FROM insurance_data WHERE " .
716       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
717       "id != " . $idrow['id']);
719     $data = array();
720     $data['type'] = $type;
721     $data['provider'] = $provider;
722     $data['policy_number'] = $policy_number;
723     $data['group_number'] = $group_number;
724     $data['plan_name'] = $plan_name;
725     $data['subscriber_lname'] = $subscriber_lname;
726     $data['subscriber_mname'] = $subscriber_mname;
727     $data['subscriber_fname'] = $subscriber_fname;
728     $data['subscriber_relationship'] = $subscriber_relationship;
729     $data['subscriber_ss'] = $subscriber_ss;
730     $data['subscriber_DOB'] = $subscriber_DOB;
731     $data['subscriber_street'] = $subscriber_street;
732     $data['subscriber_postal_code'] = $subscriber_postal_code;
733     $data['subscriber_city'] = $subscriber_city;
734     $data['subscriber_state'] = $subscriber_state;
735     $data['subscriber_country'] = $subscriber_country;
736     $data['subscriber_phone'] = $subscriber_phone;
737     $data['subscriber_employer'] = $subscriber_employer;
738     $data['subscriber_employer_city'] = $subscriber_employer_city;
739     $data['subscriber_employer_street'] = $subscriber_employer_street;
740     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
741     $data['subscriber_employer_state'] = $subscriber_employer_state;
742     $data['subscriber_employer_country'] = $subscriber_employer_country;
743     $data['copay'] = $copay;
744     $data['subscriber_sex'] = $subscriber_sex;
745     $data['pid'] = $pid;
746     $data['date'] = $effective_date;
747     updateInsuranceData($idrow['id'], $data);
748     return $idrow['id'];
749   }
750   else {
751     return sqlInsert("INSERT INTO insurance_data SET
752       type = '$type',
753       provider = '$provider',
754       policy_number = '$policy_number',
755       group_number = '$group_number',
756       plan_name = '$plan_name',
757       subscriber_lname = '$subscriber_lname',
758       subscriber_mname = '$subscriber_mname',
759       subscriber_fname = '$subscriber_fname',
760       subscriber_relationship = '$subscriber_relationship',
761       subscriber_ss = '$subscriber_ss',
762       subscriber_DOB = '$subscriber_DOB',
763       subscriber_street = '$subscriber_street',
764       subscriber_postal_code = '$subscriber_postal_code',
765       subscriber_city = '$subscriber_city',
766       subscriber_state = '$subscriber_state',
767       subscriber_country = '$subscriber_country',
768       subscriber_phone = '$subscriber_phone',
769       subscriber_employer = '$subscriber_employer',
770       subscriber_employer_city = '$subscriber_employer_city',
771       subscriber_employer_street = '$subscriber_employer_street',
772       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
773       subscriber_employer_state = '$subscriber_employer_state',
774       subscriber_employer_country = '$subscriber_employer_country',
775       copay = '$copay',
776       subscriber_sex = '$subscriber_sex',
777       pid = '$pid',
778       date = '$effective_date'
779     ");
780   }
783 // This is used internally only.
784 function updateInsuranceData($id, $new)
786   $fields = sqlListFields("insurance_data");
787   $use = array();
789   while(list($key, $value) = each ($new)) {
790     if (in_array($key, $fields)) {
791       $use[$key] = $value;
792     }
793   }
795   $sql = "UPDATE insurance_data SET ";
796   while(list($key, $value) = each($use))
797     $sql .= $key . " = '$value', ";
798   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
800   sqlStatement($sql);
803 function newHistoryData($pid, $new=false) {
804   $sql = "insert into history_data set pid = '$pid', date = NOW()";
805   if ($new) {
806     while(list($key, $value) = each($new)) {
807       if (!get_magic_quotes_gpc()) $value = addslashes($value);
808       $sql .= ", $key = '$value'";
809     }
810   }
811   return sqlInsert($sql);
814 function updateHistoryData($pid,$new)
816         $real = getHistoryData($pid);
817         while(list($key, $value) = each ($new))
818                 $real[$key] = $value;
819         $real['date'] = "'+NOW()+'";
820         $real['id'] = "";
822         $sql = "insert into history_data set ";
823         while(list($key, $value) = each($real))
824                 $sql .= $key." = '$value', ";
825         $sql = substr($sql, 0, -2);
828         return sqlInsert($sql);
831 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
832                 $phone_biz,$phone_cell,$email,$pid="")
834     $db = $GLOBALS['adodb']['db'];
835     $customer_info = array();
837     $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
838     $result = $db->Execute($sql);
839     if ($result && !$result->EOF) {
840         $customer_info['foreign_update'] = true;
841         $customer_info['foreign_id'] = $result->fields['foreign_id'];
842         $customer_info['foreign_table'] = $result->fields['foreign_table'];
843     }
845     ///xml rpc code to connect to accounting package and add user to it
846     $customer_info['firstname'] = $fname;
847     $customer_info['lastname'] = $lname;
848     $customer_info['address'] = $street;
849     $customer_info['suburb'] = $city;
850     $customer_info['state'] = $state;
851     $customer_info['postcode'] = $postal_code;
853     //ezybiz wants state as a code rather than abbreviation
854     $customer_info['geo_zone_id'] = "";
855     $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
856     $db = $GLOBALS['adodb']['db'];
857     $result = $db->Execute($sql);
858     if ($result && !$result->EOF) {
859         $customer_info['geo_zone_id'] = $result->fields['zone_id'];
860     }
862     //ezybiz wants country as a code rather than abbreviation
863     $customer_info['geo_country_id'] = "";
864     $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
865     $db = $GLOBALS['adodb']['db'];
866     $result = $db->Execute($sql);
867     if ($result && !$result->EOF) {
868         $customer_info['geo_country_id'] = $result->fields['countries_id'];
869     }
871     $customer_info['phone1'] = $phone_home;
872     $customer_info['phone1comment'] = "Home Phone";
873     $customer_info['phone2'] = $phone_biz;
874     $customer_info['phone2comment'] = "Business Phone";
875   $customer_info['phone3'] = $phone_cell;
876   $customer_info['phone3comment'] = "Cell Phone";
877     $customer_info['email'] = $email;
878     $customer_info['customernumber'] = $pid;
880     $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
881     $ws = new WSWrapper($function);
883     // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
884     if (is_numeric($ws->value)) {
885         $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
886         $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
887     }
890 // Returns Date of Birth given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
891 function getPatientAge($dobYMD)
893     $tdyYMD=date("Ymd");
894     $yearDiff = substr($tdyYMD,0,4) - substr($dobYMD,0,4);
895     $ageInMonths = ((substr($tdyYMD,0,4)*12)+substr($tdyYMD,4,2)) -
896                    ((substr($dobYMD,0,4)*12)+substr($dobYMD,4,2));
897     $dayDiff = substr($tdyYMD,6,2) - substr($dobYMD,6,2);
898     if ( $dayDiff < 0 ) {
899         $ageInMonths -= 1;
900     }
901     if ( $ageInMonths > 24 ) {
902         $age = intval($ageInMonths/12);
903     }
904     else  {
905         $age = "$ageInMonths month";
906     }
907     return $age;
910 function dateToDB ($date)
912     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
913     return $date;
916 function DBToDate ($date)
918     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
919     return $date;