fixed failure to retain referral_source when updating demographics
[openemr.git] / library / patient.inc
blob1e6175206ff572805b062988e9cc3d403ec850ef
1 <?php
2 include_once("{$GLOBALS['srcdir']}/sql.inc");
3 require_once(dirname(__FILE__) . "/classes/WSWrapper.class.php");
5 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS") {
6         $sql = "select $given from patient_data where pid='$pid' order by date DESC limit 0,1";
7         return sqlQuery($sql);
10 function getLanguages() {
11         $returnval = array('','english');
12         $sql = "select distinct lower(language) as language from patient_data";
13         $rez = sqlStatement($sql);
14         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
15                 if (($row["language"] != "english") && ($row["language"] != "")) {
16                         array_push($returnval, $row["language"]);
17                 }
18         }
21         return $returnval;
24 function getInsuranceProviders() {
25         $returnval = array();
27         if (true) {
28                 $sql = "select name, id from insurance_companies order by name, id";
29                 $rez = sqlStatement($sql);
30                 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
31                         $returnval[$row['id']] = $row['name'];
32                 }
33         }
35         // Please leave this here. I have a user who wants to see zip codes and PO
36         // box numbers listed along with the insurance company names, as many companies
37         // have different billing addresses for different plans.  -- Rod Roark
38         //
39         else {
40                 $sql = "select insurance_companies.name, insurance_companies.id, " .
41                   "addresses.zip, addresses.line1 " .
42                   "from insurance_companies, addresses " .
43                   "where addresses.foreign_id = insurance_companies.id " .
44                   "order by insurance_companies.name, addresses.zip";
46                 $rez = sqlStatement($sql);
48                 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
49                         preg_match("/\d+/", $row['line1'], $matches);
50                         $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
51                           "," . $matches[0] . ")";
52                 }
53         }
55         // print_r($retval);
57         return $returnval;
61 function getProviders() {
62         $returnval = array("");
63         $sql = "select fname,lname from users where authorized=1";
64         $rez = sqlStatement($sql);
65         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
66                 if (($row["fname"] != "") && ($row["lname"] != "")) {
67                         array_push($returnval, $row["fname"] . " " . $row["lname"]);
68                 }
69         }
72         return $returnval;
75 function getProviderInfo($providerID = "%", $providers_only = true) {
76         $param1 = "";
77         if ($providers_only) {
78                 $param1 = "AND authorized=1";
79         }
80         $command = "=";
81         if ($providerID == "%") {
82                 $command = "like";
83         }
84         $query = "select distinct id,username,lname,fname, authorized, info, facility from users where id $command '" . mysql_real_escape_string($providerID) . "' " . $param1;
85         $rez = sqlStatement($query);
86         for($iter=0; $row=sqlFetchArray($rez); $iter++)
87                 $returnval[$iter]=$row;
89         //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
90         //accessible from $resultval['key']
92         if($iter==1) {
93                 $akeys = array_keys($returnval[0]);
94                 foreach($akeys as $key) {
96                         $returnval[0][$key] = $returnval[0][$key];
97                 }
98         }
99         return $returnval;
102 //same as above but does not reduce if only 1 row returned
103 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
104         $param1 = "";
105         if ($providers_only) {
106                 $param1 = "AND authorized=1";
107         }
108         $command = "=";
109         if ($providerID == "%") {
110                 $command = "like";
111         }
112         $query = "select distinct id,username,lname,fname, authorized, info, facility from users where id $command '" . mysql_real_escape_string($providerID) . "' " . $param1;
114         $rez = sqlStatement($query);
115         for($iter=0; $row=sqlFetchArray($rez); $iter++)
116                 $returnval[$iter]=$row;
118         return $returnval;
123 function getProviderName($providerID) {
125         $pi = getProviderInfo($providerID);
127         if (strlen($pi[0]["lname"]) > 0) {
128                 return $pi[0]['fname'] . " " . $pi[0]['lname'];
129         }
131         return "";
134 function getProviderId($providerName) {
135         $query = "select id from users where username = '". mysql_real_escape_string($providerName)."'";
137         $rez = sqlStatement($query);
138         for($iter=0; $row=sqlFetchArray($rez); $iter++)
139                 $returnval[$iter]=$row;
141         return $returnval;
144 function getEthnoRacials() {
145         $returnval = array("");
146         $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
147         $rez = sqlStatement($sql);
148         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
149                 if (($row["ethnoracial"] != "")) {
150                         array_push($returnval, $row["ethnoracial"]);
151                 }
152         }
155         return $returnval;
158 function getHistoryData($pid, $given = "*")
160         $sql = "select $given from history_data where pid='$pid' order by date DESC limit 0,1";
161         return sqlQuery($sql);
164 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
165 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
167         $sql = "select $given from insurance_data as insd left join insurance_companies as ic on ic.id = insd.provider where pid='$pid' and type='$type' order by date DESC limit 0,1";
168         return sqlQuery($sql);
171 function getInsuranceDataByDate( $pid, $date, $type, $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
172 { //this must take the date in the following manner: YYYY-MM-DD
173         //this function recalls the insurance value that was most recently enterred from the
174         //given date. it will call up most recent records up to and on the date given,
175         //but not records enterred after the given date
176         $sql = "select $given from insurance_data as insd left join insurance_companies as ic on ic.id = provider where pid='$pid' and  date_format(date,'%Y-%m-%d')<='$date' and type='$type' order by date DESC limit 0,1";
177         return sqlQuery($sql);
181 function getEmployerData($pid, $given = "*")
183         $sql = "select $given from employer_data where pid='$pid' order by date DESC limit 0,1";
184         return sqlQuery($sql);
187 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")
189         /****
190         $sql="select pid, MAX(id) as id from patient_data group by pid DESC order by pid ASC";
191         $res = sqlStatement($sql);
192         $sql="select $given from patient_data where lname like '$lname%' and (";
193         for ($iter = 0;$row = sqlFetchArray($res);$iter++)
194                 $sql.=" id='{$row['id']}' or";
195         if ($iter > 0)
196                 $sql = substr($sql, 0, -3) . ") order by $orderby";
197         else
198                 $sql = substr($sql, 0, -5)."order by $orderby";
199         ****/
201         // WTF? That was a good way to create a 200KB sql statement.
203         // Allow the last name to be followed by a comma and some part of a first name.
204         // New behavior for searches:
205         // Allows comma alone followed by some part of a first name
206         // If the first letter of either name is capital, searches for name starting
207         // with given substring (the expected behavior).  If it is lower case, it
208         // it searches for the substring anywhere in the name.  This applies to either
209         // last name or first name or both.  The arbitrary limit of 100 results is set
210         // in the sql query below. --Mark Leeds
211         $lname = trim($lname);
212         $fname = '';
213         if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
214                 $lname = trim($matches[1]);
215                 $fname = trim($matches[2]);
216         }
217         $search_for_pieces1 = '';
218         $search_for_pieces2 = '';
219         if ($lname{0} != strtoupper($lname{0})) {$search_for_pieces1 = '%';}
220         if ($fname{0} != strtoupper($fname{0})) {$search_for_pieces2 = '%';}
221         $sql="select $given from patient_data where lname like '"
222                 .$search_for_pieces1."$lname%' "
223                 ."and fname like '"
224                 .$search_for_pieces2."$fname%' "
225                 ."order by $orderby limit 100";
227         if ($limit != "all")
228                 $sql .= " limit $start, $limit";
229         $rez = sqlStatement($sql);
231         for($iter=0; $row=sqlFetchArray($rez); $iter++)
232                 $returnval[$iter]=$row;
234         return $returnval;
237 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")
239         /****
240         $sql="select pid, MAX(id) as id from patient_data group by pid DESC order by pid ASC";
241         $res = sqlStatement($sql);
242         $sql="select $given from patient_data where pubpid like '$pid%' and (";
243         for ($iter = 0;$row = sqlFetchArray($res);$iter++)
244                 $sql.=" id='{$row['id']}' or";
245         if ($iter > 0)
246                 $sql = substr($sql, 0, -3) . ") order by $orderby";
247         else
248                 $sql = substr($sql, 0, -5)."order by $orderby";
249         ****/
251         $sql = "select $given from patient_data where pubpid like '$pid%' " .
252                 "order by $orderby";
254         if ($limit != "all")
255                 $sql .= " limit $start, $limit";
256         $rez = sqlStatement($sql);
257         for($iter=0; $row=sqlFetchArray($rez); $iter++)
258                 $returnval[$iter]=$row;
260         return $returnval;
263 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")
265         $command = "=";
266         if ($pid == -1)
267                 $pid = "%";
268         elseif (empty($pid))
269                 $pid = "NULL";
271         if (strstr($pid,"%"))
272                 $command = "like";
274         $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
276         if ($limit != "all")
277                 $sql .= " limit $start, $limit";
279         $rez = sqlStatement($sql);
280         for($iter=0; $row=sqlFetchArray($rez); $iter++)
281                 $returnval[$iter]=$row;
284         return $returnval;
287 function getPatientName($pid) {
288         if (empty($pid))
289                 return "";
290         $patientData = getPatientPID($pid);
291         if (empty($patientData[0]['lname']))
292                 return "";
293         $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
294         return $patientName;
298 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
300         /****
301         $sql="select pid, MAX(id) as id from patient_data group by pid DESC order by pid ASC";
302         $res = sqlStatement($sql);
303         $sql="select $given from patient_data where DOB like '$DOB%' and (";
304         for ($iter = 0;$row = sqlFetchArray($res);$iter++)
305                 $sql.=" id='{$row['id']}' or";
306         if ($iter > 0)
307                 $sql = substr($sql, 0, -3) . ") order by $orderby";
308         else
309                 $sql = substr($sql, 0, -5)."order by $orderby";
310         ****/
312         $DOB = fixDate($DOB, $DOB);
314         $sql="select $given from patient_data where DOB like '$DOB%' " .
315                 "order by $orderby";
317         if ($limit != "all")
318                 $sql .= " limit $start, $limit";
320         $rez = sqlStatement($sql);
321         for($iter=0; $row=sqlFetchArray($rez); $iter++)
322                 $returnval[$iter]=$row;
324         return $returnval;
327 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
329         /****
330         $sql="select pid, MAX(id) as id from patient_data group by pid DESC order by pid ASC";
331         $res = sqlStatement($sql);
332         $sql="select $given from patient_data where ss like '$ss%' and (";
333         for ($iter = 0;$row = sqlFetchArray($res);$iter++)
334                 $sql.=" id='{$row['id']}' or";
335         if ($iter > 0)
336                 $sql = substr($sql, 0, -3) . ") order by $orderby";
337         else
338                 $sql = substr($sql, 0, -5)."order by $orderby";
339         ****/
341         $sql="select $given from patient_data where ss like '$ss%' " .
342                 "order by $orderby";
344         if ($limit != "all")
345                 $sql .= " limit $start, $limit";
347         $rez = sqlStatement($sql);
348         for($iter=0; $row=sqlFetchArray($rez); $iter++)
349                 $returnval[$iter]=$row;
351         return $returnval;
354 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
356         /****
357         $sql="select pid, MAX(id) as id from patient_data group by pid DESC order by pid ASC";
358         $res = sqlStatement($sql);
359         $sql="select $given from patient_data where ";
360         for ($iter = 0;$row = sqlFetchArray($res);$iter++)
361                 $sql.="id='{$row['id']}' or ";
362         $sql = substr($sql, 0, -3) . "order by $orderby";
363         ****/
365         $sql="select $given from patient_data order by $orderby";
367         if ($limit != "all")
368                 $sql .= " limit $start, $limit";
370         $rez = sqlStatement($sql);
371         for($iter=0; $row=sqlFetchArray($rez); $iter++)
372                 $returnval[$iter]=$row;
374         return $returnval;
377 //----------------------input functions
378 function newPatientData(        $db_id="",
379                                 $title = "",
380                                 $fname = "",
381                                 $lname = "",
382                                 $mname = "",
383                                 $sex = "",
384                                 $DOB = "",
385                                 $street = "",
386                                 $postal_code = "",
387                                 $city = "",
388                                 $state = "",
389                                 $country_code = "",
390                                 $ss = "",
391                                 $occupation = "",
392                                 $phone_home = "",
393                                 $phone_biz = "",
394                                 $phone_contact = "",
395                                 $status = "",
396                                 $contact_relationship = "",
397                                 $referrer = "",
398                                 $referrerID = "",
399                                 $email = "",
400                                 $language = "",
401                                 $ethnoracial = "",
402                                 $interpretter = "",
403                                 $migrantseasonal = "",
404                                 $family_size = "",
405                                 $monthly_income = "",
406                                 $homeless = "",
407                                 $financial_review = "",
408                                 $pubpid = "",
409                                 $pid = "MAX(pid)+1",
410                                 $providerID = "",
411                                 $genericname1 = "",
412                                 $genericval1 = "",
413                                 $genericname2 = "",
414                                 $genericval2 = "",
415                                 $phone_cell = "",
416                                 $hipaa_mail = "",
417                                 $hipaa_voice = "",
418                                 $squad = 0,
419                                 $pharmacy_id = 0,
420                                 $drivers_license = ""
421                         )
423         $DOB = fixDate($DOB);
425         $fitness = 0;
426         $referral_source = '';
427         if ($pid) {
428                 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
429                 // Check for brain damage:
430                 if ($db_id != $rez['id']) {
431                         $errmsg = "Internal error: Attempt to change patient_data.id from '" .
432                           $rez['id'] . "' to '$db_id' for pid '$pid'";
433                         die($errmsg);
434                 }
435                 $fitness = $rez['fitness'];
436                 $referral_source = $rez['referral_source'];
437         }
439         $query = ("replace into patient_data set
440                 id='$db_id',
441                 title='$title',
442                 fname='$fname',
443                 lname='$lname',
444                 mname='$mname',
445                 sex='$sex',
446                 DOB='$DOB',
447                 street='$street',
448                 postal_code='$postal_code',
449                 city='$city',
450                 state='$state',
451                 country_code='$country_code',
452                 drivers_license='$drivers_license',
453                 ss='$ss',
454                 occupation='$occupation',
455                 phone_home='$phone_home',
456                 phone_biz='$phone_biz',
457                 phone_contact='$phone_contact',
458                 status='$status',
459                 contact_relationship='$contact_relationship',
460                 referrer='$referrer',
461                 referrerID='$referrerID',
462                 email='$email',
463                 language='$language',
464                 ethnoracial='$ethnoracial',
465                 interpretter='$interpretter',
466                 migrantseasonal='$migrantseasonal',
467                 family_size='$family_size',
468                 monthly_income='$monthly_income',
469                 homeless='$homeless',
470                 financial_review='$financial_review',
471                 pubpid='$pubpid',
472                 pid = $pid,
473                 providerID = '$providerID',
474                 genericname1 = '$genericname1',
475                 genericval1 = '$genericval1',
476                 genericname2 = '$genericname2',
477                 genericval2 = '$genericval2',
478                 phone_cell = '$phone_cell',
479                 pharmacy_id = '$pharmacy_id',
480                 hipaa_mail = '$hipaa_mail',
481                 hipaa_voice = '$hipaa_voice',
482                 squad = '$squad',
483                 fitness='$fitness',
484                 referral_source='$referral_source',
485                 date=NOW()
486                         ");
488         $id = sqlInsert($query);
489         $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
491         sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
492                                 $phone_biz,$email,$pid);
494         return $foo['pid'];
497 // Supported input date formats are:
498 //   mm/dd/yyyy
499 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
500 //   yyyy/mm/dd
501 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
503 function fixDate($date, $default="0000-00-00") {
504     $fixed_date = $default;
505     $date = trim($date);
506     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
507         $dmy = preg_split("'[/.-]'", $date);
508         if ($dmy[0] > 99) {
509             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
510         } else {
511             if ($dmy[2] < 1000) $dmy[2] += 1900;
512             if ($dmy[2] < 1910) $dmy[2] += 100;
513             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
514         }
515     }
517     return $fixed_date;
521 function updatePatientData($pid,$new)
523         $real = getPatientData($pid);
524         $new['DOB'] = fixDate($new['DOB']);
525         while(list($key, $value) = each ($new))
526                 $real[$key] = $value;
527         $real['date'] = "'+NOW()+'";
528         $real['id'] = "";
530         $sql = "insert into patient_data set ";
531         while(list($key, $value) = each($real))
532                 $sql .= $key." = '$value', ";
533         $sql = substr($sql, 0, -2);
536         return sqlInsert($sql);
540 function newEmployerData(       $pid,
541                                 $name = "",
542                                 $street = "",
543                                 $postal_code = "",
544                                 $city = "",
545                                 $state = "",
546                                 $country = ""
547                         )
549         return sqlInsert("insert into employer_data set
550                 name='$name',
551                 street='$street',
552                 postal_code='$postal_code',
553                 city='$city',
554                 state='$state',
555                 country='$country',
556                 pid='$pid',
557                 date=NOW()
558                 ");
561 function updateEmployerData($pid,$new)
563         $real = getEmployerData($pid);
564         while(list($key, $value) = each ($new))
565                 $real[$key] = $value;
566         $real['date'] = "'+NOW()+'";
567         $real['id'] = "";
569         $sql = "insert into employer_data set ";
570         while(list($key, $value) = each($real))
571                 $sql .= $key." = '$value', ";
572         $sql = substr($sql, 0, -2);
575         return sqlInsert($sql);
578 function newInsuranceData(      $pid,
579                                 $type = "",
580                                 $provider = "",
581                                 $policy_number = "",
582                                 $group_number = "",
583                                 $plan_name = "",
584                                 $subscriber_lname = "",
585                                 $subscriber_mname = "",
586                                 $subscriber_fname = "",
587                                 $subscriber_relationship = "",
588                                 $subscriber_ss = "",
589                                 $subscriber_DOB = "",
590                                 $subscriber_street = "",
591                                 $subscriber_postal_code = "",
592                                 $subscriber_city = "",
593                                 $subscriber_state = "",
594                                 $subscriber_country = "",
595                                 $subscriber_phone = "",
596                                 $subscriber_employer = "",
597                                 $subscriber_employer_street = "",
598                                 $subscriber_employer_city = "",
599                                 $subscriber_employer_postal_code = "",
600                                 $subscriber_employer_state = "",
601                                 $subscriber_employer_country = "",
602                                 $copay = "",
603                                 $subscriber_sex = ""
604                         )
606         if (strlen($type) > 0) {
607         $query = "select * from insurance_data where type='" . $type  . "' and pid = " . $pid .  " limit 1";
608         }
609         else {
610                 return FALSE;
611         }
612         $res = sqlQuery ($query);
614         if ($res) {
615                 $data['type'] = $type;
616                 $data['provider'] = $provider;
617                 $data['policy_number']=$policy_number;
618                 $data['group_number']=$group_number;
619                 $data['plan_name']=$plan_name;
620                 $data['subscriber_lname']=$subscriber_lname;
621                 $data['subscriber_mname']=$subscriber_mname;
622                 $data['subscriber_fname']=$subscriber_fname;
623                 $data['subscriber_relationship']=$subscriber_relationship;
624                 $data['subscriber_ss']=$subscriber_ss;
625                 $data['subscriber_DOB']=$subscriber_DOB;
626                 $data['subscriber_street']=$subscriber_street;
627                 $data['subscriber_postal_code']=$subscriber_postal_code;
628                 $data['subscriber_city']=$subscriber_city;
629                 $data['subscriber_state']=$subscriber_state;
630                 $data['subscriber_country']=$subscriber_country;
631                 $data['subscriber_phone']=$subscriber_phone;
632                 $data['subscriber_employer']=$subscriber_employer;
633                 $data['subscriber_employer_city']=$subscriber_employer_city;
634                 $data['subscriber_employer_street']=$subscriber_employer_street;
635                 $data['subscriber_employer_postal_code']=$subscriber_employer_postal_code;
636                 $data['subscriber_employer_state']=$subscriber_employer_state;
637                 $data['subscriber_employer_country']=$subscriber_employer_country;
638                 $data['copay']=$copay;
639                 $data['subscriber_sex']=$subscriber_sex;
640                 $data['pid']=$pid;
641                 $data['date']="NOW()";
642         //      echo "updating<br><br>";
644                 return updateInsuranceData($pid,$data);
645         }
646         else {
647         return sqlInsert("insert into insurance_data set
648                 type='$type',
649                 provider='$provider',
650                 policy_number='$policy_number',
651                 group_number='$group_number',
652                 plan_name='$plan_name',
653                 subscriber_lname='$subscriber_lname',
654                 subscriber_mname='$subscriber_mname',
655                 subscriber_fname='$subscriber_fname',
656                 subscriber_relationship='$subscriber_relationship',
657                 subscriber_ss='$subscriber_ss',
658                 subscriber_DOB='$subscriber_DOB',
659                 subscriber_street='$subscriber_street',
660                 subscriber_postal_code='$subscriber_postal_code',
661                 subscriber_city='$subscriber_city',
662                 subscriber_state='$subscriber_state',
663                 subscriber_country='$subscriber_country',
664                 subscriber_phone='$subscriber_phone',
665                 subscriber_employer = '$subscriber_employer',
666                 subscriber_employer_city='$subscriber_employer_city',
667                 subscriber_employer_street='$subscriber_employer_street',
668                 subscriber_employer_postal_code='$subscriber_employer_postal_code',
669                 subscriber_employer_state='$subscriber_employer_state',
670                 subscriber_employer_country='$subscriber_employer_country',
671                 copay='$copay',
672                 subscriber_sex='$subscriber_sex',
673                 pid='$pid',
674                 date=NOW()
675                 ");
676         }
679 function updateInsuranceData($pid,$new)
681                 $fields = sqlListFields("insurance_data");
683         $real = getInsuranceData($pid);
684         $use = array();
685         while(list($key, $value) = each ($new)) {
686                         if (in_array($key,$fields)){
687                         $use[$key] = $value;
688                         }
689                 }
690         $real['date'] = "'+NOW()+'";
691         $real['id'] = "";
693         $sql = "replace into insurance_data set ";
694         while(list($key, $value) = each($use))
695                 $sql .= $key." = '$value', ";
698         $sql = substr($sql, 0, -2);
700         //echo $sql;
701         //exit;
702         return sqlInsert($sql);
706 function newHistoryData(        $pid,
707                                 $coffee = "",
708                                 $tobacco = "",
709                                 $alcohol = "",
710                                 $sleep_patterns = "",
711                                 $exercise_patterns = "",
712                                 $seatbelt_use = "",
713                                 $counseling = "",
714                                 $hazardous_activities = "",
715                                 $last_breast_exam = "",
716                                 $last_mammogram = "",
717                                 $last_gynocological_exam = "",
718                                 $last_rectal_exam = "",
719                                 $last_prostate_exam = "",
720                                 $last_physical_exam = "",
721                                 $last_sigmoidoscopy_colonoscopy = "",
722                                 $history_mother = "",
723                                 $history_father = "",
724                                 $history_siblings = "",
725                                 $history_offspring = "",
726                                 $history_spouse = "",
727                                 $relatives_cancer = "",
728                                 $relatives_tuberculosis = "",
729                                 $relatives_diabetes = "",
730                                 $relatives_high_blood_pressure = "",
731                                 $relatives_heart_problems = "",
732                                 $relatives_stroke = "",
733                                 $relatives_epilepsy = "",
734                                 $relatives_mental_illness = "",
735                                 $relatives_suicide = "",
736                                 $cataract_surgery = "",
737                                 $tonsillectomy = "",
738                                 $appendectomy = "",
739                                 $cholecystestomy = "",
740                                 $heart_surgery = "",
741                                 $hysterectomy = "",
742                                 $hernia_repair = "",
743                                 $hip_replacement = "",
744                                 $knee_replacement = "",
745                                 $name_1 = "",
746                                 $value_1 = "",
747                                 $name_2 = "",
748                                 $value_2 = "",
749                                 $additional_history = "",
750                                 $last_ecg = "",
751                                 $last_cardiac_echo = "",
752                                 $last_exam_results = ""
753                                 )
755         return sqlInsert("insert into history_data set
756                 coffee='$coffee',
757                 tobacco='$tobacco',
758                 alcohol='$alcohol',
759                 sleep_patterns='$sleep_patterns',
760                 exercise_patterns='$exercise_patterns',
761                 seatbelt_use='$seatbelt_use',
762                 counseling='$counseling',
763                 hazardous_activities='$hazardous_activities',
764                 last_breast_exam='$last_breast_exam',
765                 last_mammogram='$last_mammogram',
766                 last_gynocological_exam='$last_gynocological_exam',
767                 last_rectal_exam='$last_rectal_exam',
768                 last_prostate_exam='$last_prostate_exam',
769                 last_physical_exam='$last_physical_exam',
770                 last_sigmoidoscopy_colonoscopy='$last_sigmoidoscopy_colonoscopy',
771                 last_ecg='$last_ecg',
772                 last_cardiac_echo='$last_cardiac_echo',
773                 last_exam_results='$last_exam_results',
774                 history_mother='$history_mother',
775                 history_father='$history_father',
776                 history_siblings='$history_siblings',
777                 history_offspring='$history_offspring',
778                 history_spouse='$history_spouse',
779                 relatives_cancer='$relatives_cancer',
780                 relatives_tuberculosis ='$relatives_tuberculosis',
781                 relatives_diabetes='$relatives_diabetes',
782                 relatives_high_blood_pressure='$relatives_high_blood_pressure',
783                 relatives_heart_problems='$relatives_heart_problems',
784                 relatives_stroke='$relatives_stroke',
785                 relatives_epilepsy='$relatives_epilepsy',
786                 relatives_mental_illness='$relatives_mental_illness',
787                 relatives_suicide='$relatives_suicide',
788                 cataract_surgery='$cataract_surgery',
789                 tonsillectomy='$tonsillectomy',
790                 appendectomy='$appendectomy',
791                 cholecystestomy='$cholecystestomy',
792                 heart_surgery='$heart_surgery',
793                 hysterectomy='$hysterectomy',
794                 hernia_repair='$hernia_repair',
795                 hip_replacement='$hip_replacement',
796                 knee_replacement='$knee_replacement',
797                 name_1 = '$name_1',
798                 value_1 = '$value_1',
799                 name_2 = '$name_2',
800                 value_2 = '$value_2',
801                 additional_history = '$additional_history',
802                 date=NOW(),
803                 pid='$pid'
804                 ");
807 function updateHistoryData($pid,$new)
809         $real = getHistoryData($pid);
810         while(list($key, $value) = each ($new))
811                 $real[$key] = $value;
812         $real['date'] = "'+NOW()+'";
813         $real['id'] = "";
815         $sql = "insert into history_data set ";
816         while(list($key, $value) = each($real))
817                 $sql .= $key." = '$value', ";
818         $sql = substr($sql, 0, -2);
821         return sqlInsert($sql);
824 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
825                                 $phone_biz,$email,$pid="")
827         $db = $GLOBALS['adodb']['db'];
828         $customer_info = array();
830         $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
831         $result = $db->Execute($sql);
832         if ($result && !$result->EOF) {
833                 $customer_info['foreign_update'] = true;
834                 $customer_info['foreign_id'] = $result->fields['foreign_id'];
835                 $customer_info['foreign_table'] = $result->fields['foreign_table'];
836         }
838         ///xml rpc code to connect to accounting package and add user to it
839         $customer_info['firstname'] = $fname;
840         $customer_info['lastname'] = $lname;
841         $customer_info['address'] = $street;
842         $customer_info['suburb'] = $city;
843         $customer_info['state'] = $state;
844         $customer_info['postcode'] = $postal_code;
846         //ezybiz wants state as a code rather than abbreviation
847         $customer_info['geo_zone_id'] = "";
848         $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
849         $db = $GLOBALS['adodb']['db'];
850         $result = $db->Execute($sql);
851         if ($result && !$result->EOF) {
852                 $customer_info['geo_zone_id'] = $result->fields['zone_id'];
853         }
855         //ezybiz wants country as a code rather than abbreviation
856         $customer_info['geo_country_id'] = "";
857         $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
858         $db = $GLOBALS['adodb']['db'];
859         $result = $db->Execute($sql);
860         if ($result && !$result->EOF) {
861                 $customer_info['geo_country_id'] = $result->fields['countries_id'];
862         }
865         $customer_info['phone1'] = $phone_home;
866         $customer_info['phone1comment'] = "Home Phone";
867         $customer_info['phone2'] = $phone_biz;
868         $customer_info['phone2comment'] = "Business Phone";
869         $customer_info['email'] = $email;
870         $customer_info['customernumber'] = $pid;
872         $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
873         $ws = new WSWrapper($function);
875         // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
876         if (is_numeric($ws->value)) {
877                 $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
878                 $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
879         }
882 // Returns Date of Birth given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
883 function getPatientAge($dobYMD)
885     $tdyYMD=date("Ymd");
886     $yearDiff = substr($tdyYMD,0,4) - substr($dobYMD,0,4);
887     $ageInMonths = ((substr($tdyYMD,0,4)*12)+substr($tdyYMD,4,2)) -
888                    ((substr($dobYMD,0,4)*12)+substr($dobYMD,4,2));
889     $dayDiff = substr($tdyYMD,6,2) - substr($dobYMD,6,2);
890     if ( $dayDiff < 0 ) {
891         $ageInMonths -= 1;
892     }
893     if ( $ageInMonths > 24 ) {
894         $age = intval($ageInMonths/12);
895     }
896     else  {
897         $age = "$ageInMonths month";
898     }
899     return $age;
902 function dateToDB ($date) 
904         $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
905         return $date;
911 function DBToDate ($date)
913         $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
914         return $date;