css file for four pane rx printing.
[openemr.git] / library / patient.inc
blobcb93bbfe66ebe70151c849842bc729981f33fb9c
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;
96         
97         if ( $first == 'first') {
98             return $ret[0]['id'];
99         } else {
100             return $ret;
101         }
104 function getProviderInfo($providerID = "%", $providers_only = true) {
105         $param1 = "";
106         if ($providers_only) {
107                 $param1 = "AND authorized=1";
108         }
109         $command = "=";
110         if ($providerID == "%") {
111                 $command = "like";
112         }
113         $query = "select distinct id, username, lname, fname, authorized, info, facility " .
114                 "from users where username != '' and active = 1 and id $command '" .
115                 mysql_real_escape_string($providerID) . "' " . $param1;
116         $rez = sqlStatement($query);
117         for($iter=0; $row=sqlFetchArray($rez); $iter++)
118                 $returnval[$iter]=$row;
120         //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
121         //accessible from $resultval['key']
123         if($iter==1) {
124                 $akeys = array_keys($returnval[0]);
125                 foreach($akeys as $key) {
127                         $returnval[0][$key] = $returnval[0][$key];
128                 }
129         }
130         return $returnval;
133 //same as above but does not reduce if only 1 row returned
134 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
135         $param1 = "";
136         if ($providers_only) {
137                 $param1 = "AND authorized=1";
138         }
139         $command = "=";
140         if ($providerID == "%") {
141                 $command = "like";
142         }
143         $query = "select distinct id, username, lname, fname, authorized, info, facility " .
144                 "from users where active = 1 and username != '' and id $command '" .
145                 mysql_real_escape_string($providerID) . "' " . $param1;
147         $rez = sqlStatement($query);
148         for($iter=0; $row=sqlFetchArray($rez); $iter++)
149                 $returnval[$iter]=$row;
151         return $returnval;
154 function getProviderName($providerID) {
155         $pi = getProviderInfo($providerID);
156         if (strlen($pi[0]["lname"]) > 0) {
157                 return $pi[0]['fname'] . " " . $pi[0]['lname'];
158         }
159         return "";
162 function getProviderId($providerName) {
163         $query = "select id from users where username = '". mysql_real_escape_string($providerName)."'";
164         $rez = sqlStatement($query);
165         for($iter=0; $row=sqlFetchArray($rez); $iter++)
166                 $returnval[$iter]=$row;
167         return $returnval;
170 function getEthnoRacials() {
171         $returnval = array("");
172         $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
173         $rez = sqlStatement($sql);
174         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
175                 if (($row["ethnoracial"] != "")) {
176                         array_push($returnval, $row["ethnoracial"]);
177                 }
178         }
179         return $returnval;
182 function getHistoryData($pid, $given = "*")
184         $sql = "select $given from history_data where pid='$pid' order by date DESC limit 0,1";
185         return sqlQuery($sql);
188 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
189 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
191   $sql = "select $given from insurance_data as insd " .
192     "left join insurance_companies as ic on ic.id = insd.provider " .
193     "where pid = '$pid' and type = '$type' order by date DESC limit 1";
194   return sqlQuery($sql);
197 function getInsuranceDataByDate($pid, $date, $type,
198   $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
199 { // this must take the date in the following manner: YYYY-MM-DD
200   // this function recalls the insurance value that was most recently enterred from the
201   // given date. it will call up most recent records up to and on the date given,
202   // but not records enterred after the given date
203   $sql = "select $given from insurance_data as insd " .
204     "left join insurance_companies as ic on ic.id = provider " .
205     "where pid = '$pid' and date_format(date,'%Y-%m-%d') <= '$date' and " .
206     "type='$type' order by date DESC limit 1";
207   return sqlQuery($sql);
210 function getEmployerData($pid, $given = "*")
212         $sql = "select $given from employer_data where pid='$pid' order by date DESC limit 0,1";
213         return sqlQuery($sql);
216 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")
218         // Allow the last name to be followed by a comma and some part of a first name.
219         // New behavior for searches:
220         // Allows comma alone followed by some part of a first name
221         // If the first letter of either name is capital, searches for name starting
222         // with given substring (the expected behavior).  If it is lower case, it
223         // it searches for the substring anywhere in the name.  This applies to either
224         // last name or first name or both.  The arbitrary limit of 100 results is set
225         // in the sql query below. --Mark Leeds
226         $lname = trim($lname);
227         $fname = '';
228         if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
229                 $lname = trim($matches[1]);
230                 $fname = trim($matches[2]);
231         }
232         $search_for_pieces1 = '';
233         $search_for_pieces2 = '';
234         if ($lname{0} != strtoupper($lname{0})) {$search_for_pieces1 = '%';}
235         if ($fname{0} != strtoupper($fname{0})) {$search_for_pieces2 = '%';}
236         $sql="select $given from patient_data where lname like '"
237                 .$search_for_pieces1."$lname%' "
238                 ."and fname like '"
239                 .$search_for_pieces2."$fname%' "
240                 ."order by $orderby limit 100";
242         if ($limit != "all")
243                 $sql .= " limit $start, $limit";
244         $rez = sqlStatement($sql);
246         for($iter=0; $row=sqlFetchArray($rez); $iter++)
247                 $returnval[$iter]=$row;
249         return $returnval;
252 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")
254         $sql = "select $given from patient_data where pubpid like '$pid%' " .
255                 "order by $orderby";
257         if ($limit != "all")
258                 $sql .= " limit $start, $limit";
259         $rez = sqlStatement($sql);
260         for($iter=0; $row=sqlFetchArray($rez); $iter++)
261                 $returnval[$iter]=$row;
263         return $returnval;
266 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")
268         $command = "=";
269         if ($pid == -1)
270                 $pid = "%";
271         elseif (empty($pid))
272                 $pid = "NULL";
274         if (strstr($pid,"%"))
275                 $command = "like";
277         $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
279         if ($limit != "all")
280                 $sql .= " limit $start, $limit";
282         $rez = sqlStatement($sql);
283         for($iter=0; $row=sqlFetchArray($rez); $iter++)
284                 $returnval[$iter]=$row;
286         return $returnval;
289 function getPatientName($pid) {
290         if (empty($pid))
291                 return "";
292         $patientData = getPatientPID($pid);
293         if (empty($patientData[0]['lname']))
294                 return "";
295         $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
296         return $patientName;
299 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
301         $DOB = fixDate($DOB, $DOB);
303         $sql="select $given from patient_data where DOB like '$DOB%' " .
304                 "order by $orderby";
306         if ($limit != "all")
307                 $sql .= " limit $start, $limit";
309         $rez = sqlStatement($sql);
310         for($iter=0; $row=sqlFetchArray($rez); $iter++)
311                 $returnval[$iter]=$row;
313         return $returnval;
316 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
318         $sql="select $given from patient_data where ss like '$ss%' " .
319                 "order by $orderby";
321         if ($limit != "all")
322                 $sql .= " limit $start, $limit";
324         $rez = sqlStatement($sql);
325         for($iter=0; $row=sqlFetchArray($rez); $iter++)
326                 $returnval[$iter]=$row;
328         return $returnval;
331 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
333         $sql="select $given from patient_data order by $orderby";
335         if ($limit != "all")
336                 $sql .= " limit $start, $limit";
338         $rez = sqlStatement($sql);
339         for($iter=0; $row=sqlFetchArray($rez); $iter++)
340                 $returnval[$iter]=$row;
342         return $returnval;
345 //----------------------input functions
346 function newPatientData(        $db_id="",
347                                 $title = "",
348                                 $fname = "",
349                                 $lname = "",
350                                 $mname = "",
351                                 $sex = "",
352                                 $DOB = "",
353                                 $street = "",
354                                 $postal_code = "",
355                                 $city = "",
356                                 $state = "",
357                                 $country_code = "",
358                                 $ss = "",
359                                 $occupation = "",
360                                 $phone_home = "",
361                                 $phone_biz = "",
362                                 $phone_contact = "",
363                                 $status = "",
364                                 $contact_relationship = "",
365                                 $referrer = "",
366                                 $referrerID = "",
367                                 $email = "",
368                                 $language = "",
369                                 $ethnoracial = "",
370                                 $interpretter = "",
371                                 $migrantseasonal = "",
372                                 $family_size = "",
373                                 $monthly_income = "",
374                                 $homeless = "",
375                                 $financial_review = "",
376                                 $pubpid = "",
377                                 $pid = "MAX(pid)+1",
378                                 $providerID = "",
379                                 $genericname1 = "",
380                                 $genericval1 = "",
381                                 $genericname2 = "",
382                                 $genericval2 = "",
383                                 $phone_cell = "",
384                                 $hipaa_mail = "",
385                                 $hipaa_voice = "",
386                                 $squad = 0,
387                                 $pharmacy_id = 0,
388                                 $drivers_license = "",
389                                 $hipaa_notice = "",
390                                 $hipaa_message = ""
391                         )
393         $DOB = fixDate($DOB);
395         $fitness = 0;
396         $referral_source = '';
397         if ($pid) {
398                 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
399                 // Check for brain damage:
400                 if ($db_id != $rez['id']) {
401                         $errmsg = "Internal error: Attempt to change patient_data.id from '" .
402                           $rez['id'] . "' to '$db_id' for pid '$pid'";
403                         die($errmsg);
404                 }
405                 $fitness = $rez['fitness'];
406                 $referral_source = $rez['referral_source'];
407         }
409         $query = ("replace into patient_data set
410                 id='$db_id',
411                 title='$title',
412                 fname='$fname',
413                 lname='$lname',
414                 mname='$mname',
415                 sex='$sex',
416                 DOB='$DOB',
417                 street='$street',
418                 postal_code='$postal_code',
419                 city='$city',
420                 state='$state',
421                 country_code='$country_code',
422                 drivers_license='$drivers_license',
423                 ss='$ss',
424                 occupation='$occupation',
425                 phone_home='$phone_home',
426                 phone_biz='$phone_biz',
427                 phone_contact='$phone_contact',
428                 status='$status',
429                 contact_relationship='$contact_relationship',
430                 referrer='$referrer',
431                 referrerID='$referrerID',
432                 email='$email',
433                 language='$language',
434                 ethnoracial='$ethnoracial',
435                 interpretter='$interpretter',
436                 migrantseasonal='$migrantseasonal',
437                 family_size='$family_size',
438                 monthly_income='$monthly_income',
439                 homeless='$homeless',
440                 financial_review='$financial_review',
441                 pubpid='$pubpid',
442                 pid = $pid,
443                 providerID = '$providerID',
444                 genericname1 = '$genericname1',
445                 genericval1 = '$genericval1',
446                 genericname2 = '$genericname2',
447                 genericval2 = '$genericval2',
448                 phone_cell = '$phone_cell',
449                 pharmacy_id = '$pharmacy_id',
450                 hipaa_mail = '$hipaa_mail',
451                 hipaa_voice = '$hipaa_voice',
452                 hipaa_notice = '$hipaa_notice',
453                 hipaa_message = '$hipaa_message',
454                 squad = '$squad',
455                 fitness='$fitness',
456                 referral_source='$referral_source',
457                 date=NOW()
458                         ");
460         $id = sqlInsert($query);
461         $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
463         sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
464                                 $phone_biz,$phone_cell,$email,$pid);
466         return $foo['pid'];
469 // Supported input date formats are:
470 //   mm/dd/yyyy
471 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
472 //   yyyy/mm/dd
473 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
475 function fixDate($date, $default="0000-00-00") {
476     $fixed_date = $default;
477     $date = trim($date);
478     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
479         $dmy = preg_split("'[/.-]'", $date);
480         if ($dmy[0] > 99) {
481             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
482         } else {
483             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
484               if ($dmy[2] < 1000) $dmy[2] += 1900;
485               if ($dmy[2] < 1910) $dmy[2] += 100;
486             }
487             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
488         }
489     }
491     return $fixed_date;
494 function updatePatientData($pid,$new)
496   /*******************************************************************
497         $real = getPatientData($pid);
498         $new['DOB'] = fixDate($new['DOB']);
499         while(list($key, $value) = each ($new))
500                 $real[$key] = $value;
501         $real['date'] = "'+NOW()+'";
502         $real['id'] = "";
503         $sql = "insert into patient_data set ";
504         while(list($key, $value) = each($real))
505                 $sql .= $key." = '$value', ";
506         $sql = substr($sql, 0, -2);
507         return sqlInsert($sql);
508   *******************************************************************/
510   // The above was broken, though seems intent to insert a new patient_data
511   // row for each update.  A good idea, but nothing is doing that yet so
512   // the code below does not yet attempt it.
514   $new['DOB'] = fixDate($new['DOB']);
515   $db_id = $new['id'];
517   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
518   // Check for brain damage:
519   if ($pid != $rez['pid']) {
520     $errmsg = "Internal error: Attempt to change patient data with pid = '" .
521       $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
522     die($errmsg);
523   }
524   $sql = "UPDATE patient_data SET date = NOW()";
525   foreach ($new as $key => $value) {
526     $sql .= ", $key = '$value'";
527   }
528   $sql .= " WHERE id = '$db_id'";
529   $id = sqlInsert($sql);
531   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
532     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
533     $rez['phone_cell'],$rez['email'],$rez['pid']);
535   return $id;
538 function newEmployerData(       $pid,
539                                 $name = "",
540                                 $street = "",
541                                 $postal_code = "",
542                                 $city = "",
543                                 $state = "",
544                                 $country = ""
545                         )
547         return sqlInsert("insert into employer_data set
548                 name='$name',
549                 street='$street',
550                 postal_code='$postal_code',
551                 city='$city',
552                 state='$state',
553                 country='$country',
554                 pid='$pid',
555                 date=NOW()
556                 ");
559 function updateEmployerData($pid,$new)
561         $real = getEmployerData($pid);
562         while(list($key, $value) = each ($new))
563                 $real[$key] = $value;
564         $real['date'] = "'+NOW()+'";
565         $real['id'] = "";
567         $sql = "insert into employer_data set ";
568         while(list($key, $value) = each($real))
569                 $sql .= $key." = '$value', ";
570         $sql = substr($sql, 0, -2);
573         return sqlInsert($sql);
576 // This updates or adds the given insurance data info, while retaining any
577 // previously added insurance_data rows that should be preserved.
578 // This does not directly support the maintenance of non-current insurance.
580 function newInsuranceData(
581   $pid,
582   $type = "",
583   $provider = "",
584   $policy_number = "",
585   $group_number = "",
586   $plan_name = "",
587   $subscriber_lname = "",
588   $subscriber_mname = "",
589   $subscriber_fname = "",
590   $subscriber_relationship = "",
591   $subscriber_ss = "",
592   $subscriber_DOB = "",
593   $subscriber_street = "",
594   $subscriber_postal_code = "",
595   $subscriber_city = "",
596   $subscriber_state = "",
597   $subscriber_country = "",
598   $subscriber_phone = "",
599   $subscriber_employer = "",
600   $subscriber_employer_street = "",
601   $subscriber_employer_city = "",
602   $subscriber_employer_postal_code = "",
603   $subscriber_employer_state = "",
604   $subscriber_employer_country = "",
605   $copay = "",
606   $subscriber_sex = "",
607   $effective_date = "0000-00-00")
609   if (strlen($type) <= 0) return FALSE;
611   // If a bad date was passed, err on the side of caution.
612   $effective_date = fixDate($effective_date, date('Y-m-d'));
614   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
615     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
616   $idrow = sqlFetchArray($idres);
618   // Replace the most recent entry in any of the following cases:
619   // * Its effective date is >= this effective date.
620   // * It is the first entry and it has no (insurance) provider.
621   // * There is no encounter that is earlier than the new effective date but
622   //   on or after the old effective date.
623   // Otherwise insert a new entry.
625   $replace = false;
626   if ($idrow) {
627     if (strcmp($idrow['date'], $effective_date) > 0) {
628       $replace = true;
629     }
630     else {
631       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
632         $replace = true;
633       }
634       else {
635         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
636           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
637           "date >= '" . $idrow['date'] . " 00:00:00'");
638         if ($ferow['count'] == 0) $replace = true;
639       }
640     }
641   }
643   if ($replace) {
645     // TBD: This is a bit dangerous in that a typo in entering the effective
646     // date can wipe out previous insurance history.  So we want some data
647     // entry validation somewhere.
648     sqlStatement("DELETE FROM insurance_data WHERE " .
649       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
650       "id != " . $idrow['id']);
652     $data = array();
653     $data['type'] = $type;
654     $data['provider'] = $provider;
655     $data['policy_number'] = $policy_number;
656     $data['group_number'] = $group_number;
657     $data['plan_name'] = $plan_name;
658     $data['subscriber_lname'] = $subscriber_lname;
659     $data['subscriber_mname'] = $subscriber_mname;
660     $data['subscriber_fname'] = $subscriber_fname;
661     $data['subscriber_relationship'] = $subscriber_relationship;
662     $data['subscriber_ss'] = $subscriber_ss;
663     $data['subscriber_DOB'] = $subscriber_DOB;
664     $data['subscriber_street'] = $subscriber_street;
665     $data['subscriber_postal_code'] = $subscriber_postal_code;
666     $data['subscriber_city'] = $subscriber_city;
667     $data['subscriber_state'] = $subscriber_state;
668     $data['subscriber_country'] = $subscriber_country;
669     $data['subscriber_phone'] = $subscriber_phone;
670     $data['subscriber_employer'] = $subscriber_employer;
671     $data['subscriber_employer_city'] = $subscriber_employer_city;
672     $data['subscriber_employer_street'] = $subscriber_employer_street;
673     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
674     $data['subscriber_employer_state'] = $subscriber_employer_state;
675     $data['subscriber_employer_country'] = $subscriber_employer_country;
676     $data['copay'] = $copay;
677     $data['subscriber_sex'] = $subscriber_sex;
678     $data['pid'] = $pid;
679     $data['date'] = $effective_date;
680     updateInsuranceData($idrow['id'], $data);
681     return $idrow['id'];
682   }
683   else {
684     return sqlInsert("INSERT INTO insurance_data SET
685       type = '$type',
686       provider = '$provider',
687       policy_number = '$policy_number',
688       group_number = '$group_number',
689       plan_name = '$plan_name',
690       subscriber_lname = '$subscriber_lname',
691       subscriber_mname = '$subscriber_mname',
692       subscriber_fname = '$subscriber_fname',
693       subscriber_relationship = '$subscriber_relationship',
694       subscriber_ss = '$subscriber_ss',
695       subscriber_DOB = '$subscriber_DOB',
696       subscriber_street = '$subscriber_street',
697       subscriber_postal_code = '$subscriber_postal_code',
698       subscriber_city = '$subscriber_city',
699       subscriber_state = '$subscriber_state',
700       subscriber_country = '$subscriber_country',
701       subscriber_phone = '$subscriber_phone',
702       subscriber_employer = '$subscriber_employer',
703       subscriber_employer_city = '$subscriber_employer_city',
704       subscriber_employer_street = '$subscriber_employer_street',
705       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
706       subscriber_employer_state = '$subscriber_employer_state',
707       subscriber_employer_country = '$subscriber_employer_country',
708       copay = '$copay',
709       subscriber_sex = '$subscriber_sex',
710       pid = '$pid',
711       date = '$effective_date'
712     ");
713   }
716 // This is used internally only.
717 function updateInsuranceData($id, $new)
719   $fields = sqlListFields("insurance_data");
720   $use = array();
722   while(list($key, $value) = each ($new)) {
723     if (in_array($key, $fields)) {
724       $use[$key] = $value;
725     }
726   }
728   $sql = "UPDATE insurance_data SET ";
729   while(list($key, $value) = each($use))
730     $sql .= $key . " = '$value', ";
731   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
733   sqlStatement($sql);
736 function newHistoryData($pid, $new=false) {
737   $sql = "insert into history_data set pid = '$pid', date = NOW()";
738   if ($new) {
739     while(list($key, $value) = each($new)) {
740       if (!get_magic_quotes_gpc()) $value = addslashes($value);
741       $sql .= ", $key = '$value'";
742     }
743   }
744   return sqlInsert($sql);
747 function updateHistoryData($pid,$new)
749         $real = getHistoryData($pid);
750         while(list($key, $value) = each ($new))
751                 $real[$key] = $value;
752         $real['date'] = "'+NOW()+'";
753         $real['id'] = "";
755         $sql = "insert into history_data set ";
756         while(list($key, $value) = each($real))
757                 $sql .= $key." = '$value', ";
758         $sql = substr($sql, 0, -2);
761         return sqlInsert($sql);
764 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
765                                 $phone_biz,$phone_cell,$email,$pid="")
767         $db = $GLOBALS['adodb']['db'];
768         $customer_info = array();
770         $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
771         $result = $db->Execute($sql);
772         if ($result && !$result->EOF) {
773                 $customer_info['foreign_update'] = true;
774                 $customer_info['foreign_id'] = $result->fields['foreign_id'];
775                 $customer_info['foreign_table'] = $result->fields['foreign_table'];
776         }
778         ///xml rpc code to connect to accounting package and add user to it
779         $customer_info['firstname'] = $fname;
780         $customer_info['lastname'] = $lname;
781         $customer_info['address'] = $street;
782         $customer_info['suburb'] = $city;
783         $customer_info['state'] = $state;
784         $customer_info['postcode'] = $postal_code;
786         //ezybiz wants state as a code rather than abbreviation
787         $customer_info['geo_zone_id'] = "";
788         $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
789         $db = $GLOBALS['adodb']['db'];
790         $result = $db->Execute($sql);
791         if ($result && !$result->EOF) {
792                 $customer_info['geo_zone_id'] = $result->fields['zone_id'];
793         }
795         //ezybiz wants country as a code rather than abbreviation
796         $customer_info['geo_country_id'] = "";
797         $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
798         $db = $GLOBALS['adodb']['db'];
799         $result = $db->Execute($sql);
800         if ($result && !$result->EOF) {
801                 $customer_info['geo_country_id'] = $result->fields['countries_id'];
802         }
804         $customer_info['phone1'] = $phone_home;
805         $customer_info['phone1comment'] = "Home Phone";
806         $customer_info['phone2'] = $phone_biz;
807         $customer_info['phone2comment'] = "Business Phone";
808   $customer_info['phone3'] = $phone_cell;
809   $customer_info['phone3comment'] = "Cell Phone";
810         $customer_info['email'] = $email;
811         $customer_info['customernumber'] = $pid;
813         $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
814         $ws = new WSWrapper($function);
816         // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
817         if (is_numeric($ws->value)) {
818                 $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
819                 $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
820         }
823 // Returns Date of Birth given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
824 function getPatientAge($dobYMD)
826     $tdyYMD=date("Ymd");
827     $yearDiff = substr($tdyYMD,0,4) - substr($dobYMD,0,4);
828     $ageInMonths = ((substr($tdyYMD,0,4)*12)+substr($tdyYMD,4,2)) -
829                    ((substr($dobYMD,0,4)*12)+substr($dobYMD,4,2));
830     $dayDiff = substr($tdyYMD,6,2) - substr($dobYMD,6,2);
831     if ( $dayDiff < 0 ) {
832         $ageInMonths -= 1;
833     }
834     if ( $ageInMonths > 24 ) {
835         $age = intval($ageInMonths/12);
836     }
837     else  {
838         $age = "$ageInMonths month";
839     }
840     return $age;
843 function dateToDB ($date) 
845         $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
846         return $date;
849 function DBToDate ($date)
851         $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
852         return $date;