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(
9 xl('Restricted Training'),
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"]);
34 function getInsuranceProviders() {
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'];
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
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] . ")";
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"]);
81 function getProviderInfo($providerID = "%", $providers_only = true) {
83 if ($providers_only) {
84 $param1 = "AND authorized=1";
87 if ($providerID == "%") {
90 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
91 "from users where username != '' and active = 1 and id $command '" .
92 mysql_real_escape_string($providerID) . "' " . $param1;
93 $rez = sqlStatement($query);
94 for($iter=0; $row=sqlFetchArray($rez); $iter++)
95 $returnval[$iter]=$row;
97 //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
98 //accessible from $resultval['key']
101 $akeys = array_keys($returnval[0]);
102 foreach($akeys as $key) {
104 $returnval[0][$key] = $returnval[0][$key];
110 //same as above but does not reduce if only 1 row returned
111 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
113 if ($providers_only) {
114 $param1 = "AND authorized=1";
117 if ($providerID == "%") {
120 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
121 "from users where active = 1 and username != '' and id $command '" .
122 mysql_real_escape_string($providerID) . "' " . $param1;
124 $rez = sqlStatement($query);
125 for($iter=0; $row=sqlFetchArray($rez); $iter++)
126 $returnval[$iter]=$row;
131 function getProviderName($providerID) {
132 $pi = getProviderInfo($providerID);
133 if (strlen($pi[0]["lname"]) > 0) {
134 return $pi[0]['fname'] . " " . $pi[0]['lname'];
139 function getProviderId($providerName) {
140 $query = "select id from users where username = '". mysql_real_escape_string($providerName)."'";
141 $rez = sqlStatement($query);
142 for($iter=0; $row=sqlFetchArray($rez); $iter++)
143 $returnval[$iter]=$row;
147 function getEthnoRacials() {
148 $returnval = array("");
149 $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
150 $rez = sqlStatement($sql);
151 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
152 if (($row["ethnoracial"] != "")) {
153 array_push($returnval, $row["ethnoracial"]);
159 function getHistoryData($pid, $given = "*")
161 $sql = "select $given from history_data where pid='$pid' order by date DESC limit 0,1";
162 return sqlQuery($sql);
165 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
166 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
168 $sql = "select $given from insurance_data as insd " .
169 "left join insurance_companies as ic on ic.id = insd.provider " .
170 "where pid = '$pid' and type = '$type' order by date DESC limit 1";
171 return sqlQuery($sql);
174 function getInsuranceDataByDate($pid, $date, $type,
175 $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
176 { // this must take the date in the following manner: YYYY-MM-DD
177 // this function recalls the insurance value that was most recently enterred from the
178 // given date. it will call up most recent records up to and on the date given,
179 // but not records enterred after the given date
180 $sql = "select $given from insurance_data as insd " .
181 "left join insurance_companies as ic on ic.id = provider " .
182 "where pid = '$pid' and date_format(date,'%Y-%m-%d') <= '$date' and " .
183 "type='$type' order by date DESC limit 1";
184 return sqlQuery($sql);
187 function getEmployerData($pid, $given = "*")
189 $sql = "select $given from employer_data where pid='$pid' order by date DESC limit 0,1";
190 return sqlQuery($sql);
193 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")
195 // Allow the last name to be followed by a comma and some part of a first name.
196 // New behavior for searches:
197 // Allows comma alone followed by some part of a first name
198 // If the first letter of either name is capital, searches for name starting
199 // with given substring (the expected behavior). If it is lower case, it
200 // it searches for the substring anywhere in the name. This applies to either
201 // last name or first name or both. The arbitrary limit of 100 results is set
202 // in the sql query below. --Mark Leeds
203 $lname = trim($lname);
205 if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
206 $lname = trim($matches[1]);
207 $fname = trim($matches[2]);
209 $search_for_pieces1 = '';
210 $search_for_pieces2 = '';
211 if ($lname{0} != strtoupper($lname{0})) {$search_for_pieces1 = '%';}
212 if ($fname{0} != strtoupper($fname{0})) {$search_for_pieces2 = '%';}
213 $sql="select $given from patient_data where lname like '"
214 .$search_for_pieces1."$lname%' "
216 .$search_for_pieces2."$fname%' "
217 ."order by $orderby limit 100";
220 $sql .= " limit $start, $limit";
221 $rez = sqlStatement($sql);
223 for($iter=0; $row=sqlFetchArray($rez); $iter++)
224 $returnval[$iter]=$row;
229 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")
231 $sql = "select $given from patient_data where pubpid like '$pid%' " .
235 $sql .= " limit $start, $limit";
236 $rez = sqlStatement($sql);
237 for($iter=0; $row=sqlFetchArray($rez); $iter++)
238 $returnval[$iter]=$row;
243 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")
251 if (strstr($pid,"%"))
254 $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
257 $sql .= " limit $start, $limit";
259 $rez = sqlStatement($sql);
260 for($iter=0; $row=sqlFetchArray($rez); $iter++)
261 $returnval[$iter]=$row;
266 function getPatientName($pid) {
269 $patientData = getPatientPID($pid);
270 if (empty($patientData[0]['lname']))
272 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
276 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
278 $DOB = fixDate($DOB, $DOB);
280 $sql="select $given from patient_data where DOB like '$DOB%' " .
284 $sql .= " limit $start, $limit";
286 $rez = sqlStatement($sql);
287 for($iter=0; $row=sqlFetchArray($rez); $iter++)
288 $returnval[$iter]=$row;
293 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
295 $sql="select $given from patient_data where ss like '$ss%' " .
299 $sql .= " limit $start, $limit";
301 $rez = sqlStatement($sql);
302 for($iter=0; $row=sqlFetchArray($rez); $iter++)
303 $returnval[$iter]=$row;
308 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
310 $sql="select $given from patient_data order by $orderby";
313 $sql .= " limit $start, $limit";
315 $rez = sqlStatement($sql);
316 for($iter=0; $row=sqlFetchArray($rez); $iter++)
317 $returnval[$iter]=$row;
322 //----------------------input functions
323 function newPatientData( $db_id="",
341 $contact_relationship = "",
348 $migrantseasonal = "",
350 $monthly_income = "",
352 $financial_review = "",
365 $drivers_license = "",
370 $DOB = fixDate($DOB);
373 $referral_source = '';
375 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
376 // Check for brain damage:
377 if ($db_id != $rez['id']) {
378 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
379 $rez['id'] . "' to '$db_id' for pid '$pid'";
382 $fitness = $rez['fitness'];
383 $referral_source = $rez['referral_source'];
386 $query = ("replace into patient_data set
395 postal_code='$postal_code',
398 country_code='$country_code',
399 drivers_license='$drivers_license',
401 occupation='$occupation',
402 phone_home='$phone_home',
403 phone_biz='$phone_biz',
404 phone_contact='$phone_contact',
406 contact_relationship='$contact_relationship',
407 referrer='$referrer',
408 referrerID='$referrerID',
410 language='$language',
411 ethnoracial='$ethnoracial',
412 interpretter='$interpretter',
413 migrantseasonal='$migrantseasonal',
414 family_size='$family_size',
415 monthly_income='$monthly_income',
416 homeless='$homeless',
417 financial_review='$financial_review',
420 providerID = '$providerID',
421 genericname1 = '$genericname1',
422 genericval1 = '$genericval1',
423 genericname2 = '$genericname2',
424 genericval2 = '$genericval2',
425 phone_cell = '$phone_cell',
426 pharmacy_id = '$pharmacy_id',
427 hipaa_mail = '$hipaa_mail',
428 hipaa_voice = '$hipaa_voice',
429 hipaa_notice = '$hipaa_notice',
430 hipaa_message = '$hipaa_message',
433 referral_source='$referral_source',
437 $id = sqlInsert($query);
438 $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
440 sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
441 $phone_biz,$email,$pid);
446 // Supported input date formats are:
448 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
450 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
452 function fixDate($date, $default="0000-00-00") {
453 $fixed_date = $default;
455 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
456 $dmy = preg_split("'[/.-]'", $date);
458 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
460 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
461 if ($dmy[2] < 1000) $dmy[2] += 1900;
462 if ($dmy[2] < 1910) $dmy[2] += 100;
464 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
471 function updatePatientData($pid,$new)
473 $real = getPatientData($pid);
474 $new['DOB'] = fixDate($new['DOB']);
475 while(list($key, $value) = each ($new))
476 $real[$key] = $value;
477 $real['date'] = "'+NOW()+'";
480 $sql = "insert into patient_data set ";
481 while(list($key, $value) = each($real))
482 $sql .= $key." = '$value', ";
483 $sql = substr($sql, 0, -2);
486 return sqlInsert($sql);
489 function newEmployerData( $pid,
498 return sqlInsert("insert into employer_data set
501 postal_code='$postal_code',
510 function updateEmployerData($pid,$new)
512 $real = getEmployerData($pid);
513 while(list($key, $value) = each ($new))
514 $real[$key] = $value;
515 $real['date'] = "'+NOW()+'";
518 $sql = "insert into employer_data set ";
519 while(list($key, $value) = each($real))
520 $sql .= $key." = '$value', ";
521 $sql = substr($sql, 0, -2);
524 return sqlInsert($sql);
527 // This updates or adds the given insurance data info, while retaining any
528 // previously added insurance_data rows that should be preserved.
529 // This does not directly support the maintenance of non-current insurance.
531 function newInsuranceData(
538 $subscriber_lname = "",
539 $subscriber_mname = "",
540 $subscriber_fname = "",
541 $subscriber_relationship = "",
543 $subscriber_DOB = "",
544 $subscriber_street = "",
545 $subscriber_postal_code = "",
546 $subscriber_city = "",
547 $subscriber_state = "",
548 $subscriber_country = "",
549 $subscriber_phone = "",
550 $subscriber_employer = "",
551 $subscriber_employer_street = "",
552 $subscriber_employer_city = "",
553 $subscriber_employer_postal_code = "",
554 $subscriber_employer_state = "",
555 $subscriber_employer_country = "",
557 $subscriber_sex = "",
558 $effective_date = "0000-00-00")
560 if (strlen($type) <= 0) return FALSE;
562 // If a bad date was passed, err on the side of caution.
563 $effective_date = fixDate($effective_date, date('Y-m-d'));
565 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
566 "pid = '$pid' AND type = '$type' ORDER BY date DESC");
567 $idrow = sqlFetchArray($idres);
569 // Replace the most recent entry in any of the following cases:
570 // * Its effective date is >= this effective date.
571 // * It is the first entry and it has no (insurance) provider.
572 // * There is no encounter that is earlier than the new effective date but
573 // on or after the old effective date.
574 // Otherwise insert a new entry.
578 if (strcmp($idrow['date'], $effective_date) > 0) {
582 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
586 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
587 "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
588 "date >= '" . $idrow['date'] . " 00:00:00'");
589 if ($ferow['count'] == 0) $replace = true;
596 // TBD: This is a bit dangerous in that a typo in entering the effective
597 // date can wipe out previous insurance history. So we want some data
598 // entry validation somewhere.
599 sqlStatement("DELETE FROM insurance_data WHERE " .
600 "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
601 "id != " . $idrow['id']);
604 $data['type'] = $type;
605 $data['provider'] = $provider;
606 $data['policy_number'] = $policy_number;
607 $data['group_number'] = $group_number;
608 $data['plan_name'] = $plan_name;
609 $data['subscriber_lname'] = $subscriber_lname;
610 $data['subscriber_mname'] = $subscriber_mname;
611 $data['subscriber_fname'] = $subscriber_fname;
612 $data['subscriber_relationship'] = $subscriber_relationship;
613 $data['subscriber_ss'] = $subscriber_ss;
614 $data['subscriber_DOB'] = $subscriber_DOB;
615 $data['subscriber_street'] = $subscriber_street;
616 $data['subscriber_postal_code'] = $subscriber_postal_code;
617 $data['subscriber_city'] = $subscriber_city;
618 $data['subscriber_state'] = $subscriber_state;
619 $data['subscriber_country'] = $subscriber_country;
620 $data['subscriber_phone'] = $subscriber_phone;
621 $data['subscriber_employer'] = $subscriber_employer;
622 $data['subscriber_employer_city'] = $subscriber_employer_city;
623 $data['subscriber_employer_street'] = $subscriber_employer_street;
624 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
625 $data['subscriber_employer_state'] = $subscriber_employer_state;
626 $data['subscriber_employer_country'] = $subscriber_employer_country;
627 $data['copay'] = $copay;
628 $data['subscriber_sex'] = $subscriber_sex;
630 $data['date'] = $effective_date;
631 updateInsuranceData($idrow['id'], $data);
635 return sqlInsert("INSERT INTO insurance_data SET
637 provider = '$provider',
638 policy_number = '$policy_number',
639 group_number = '$group_number',
640 plan_name = '$plan_name',
641 subscriber_lname = '$subscriber_lname',
642 subscriber_mname = '$subscriber_mname',
643 subscriber_fname = '$subscriber_fname',
644 subscriber_relationship = '$subscriber_relationship',
645 subscriber_ss = '$subscriber_ss',
646 subscriber_DOB = '$subscriber_DOB',
647 subscriber_street = '$subscriber_street',
648 subscriber_postal_code = '$subscriber_postal_code',
649 subscriber_city = '$subscriber_city',
650 subscriber_state = '$subscriber_state',
651 subscriber_country = '$subscriber_country',
652 subscriber_phone = '$subscriber_phone',
653 subscriber_employer = '$subscriber_employer',
654 subscriber_employer_city = '$subscriber_employer_city',
655 subscriber_employer_street = '$subscriber_employer_street',
656 subscriber_employer_postal_code = '$subscriber_employer_postal_code',
657 subscriber_employer_state = '$subscriber_employer_state',
658 subscriber_employer_country = '$subscriber_employer_country',
660 subscriber_sex = '$subscriber_sex',
662 date = '$effective_date'
667 // This is used internally only.
668 function updateInsuranceData($id, $new)
670 $fields = sqlListFields("insurance_data");
673 while(list($key, $value) = each ($new)) {
674 if (in_array($key, $fields)) {
679 $sql = "UPDATE insurance_data SET ";
680 while(list($key, $value) = each($use))
681 $sql .= $key . " = '$value', ";
682 $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
687 function newHistoryData($pid, $new=false) {
688 $sql = "insert into history_data set pid = '$pid', date = NOW()";
690 while(list($key, $value) = each($new)) {
691 if (!get_magic_quotes_gpc()) $value = addslashes($value);
692 $sql .= ", $key = '$value'";
695 return sqlInsert($sql);
698 function updateHistoryData($pid,$new)
700 $real = getHistoryData($pid);
701 while(list($key, $value) = each ($new))
702 $real[$key] = $value;
703 $real['date'] = "'+NOW()+'";
706 $sql = "insert into history_data set ";
707 while(list($key, $value) = each($real))
708 $sql .= $key." = '$value', ";
709 $sql = substr($sql, 0, -2);
712 return sqlInsert($sql);
715 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
716 $phone_biz,$email,$pid="")
718 $db = $GLOBALS['adodb']['db'];
719 $customer_info = array();
721 $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
722 $result = $db->Execute($sql);
723 if ($result && !$result->EOF) {
724 $customer_info['foreign_update'] = true;
725 $customer_info['foreign_id'] = $result->fields['foreign_id'];
726 $customer_info['foreign_table'] = $result->fields['foreign_table'];
729 ///xml rpc code to connect to accounting package and add user to it
730 $customer_info['firstname'] = $fname;
731 $customer_info['lastname'] = $lname;
732 $customer_info['address'] = $street;
733 $customer_info['suburb'] = $city;
734 $customer_info['state'] = $state;
735 $customer_info['postcode'] = $postal_code;
737 //ezybiz wants state as a code rather than abbreviation
738 $customer_info['geo_zone_id'] = "";
739 $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
740 $db = $GLOBALS['adodb']['db'];
741 $result = $db->Execute($sql);
742 if ($result && !$result->EOF) {
743 $customer_info['geo_zone_id'] = $result->fields['zone_id'];
746 //ezybiz wants country as a code rather than abbreviation
747 $customer_info['geo_country_id'] = "";
748 $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
749 $db = $GLOBALS['adodb']['db'];
750 $result = $db->Execute($sql);
751 if ($result && !$result->EOF) {
752 $customer_info['geo_country_id'] = $result->fields['countries_id'];
756 $customer_info['phone1'] = $phone_home;
757 $customer_info['phone1comment'] = "Home Phone";
758 $customer_info['phone2'] = $phone_biz;
759 $customer_info['phone2comment'] = "Business Phone";
760 $customer_info['email'] = $email;
761 $customer_info['customernumber'] = $pid;
763 $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
764 $ws = new WSWrapper($function);
766 // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
767 if (is_numeric($ws->value)) {
768 $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
769 $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
773 // Returns Date of Birth given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
774 function getPatientAge($dobYMD)
777 $yearDiff = substr($tdyYMD,0,4) - substr($dobYMD,0,4);
778 $ageInMonths = ((substr($tdyYMD,0,4)*12)+substr($tdyYMD,4,2)) -
779 ((substr($dobYMD,0,4)*12)+substr($dobYMD,4,2));
780 $dayDiff = substr($tdyYMD,6,2) - substr($dobYMD,6,2);
781 if ( $dayDiff < 0 ) {
784 if ( $ageInMonths > 24 ) {
785 $age = intval($ageInMonths/12);
788 $age = "$ageInMonths month";
793 function dateToDB ($date)
795 $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
799 function DBToDate ($date)
801 $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);