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 // ----------------------------------------------------------------------------
83 * GET ADDITIONAL INFORMATIONS
87 * @param $pid - patient id
90 function getPatientDataNL($pid) {
91 mysql_query("SET NAMES 'utf8'");
92 $sql = "SELECT * FROM patient_data_NL WHERE pdn_id = '$pid'";
93 return sqlQuery($sql);
100 returns all facilities or just the id for the first one
101 (FACILITY FILTERING (lemonsoftware))
103 @param string - if 'first' return first facility ordered by id
104 @return array | int for 'first' case
106 function getFacilities($first = '') {
107 $r = sqlStatement("SELECT * FROM facility ORDER BY id");
109 while ( $row = sqlFetchArray($r) ) {
113 if ( $first == 'first') {
114 return $ret[0]['id'];
121 GET SERVICE FACILITIES
123 returns all service_location facilities or just the id for the first one
124 (FACILITY FILTERING (CHEMED))
126 @param string - if 'first' return first facility ordered by id
127 @return array | int for 'first' case
129 function getServiceFacilities($first = '') {
130 $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
132 while ( $row = sqlFetchArray($r) ) {
136 if ( $first == 'first') {
137 return $ret[0]['id'];
143 //(CHEMED) facility filter
144 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
146 if ($providers_only) {
147 $param1 = " AND authorized=1 ";
150 //--------------------------------
151 //(CHEMED) facility filter
154 $param2 = " AND facility_id = $facility ";
156 //--------------------------------
159 if ($providerID == "%") {
162 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
163 "from users where username != '' and active = 1 and id $command '" .
164 mysql_real_escape_string($providerID) . "' " . $param1 . $param2;
165 $rez = sqlStatement($query);
166 for($iter=0; $row=sqlFetchArray($rez); $iter++)
167 $returnval[$iter]=$row;
169 //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
170 //accessible from $resultval['key']
173 $akeys = array_keys($returnval[0]);
174 foreach($akeys as $key) {
176 $returnval[0][$key] = $returnval[0][$key];
182 //same as above but does not reduce if only 1 row returned
183 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
185 if ($providers_only) {
186 $param1 = "AND authorized=1";
189 if ($providerID == "%") {
192 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
193 "from users where active = 1 and username != '' and id $command '" .
194 mysql_real_escape_string($providerID) . "' " . $param1;
196 $rez = sqlStatement($query);
197 for($iter=0; $row=sqlFetchArray($rez); $iter++)
198 $returnval[$iter]=$row;
203 function getProviderName($providerID) {
204 $pi = getProviderInfo($providerID);
205 if (strlen($pi[0]["lname"]) > 0) {
206 return $pi[0]['fname'] . " " . $pi[0]['lname'];
211 function getProviderId($providerName) {
212 $query = "select id from users where username = '". mysql_real_escape_string($providerName)."'";
213 $rez = sqlStatement($query);
214 for($iter=0; $row=sqlFetchArray($rez); $iter++)
215 $returnval[$iter]=$row;
219 function getEthnoRacials() {
220 $returnval = array("");
221 $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
222 $rez = sqlStatement($sql);
223 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
224 if (($row["ethnoracial"] != "")) {
225 array_push($returnval, $row["ethnoracial"]);
231 function getHistoryData($pid, $given = "*")
233 $sql = "select $given from history_data where pid='$pid' order by date DESC limit 0,1";
234 return sqlQuery($sql);
237 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
238 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
240 $sql = "select $given from insurance_data as insd " .
241 "left join insurance_companies as ic on ic.id = insd.provider " .
242 "where pid = '$pid' and type = '$type' order by date DESC limit 1";
243 return sqlQuery($sql);
246 function getInsuranceDataByDate($pid, $date, $type,
247 $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
248 { // this must take the date in the following manner: YYYY-MM-DD
249 // this function recalls the insurance value that was most recently enterred from the
250 // given date. it will call up most recent records up to and on the date given,
251 // but not records enterred after the given date
252 $sql = "select $given from insurance_data as insd " .
253 "left join insurance_companies as ic on ic.id = provider " .
254 "where pid = '$pid' and date_format(date,'%Y-%m-%d') <= '$date' and " .
255 "type='$type' order by date DESC limit 1";
256 return sqlQuery($sql);
259 function getEmployerData($pid, $given = "*")
261 $sql = "select $given from employer_data where pid='$pid' order by date DESC limit 0,1";
262 return sqlQuery($sql);
265 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")
267 // Allow the last name to be followed by a comma and some part of a first name.
268 // New behavior for searches:
269 // Allows comma alone followed by some part of a first name
270 // If the first letter of either name is capital, searches for name starting
271 // with given substring (the expected behavior). If it is lower case, it
272 // it searches for the substring anywhere in the name. This applies to either
273 // last name or first name or both. The arbitrary limit of 100 results is set
274 // in the sql query below. --Mark Leeds
275 $lname = trim($lname);
277 if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
278 $lname = trim($matches[1]);
279 $fname = trim($matches[2]);
281 $search_for_pieces1 = '';
282 $search_for_pieces2 = '';
283 if ($lname{0} != strtoupper($lname{0})) {$search_for_pieces1 = '%';}
284 if ($fname{0} != strtoupper($fname{0})) {$search_for_pieces2 = '%';}
285 $sql="select $given from patient_data where lname like '"
286 .$search_for_pieces1."$lname%' "
288 .$search_for_pieces2."$fname%' "
289 ."order by $orderby ";
291 if ($limit != "all") $sql .= " limit $start, $limit";
293 $rez = sqlStatement($sql);
295 for($iter=0; $row=sqlFetchArray($rez); $iter++)
296 $returnval[$iter]=$row;
301 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")
303 $sql = "select $given from patient_data where pubpid like '$pid%' " .
307 $sql .= " limit $start, $limit";
308 $rez = sqlStatement($sql);
309 for($iter=0; $row=sqlFetchArray($rez); $iter++)
310 $returnval[$iter]=$row;
315 // return a collection of Patient PIDs
316 // new arg style by JRM March 2008
317 // orig function getPatientPID($pid = "%", $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
318 function getPatientPID($args)
321 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
322 $orderby = "lname ASC, fname ASC";
326 // alter default values if defined in the passed in args
327 if (isset($args['pid'])) { $pid = $args['pid']; }
328 if (isset($args['given'])) { $given = $args['given']; }
329 if (isset($args['orderby'])) { $orderby = $args['orderby']; }
330 if (isset($args['limit'])) { $limit = $args['limit']; }
331 if (isset($args['start'])) { $start = $args['start']; }
334 if ($pid == -1) $pid = "%";
335 elseif (empty($pid)) $pid = "NULL";
337 if (strstr($pid,"%")) $command = "like";
339 $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
340 if ($limit != "all") $sql .= " limit $start, $limit";
342 $rez = sqlStatement($sql);
343 for($iter=0; $row=sqlFetchArray($rez); $iter++)
344 $returnval[$iter]=$row;
349 function getPatientName($pid) {
352 // larry :: DBC change
353 // $patientData = getPatientPID(array("pid"=>$pid));
354 $patientData = getPatientPID($pid);
356 if (empty($patientData[0]['lname']))
358 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
362 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
364 $DOB = fixDate($DOB, $DOB);
366 $sql="select $given from patient_data where DOB like '$DOB%' " .
370 $sql .= " limit $start, $limit";
372 $rez = sqlStatement($sql);
373 for($iter=0; $row=sqlFetchArray($rez); $iter++)
374 $returnval[$iter]=$row;
379 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
381 $sql="select $given from patient_data where ss like '$ss%' " .
385 $sql .= " limit $start, $limit";
387 $rez = sqlStatement($sql);
388 for($iter=0; $row=sqlFetchArray($rez); $iter++)
389 $returnval[$iter]=$row;
394 //(CHEMED) Search by phone number
395 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
397 $phone = ereg_replace( "[[:punct:]]","", $phone );
398 $sql="select $given from patient_data where REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP '$phone' " .
402 $sql .= " limit $start, $limit";
404 $rez = sqlStatement($sql);
405 for($iter=0; $row=sqlFetchArray($rez); $iter++)
406 $returnval[$iter]=$row;
411 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
413 $sql="select $given from patient_data order by $orderby";
416 $sql .= " limit $start, $limit";
418 $rez = sqlStatement($sql);
419 for($iter=0; $row=sqlFetchArray($rez); $iter++)
420 $returnval[$iter]=$row;
425 //----------------------input functions
426 function newPatientData( $db_id="",
449 $contact_relationship = "",
456 $migrantseasonal = "",
458 $monthly_income = "",
460 $financial_review = "",
473 $drivers_license = "",
479 $prefixlastpartner = "",
488 $DOB = fixDate($DOB);
489 $regdate = fixDate($regdate);
492 $referral_source = '';
494 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
495 // Check for brain damage:
496 if ($db_id != $rez['id']) {
497 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
498 $rez['id'] . "' to '$db_id' for pid '$pid'";
501 $fitness = $rez['fitness'];
502 $referral_source = $rez['referral_source'];
505 // Get the default price level.
506 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
507 "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
508 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
510 // this was a 'replace into' statement but that would overwrite data
511 // seems like a HIPAA violation of some sort to me -- JRM Apr 2008
512 $query = ("insert into patient_data set
521 postal_code='$postal_code',
524 country_code='$country_code',
525 drivers_license='$drivers_license',
527 occupation='$occupation',
528 phone_home='$phone_home',
529 phone_biz='$phone_biz',
530 phone_contact='$phone_contact',
532 contact_relationship='$contact_relationship',
533 referrer='$referrer',
534 referrerID='$referrerID',
536 language='$language',
537 ethnoracial='$ethnoracial',
538 interpretter='$interpretter',
539 migrantseasonal='$migrantseasonal',
540 family_size='$family_size',
541 monthly_income='$monthly_income',
542 homeless='$homeless',
543 financial_review='$financial_review',
546 providerID = '$providerID',
547 genericname1 = '$genericname1',
548 genericval1 = '$genericval1',
549 genericname2 = '$genericname2',
550 genericval2 = '$genericval2',
551 phone_cell = '$phone_cell',
552 pharmacy_id = '$pharmacy_id',
553 hipaa_mail = '$hipaa_mail',
554 hipaa_voice = '$hipaa_voice',
555 hipaa_notice = '$hipaa_notice',
556 hipaa_message = '$hipaa_message',
559 referral_source='$referral_source',
561 pricelevel='$pricelevel',
564 $id = sqlInsert($query);
568 // find the last inserted id for new patient case
569 $db_id = mysql_insert_id();
573 $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
576 if ( $GLOBALS['dutchpc'] ) {
577 $querynl = ("REPLACE INTO patient_data_NL SET
579 pdn_pxlast = '$prefixlast',
580 pdn_pxlastpar = '$prefixlastpartner',
581 pdn_lastpar = '$lastpartner',
582 pdn_street = '$nstreet',
584 pdn_addition = '$nadd',
585 pdn_initials = '$initials'
588 if ( $db_id ) $idnl = sqlInsert($querynl); // only if exists
595 if ( $GLOBALS['dutchpc'] && ( $db_id ) ) {
596 $querypr = ("INSERT INTO cl_providers(pro_pid, pro_company, pro_initials, pro_prefix, pro_lname,
597 pro_street, pro_number, pro_addition, pro_city, pro_zipcode, pro_phone, pro_fax, pro_email, pro_referer )
598 VALUES ($db_id, '{$provider_data['pro_company']}', '{$provider_data['pro_initials']}',
599 '{$provider_data['pro_prefix']}', '{$provider_data['pro_lname']}',
600 '{$provider_data['pro_street']}', '{$provider_data['pro_number']}', '{$provider_data['pro_addition']}',
601 '{$provider_data['pro_city']}', '{$provider_data['pro_zipcode']}',
602 '{$provider_data['pro_phone']}', '{$provider_data['pro_fax']}', '{$provider_data['pro_email']}',
603 '{$provider_data['pro_referer']}')
604 ON DUPLICATE KEY UPDATE pro_referer = '{$provider_data['pro_referer']}',
605 pro_company = '{$provider_data['pro_company']}', pro_initials = '{$provider_data['pro_initials']}',
606 pro_prefix = '{$provider_data['pro_prefix']}',
607 pro_lname = '{$provider_data['pro_lname']}', pro_street = '{$provider_data['pro_street']}',
608 pro_number = '{$provider_data['pro_number']}', pro_addition = '{$provider_data['pro_addition']}',
609 pro_city = '{$provider_data['pro_city']}', pro_zipcode = '{$provider_data['pro_zipcode']}',
610 pro_phone = '{$provider_data['pro_phone']}', pro_fax = '{$provider_data['pro_fax']}',
611 pro_email = '{$provider_data['pro_email']}'
613 $idpr = sqlInsert($querypr);
615 // referer if it's the case
616 if ( $referer_data['ref_code'] ) {
617 $queryre = ("INSERT INTO cl_referers(ref_pid, ref_code, ref_company, ref_initials, ref_prefix,
618 ref_lname, ref_street, ref_number, ref_addition, ref_city, ref_zipcode, ref_phone, ref_fax,
620 VALUES ($db_id, {$referer_data['ref_code']}, '{$referer_data['ref_company']}',
621 '{$referer_data['ref_initials']}', '{$referer_data['ref_prefix']}',
622 '{$referer_data['ref_lname']}', '{$referer_data['ref_street']}', '{$referer_data['ref_number']}',
623 '{$referer_data['ref_addition']}', '{$referer_data['ref_city']}', '{$referer_data['ref_zipcode']}',
624 '{$referer_data['ref_phone']}', '{$referer_data['ref_fax']}', '{$referer_data['ref_email']}')
625 ON DUPLICATE KEY UPDATE ref_code = {$referer_data['ref_code']},
626 ref_company = '{$referer_data['ref_company']}', ref_initials = '{$referer_data['ref_initials']}',
627 ref_prefix = '{$referer_data['ref_prefix']}',
628 ref_lname = '{$referer_data['ref_lname']}', ref_street = '{$referer_data['ref_street']}',
629 ref_number = '{$referer_data['ref_number']}', ref_addition = '{$referer_data['ref_addition']}',
630 ref_city = '{$referer_data['ref_city']}', ref_zipcode = '{$referer_data['ref_zipcode']}',
631 ref_phone = '{$referer_data['ref_phone']}', ref_fax = '{$referer_data['ref_fax']}',
632 ref_email = '{$referer_data['ref_email']}'
634 $idre = sqlInsert($queryre);
639 sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
640 $phone_biz,$phone_cell,$email,$pid);
645 // Supported input date formats are:
647 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
649 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
651 function fixDate($date, $default="0000-00-00") {
652 $fixed_date = $default;
654 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
655 $dmy = preg_split("'[/.-]'", $date);
657 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
659 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
660 if ($dmy[2] < 1000) $dmy[2] += 1900;
661 if ($dmy[2] < 1910) $dmy[2] += 100;
663 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
670 function updatePatientData($pid,$new)
672 /*******************************************************************
673 $real = getPatientData($pid);
674 $new['DOB'] = fixDate($new['DOB']);
675 while(list($key, $value) = each ($new))
676 $real[$key] = $value;
677 $real['date'] = "'+NOW()+'";
679 $sql = "insert into patient_data set ";
680 while(list($key, $value) = each($real))
681 $sql .= $key." = '$value', ";
682 $sql = substr($sql, 0, -2);
683 return sqlInsert($sql);
684 *******************************************************************/
686 // The above was broken, though seems intent to insert a new patient_data
687 // row for each update. A good idea, but nothing is doing that yet so
688 // the code below does not yet attempt it.
690 $new['DOB'] = fixDate($new['DOB']);
693 $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
694 // Check for brain damage:
695 if ($pid != $rez['pid']) {
696 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
697 $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
700 $sql = "UPDATE patient_data SET date = NOW()";
701 foreach ($new as $key => $value) {
702 $sql .= ", $key = '$value'";
704 $sql .= " WHERE id = '$db_id'";
705 $id = sqlInsert($sql);
707 sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
708 $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
709 $rez['phone_cell'],$rez['email'],$rez['pid']);
714 function newEmployerData( $pid,
723 return sqlInsert("insert into employer_data set
726 postal_code='$postal_code',
735 function updateEmployerData($pid, $new)
737 $old = getEmployerData($pid);
740 foreach (array('name','street','city','state','postal_code','country') as $key) {
741 $value = empty($old[$key]) ? '' : addslashes($old[$key]);
742 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
746 $set .= "$key = '$value', ";
749 $set .= "pid = '$pid', date = NOW()";
750 return sqlInsert("INSERT INTO employer_data SET $set");
755 // This updates or adds the given insurance data info, while retaining any
756 // previously added insurance_data rows that should be preserved.
757 // This does not directly support the maintenance of non-current insurance.
759 function newInsuranceData(
766 $subscriber_lname = "",
767 $subscriber_mname = "",
768 $subscriber_fname = "",
769 $subscriber_relationship = "",
771 $subscriber_DOB = "",
772 $subscriber_street = "",
773 $subscriber_postal_code = "",
774 $subscriber_city = "",
775 $subscriber_state = "",
776 $subscriber_country = "",
777 $subscriber_phone = "",
778 $subscriber_employer = "",
779 $subscriber_employer_street = "",
780 $subscriber_employer_city = "",
781 $subscriber_employer_postal_code = "",
782 $subscriber_employer_state = "",
783 $subscriber_employer_country = "",
785 $subscriber_sex = "",
786 $effective_date = "0000-00-00")
788 if (strlen($type) <= 0) return FALSE;
790 // If a bad date was passed, err on the side of caution.
791 $effective_date = fixDate($effective_date, date('Y-m-d'));
793 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
794 "pid = '$pid' AND type = '$type' ORDER BY date DESC");
795 $idrow = sqlFetchArray($idres);
797 // Replace the most recent entry in any of the following cases:
798 // * Its effective date is >= this effective date.
799 // * It is the first entry and it has no (insurance) provider.
800 // * There is no encounter that is earlier than the new effective date but
801 // on or after the old effective date.
802 // Otherwise insert a new entry.
806 if (strcmp($idrow['date'], $effective_date) > 0) {
810 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
814 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
815 "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
816 "date >= '" . $idrow['date'] . " 00:00:00'");
817 if ($ferow['count'] == 0) $replace = true;
824 // TBD: This is a bit dangerous in that a typo in entering the effective
825 // date can wipe out previous insurance history. So we want some data
826 // entry validation somewhere.
827 sqlStatement("DELETE FROM insurance_data WHERE " .
828 "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
829 "id != " . $idrow['id']);
832 $data['type'] = $type;
833 $data['provider'] = $provider;
834 $data['policy_number'] = $policy_number;
835 $data['group_number'] = $group_number;
836 $data['plan_name'] = $plan_name;
837 $data['subscriber_lname'] = $subscriber_lname;
838 $data['subscriber_mname'] = $subscriber_mname;
839 $data['subscriber_fname'] = $subscriber_fname;
840 $data['subscriber_relationship'] = $subscriber_relationship;
841 $data['subscriber_ss'] = $subscriber_ss;
842 $data['subscriber_DOB'] = $subscriber_DOB;
843 $data['subscriber_street'] = $subscriber_street;
844 $data['subscriber_postal_code'] = $subscriber_postal_code;
845 $data['subscriber_city'] = $subscriber_city;
846 $data['subscriber_state'] = $subscriber_state;
847 $data['subscriber_country'] = $subscriber_country;
848 $data['subscriber_phone'] = $subscriber_phone;
849 $data['subscriber_employer'] = $subscriber_employer;
850 $data['subscriber_employer_city'] = $subscriber_employer_city;
851 $data['subscriber_employer_street'] = $subscriber_employer_street;
852 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
853 $data['subscriber_employer_state'] = $subscriber_employer_state;
854 $data['subscriber_employer_country'] = $subscriber_employer_country;
855 $data['copay'] = $copay;
856 $data['subscriber_sex'] = $subscriber_sex;
858 $data['date'] = $effective_date;
859 updateInsuranceData($idrow['id'], $data);
863 return sqlInsert("INSERT INTO insurance_data SET
865 provider = '$provider',
866 policy_number = '$policy_number',
867 group_number = '$group_number',
868 plan_name = '$plan_name',
869 subscriber_lname = '$subscriber_lname',
870 subscriber_mname = '$subscriber_mname',
871 subscriber_fname = '$subscriber_fname',
872 subscriber_relationship = '$subscriber_relationship',
873 subscriber_ss = '$subscriber_ss',
874 subscriber_DOB = '$subscriber_DOB',
875 subscriber_street = '$subscriber_street',
876 subscriber_postal_code = '$subscriber_postal_code',
877 subscriber_city = '$subscriber_city',
878 subscriber_state = '$subscriber_state',
879 subscriber_country = '$subscriber_country',
880 subscriber_phone = '$subscriber_phone',
881 subscriber_employer = '$subscriber_employer',
882 subscriber_employer_city = '$subscriber_employer_city',
883 subscriber_employer_street = '$subscriber_employer_street',
884 subscriber_employer_postal_code = '$subscriber_employer_postal_code',
885 subscriber_employer_state = '$subscriber_employer_state',
886 subscriber_employer_country = '$subscriber_employer_country',
888 subscriber_sex = '$subscriber_sex',
890 date = '$effective_date'
895 // This is used internally only.
896 function updateInsuranceData($id, $new)
898 $fields = sqlListFields("insurance_data");
901 while(list($key, $value) = each ($new)) {
902 if (in_array($key, $fields)) {
907 $sql = "UPDATE insurance_data SET ";
908 while(list($key, $value) = each($use))
909 $sql .= $key . " = '$value', ";
910 $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
915 function newHistoryData($pid, $new=false) {
916 $sql = "insert into history_data set pid = '$pid', date = NOW()";
918 while(list($key, $value) = each($new)) {
919 if (!get_magic_quotes_gpc()) $value = addslashes($value);
920 $sql .= ", $key = '$value'";
923 return sqlInsert($sql);
926 function updateHistoryData($pid,$new)
928 $real = getHistoryData($pid);
929 while(list($key, $value) = each ($new))
930 $real[$key] = $value;
931 $real['date'] = "'+NOW()+'";
934 $sql = "insert into history_data set ";
935 while(list($key, $value) = each($real))
936 $sql .= $key." = '$value', ";
937 $sql = substr($sql, 0, -2);
940 return sqlInsert($sql);
943 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
944 $phone_biz,$phone_cell,$email,$pid="")
946 $db = $GLOBALS['adodb']['db'];
947 $customer_info = array();
949 $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
950 $result = $db->Execute($sql);
951 if ($result && !$result->EOF) {
952 $customer_info['foreign_update'] = true;
953 $customer_info['foreign_id'] = $result->fields['foreign_id'];
954 $customer_info['foreign_table'] = $result->fields['foreign_table'];
957 ///xml rpc code to connect to accounting package and add user to it
958 $customer_info['firstname'] = $fname;
959 $customer_info['lastname'] = $lname;
960 $customer_info['address'] = $street;
961 $customer_info['suburb'] = $city;
962 $customer_info['state'] = $state;
963 $customer_info['postcode'] = $postal_code;
965 //ezybiz wants state as a code rather than abbreviation
966 $customer_info['geo_zone_id'] = "";
967 $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
968 $db = $GLOBALS['adodb']['db'];
969 $result = $db->Execute($sql);
970 if ($result && !$result->EOF) {
971 $customer_info['geo_zone_id'] = $result->fields['zone_id'];
974 //ezybiz wants country as a code rather than abbreviation
975 $customer_info['geo_country_id'] = "";
976 $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
977 $db = $GLOBALS['adodb']['db'];
978 $result = $db->Execute($sql);
979 if ($result && !$result->EOF) {
980 $customer_info['geo_country_id'] = $result->fields['countries_id'];
983 $customer_info['phone1'] = $phone_home;
984 $customer_info['phone1comment'] = "Home Phone";
985 $customer_info['phone2'] = $phone_biz;
986 $customer_info['phone2comment'] = "Business Phone";
987 $customer_info['phone3'] = $phone_cell;
988 $customer_info['phone3comment'] = "Cell Phone";
989 $customer_info['email'] = $email;
990 $customer_info['customernumber'] = $pid;
992 $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
993 $ws = new WSWrapper($function);
995 // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
996 if (is_numeric($ws->value)) {
997 $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
998 $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1002 // Returns Date of Birth given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1003 function getPatientAge($dobYMD)
1005 $tdyYMD=date("Ymd");
1006 $yearDiff = substr($tdyYMD,0,4) - substr($dobYMD,0,4);
1007 $ageInMonths = ((substr($tdyYMD,0,4)*12)+substr($tdyYMD,4,2)) -
1008 ((substr($dobYMD,0,4)*12)+substr($dobYMD,4,2));
1009 $dayDiff = substr($tdyYMD,6,2) - substr($dobYMD,6,2);
1010 if ( $dayDiff < 0 ) {
1013 if ( $ageInMonths > 24 ) {
1014 $age = intval($ageInMonths/12);
1017 $age = "$ageInMonths month";
1022 function dateToDB ($date)
1024 $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1029 // ----------------------------------------------------------------------------
1031 * DROPDOWN FOR COUNTRIES
1033 * build a dropdown with all countries from geo_country_reference
1035 * @param int $selected - id for selected record
1036 * @param string $name - the name/id for select form
1037 * @return void - just echo the html encoded string
1039 function dropdown_countries($selected = 0, $name = 'country_code') {
1040 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1042 $string = "<select name='$name' id='$name'>";
1043 while ( $row = sqlFetchArray($r) ) {
1044 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1045 $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1048 $string .= '</select>';
1053 // ----------------------------------------------------------------------------
1055 * DROPDOWN FOR YES/NO
1057 * build a dropdown with two options (yes - 1, no - 0)
1059 * @param int $selected - id for selected record
1060 * @param string $name - the name/id for select form
1061 * @return void - just echo the html encoded string
1063 function dropdown_yesno($selected = 0, $name = 'yesno') {
1064 $string = "<select name='$name' id='$name'>";
1066 $selected = (int)$selected;
1067 if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1068 else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1070 $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1071 $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1072 $string .= '</select>';
1077 // ----------------------------------------------------------------------------
1079 * DROPDOWN FOR MALE/FEMALE options
1081 * build a dropdown with three options (unselected/male/female)
1083 * @param int $selected - id for selected record
1084 * @param string $name - the name/id for select form
1085 * @return void - just echo the html encoded string
1087 function dropdown_sex($selected = 0, $name = 'sex') {
1088 $string = "<select name='$name' id='$name'>";
1090 if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1091 else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1092 else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1094 $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1095 $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1096 $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1097 $string .= '</select>';
1102 // ----------------------------------------------------------------------------
1104 * DROPDOWN FOR MARITAL STATUS
1106 * build a dropdown with marital status
1108 * @param int $selected - id for selected record
1109 * @param string $name - the name/id for select form
1110 * @return void - just echo the html encoded string
1112 function dropdown_marital($selected = 0, $name = 'status') {
1113 $string = "<select name='$name' id='$name'>";
1115 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1117 foreach ( $statii as $st ) {
1118 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1119 $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1122 $string .= '</select>';
1127 // ----------------------------------------------------------------------------
1129 * DROPDOWN FOR PROVIDERS
1131 * build a dropdown with all providers
1133 * @param int $selected - id for selected record
1134 * @param string $name - the name/id for select form
1135 * @return void - just echo the html encoded string
1137 function dropdown_providers($selected = 0, $name = 'status') {
1138 $provideri = getProviderInfo();
1140 $string = "<select name='$name' id='$name'>";
1141 $string .= '<option value="">' .xl('Unassigned'). '</option>';
1142 foreach ( $provideri as $s ) {
1143 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1144 $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1147 $string .= '</select>';
1152 // ----------------------------------------------------------------------------
1154 * DROPDOWN FOR INSURANCE COMPANIES
1156 * build a dropdown with all insurers
1158 * @param int $selected - id for selected record
1159 * @param string $name - the name/id for select form
1160 * @return void - just echo the html encoded string
1162 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1163 $insurancei = getInsuranceProviders();
1165 $string = "<select name='$name' id='$name'>";
1166 $string .= '<option value="0">Onbekend</option>';
1167 foreach ( $insurancei as $iid => $iname ) {
1168 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1169 $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1172 $string .= '</select>';
1178 // ----------------------------------------------------------------------------
1182 * return the name or the country code, function of arguments
1184 * @param int $country_code
1185 * @param string $country_name
1186 * @return string | int - name or code
1188 function country_code($country_code = 0, $country_name = '') {
1190 if ( $country_code ) {
1191 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1193 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1196 $db = $GLOBALS['adodb']['db'];
1197 $result = $db->Execute($sql);
1198 if ($result && !$result->EOF) {
1199 $strint = $result->fields['res'];
1205 // ----------------------------------------------------------------------------
1207 * GET INSURANCE DATA
1210 * return the insurer(s) and some patient
1212 * @param int $pid - patient id
1213 * @param int $current 1-current 0-all insurers
1216 function get_insurers_nl($pid = 0, $current = 1) {
1217 if ( !$pid ) return FALSE;
1219 $q = sprintf("SELECT * FROM patient_insurers_NL pi JOIN insurance_companies ic ON ic.id = pi.pin_provider
1220 WHERE pin_pid = %d ORDER BY pin_date DESC", $pid);
1221 $r = mysql_query($q) or die(mysql_error());
1223 while ( $row = mysql_fetch_array($r) ) {
1227 return ( $current ? $rez[0] : $rez );
1230 // ----------------------------------------------------------------------------
1232 * SET INSURANCE DATA
1235 * set the insurer for a patient
1237 * @param int $pid - patient id
1238 * @param int $insid - insurer id
1241 function set_insurer_nl($pid = 0, $insid = 0, $date = '', $policy = '') {
1242 if ( !$pid || !$insid || ($date == '0000-00-00') ) return FALSE;
1244 $q = sprintf("INSERT INTO patient_insurers_NL(pin_pid, pin_provider, pin_date, pin_policy)
1245 VALUES(%d, %d, '%s', '%s')", $pid, $insid, $date, $policy);
1246 $r = mysql_query($q) or die(mysql_error());
1249 // ----------------------------------------------------------------------------
1251 * FIND THE INSURERS STATUS FOR A PATIENT
1254 * return the answer for the question: is this the first insurer or not?
1256 * @param int $pid - patient id
1257 * @return int - the number of insurer records ( 0 - no insurer; >0 some insurers)
1259 function total_insurers($pid = 0) {
1260 if ( !$pid ) return FALSE;
1262 $q = sprintf("SELECT COUNT(*) AS c FROM patient_insurers_NL WHERE pin_pid = %d ", $pid);
1263 $r = mysql_query($q) or die(mysql_error());
1264 $row = mysql_fetch_array($r);
1270 function DBToDate ($date)
1272 $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);