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 sqlQuery("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 _set_patient_inc_count($limit, $count, $where) {
266 // When the limit is exceeded, find out what the unlimited count would be.
267 $GLOBALS['PATIENT_INC_COUNT'] = $count;
268 if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
269 $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where");
270 $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
274 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")
276 // Allow the last name to be followed by a comma and some part of a first name.
277 // New behavior for searches:
278 // Allows comma alone followed by some part of a first name
279 // If the first letter of either name is capital, searches for name starting
280 // with given substring (the expected behavior). If it is lower case, it
281 // it searches for the substring anywhere in the name. This applies to either
282 // last name or first name or both. The arbitrary limit of 100 results is set
283 // in the sql query below. --Mark Leeds
284 $lname = trim($lname);
286 if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
287 $lname = trim($matches[1]);
288 $fname = trim($matches[2]);
290 $search_for_pieces1 = '';
291 $search_for_pieces2 = '';
292 if ($lname{0} != strtoupper($lname{0})) {$search_for_pieces1 = '%';}
293 if ($fname{0} != strtoupper($fname{0})) {$search_for_pieces2 = '%';}
295 $where = "lname LIKE '" . $search_for_pieces1 . "$lname%' " .
296 "AND fname LIKE '" . $search_for_pieces2 . "$fname%'";
297 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
298 if ($limit != "all") $sql .= " LIMIT $start, $limit";
300 $rez = sqlStatement($sql);
302 for($iter=0; $row=sqlFetchArray($rez); $iter++)
303 $returnval[$iter] = $row;
305 _set_patient_inc_count($limit, count($returnval), $where);
309 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")
311 $where = "pubpid LIKE '$pid%'";
312 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
313 if ($limit != "all") $sql .= " limit $start, $limit";
314 $rez = sqlStatement($sql);
315 for($iter=0; $row=sqlFetchArray($rez); $iter++)
316 $returnval[$iter]=$row;
318 _set_patient_inc_count($limit, count($returnval), $where);
322 // return a collection of Patient PIDs
323 // new arg style by JRM March 2008
324 // 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")
325 function getPatientPID($args)
328 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
329 $orderby = "lname ASC, fname ASC";
333 // alter default values if defined in the passed in args
334 if (isset($args['pid'])) { $pid = $args['pid']; }
335 if (isset($args['given'])) { $given = $args['given']; }
336 if (isset($args['orderby'])) { $orderby = $args['orderby']; }
337 if (isset($args['limit'])) { $limit = $args['limit']; }
338 if (isset($args['start'])) { $start = $args['start']; }
341 if ($pid == -1) $pid = "%";
342 elseif (empty($pid)) $pid = "NULL";
344 if (strstr($pid,"%")) $command = "like";
346 $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
347 if ($limit != "all") $sql .= " limit $start, $limit";
349 $rez = sqlStatement($sql);
350 for($iter=0; $row=sqlFetchArray($rez); $iter++)
351 $returnval[$iter]=$row;
356 function getPatientName($pid) {
357 if (empty($pid)) return "";
358 $patientData = getPatientPID(array("pid"=>$pid));
359 if (empty($patientData[0]['lname'])) return "";
360 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
364 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
366 $DOB = fixDate($DOB, $DOB);
367 $where = "DOB like '$DOB%'";
368 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
369 if ($limit != "all") $sql .= " LIMIT $start, $limit";
371 $rez = sqlStatement($sql);
372 for($iter=0; $row=sqlFetchArray($rez); $iter++)
373 $returnval[$iter]=$row;
375 _set_patient_inc_count($limit, count($returnval), $where);
379 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
381 $where = "ss LIKE '$ss%'";
382 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
383 if ($limit != "all") $sql .= " LIMIT $start, $limit";
385 $rez = sqlStatement($sql);
386 for($iter=0; $row=sqlFetchArray($rez); $iter++)
387 $returnval[$iter]=$row;
389 _set_patient_inc_count($limit, count($returnval), $where);
393 //(CHEMED) Search by phone number
394 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
396 $phone = ereg_replace( "[[:punct:]]","", $phone );
397 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP '$phone'";
398 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
399 if ($limit != "all") $sql .= " LIMIT $start, $limit";
401 $rez = sqlStatement($sql);
402 for($iter=0; $row=sqlFetchArray($rez); $iter++)
403 $returnval[$iter]=$row;
405 _set_patient_inc_count($limit, count($returnval), $where);
409 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
411 $sql="select $given from patient_data order by $orderby";
414 $sql .= " limit $start, $limit";
416 $rez = sqlStatement($sql);
417 for($iter=0; $row=sqlFetchArray($rez); $iter++)
418 $returnval[$iter]=$row;
423 //----------------------input functions
424 function newPatientData( $db_id="",
447 $contact_relationship = "",
454 $migrantseasonal = "",
456 $monthly_income = "",
458 $financial_review = "",
471 $drivers_license = "",
477 $prefixlastpartner = "",
480 $provider_data = array(),
481 $referer_data = array()
486 $DOB = fixDate($DOB);
487 $regdate = fixDate($regdate);
490 $referral_source = '';
492 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
493 // Check for brain damage:
494 if ($db_id != $rez['id']) {
495 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
496 $rez['id'] . "' to '$db_id' for pid '$pid'";
499 $fitness = $rez['fitness'];
500 $referral_source = $rez['referral_source'];
503 // Get the default price level.
504 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
505 "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
506 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
508 $query = ("replace into patient_data set
517 postal_code='$postal_code',
520 country_code='$country_code',
521 drivers_license='$drivers_license',
523 occupation='$occupation',
524 phone_home='$phone_home',
525 phone_biz='$phone_biz',
526 phone_contact='$phone_contact',
528 contact_relationship='$contact_relationship',
529 referrer='$referrer',
530 referrerID='$referrerID',
532 language='$language',
533 ethnoracial='$ethnoracial',
534 interpretter='$interpretter',
535 migrantseasonal='$migrantseasonal',
536 family_size='$family_size',
537 monthly_income='$monthly_income',
538 homeless='$homeless',
539 financial_review='$financial_review',
542 providerID = '$providerID',
543 genericname1 = '$genericname1',
544 genericval1 = '$genericval1',
545 genericname2 = '$genericname2',
546 genericval2 = '$genericval2',
547 phone_cell = '$phone_cell',
548 pharmacy_id = '$pharmacy_id',
549 hipaa_mail = '$hipaa_mail',
550 hipaa_voice = '$hipaa_voice',
551 hipaa_notice = '$hipaa_notice',
552 hipaa_message = '$hipaa_message',
555 referral_source='$referral_source',
557 pricelevel='$pricelevel',
560 $id = sqlInsert($query);
564 // find the last inserted id for new patient case
565 $db_id = empty($GLOBALS['dutchpc']) ? mysql_insert_id() : dsql_lastid();
569 $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
572 if ( $GLOBALS['dutchpc'] ) {
573 $init = strtoupper(preg_replace('/[\s\.\-_0-9]/','',$initials));
575 $querynl = ("REPLACE INTO patient_data_NL SET
577 pdn_pxlast = '$prefixlast',
578 pdn_pxlastpar = '$prefixlastpartner',
579 pdn_lastpar = '$lastpartner',
580 pdn_street = '$nstreet',
582 pdn_addition = '$nadd',
583 pdn_initials = '$init'
586 if ( $db_id ) $idnl = sqlInsert($querynl); // only if exists
593 if ( $GLOBALS['dutchpc'] && $db_id && $provider_data && $referer_data) {
594 $querypr = ("INSERT INTO cl_providers(pro_pid, pro_company, pro_initials, pro_prefix, pro_lname,
595 pro_street, pro_number, pro_addition, pro_city, pro_zipcode, pro_phone, pro_fax, pro_email, pro_referer )
596 VALUES ($db_id, '{$provider_data['pro_company']}', '{$provider_data['pro_initials']}',
597 '{$provider_data['pro_prefix']}', '{$provider_data['pro_lname']}',
598 '{$provider_data['pro_street']}', '{$provider_data['pro_number']}', '{$provider_data['pro_addition']}',
599 '{$provider_data['pro_city']}', '{$provider_data['pro_zipcode']}',
600 '{$provider_data['pro_phone']}', '{$provider_data['pro_fax']}', '{$provider_data['pro_email']}',
601 '{$provider_data['pro_referer']}')
602 ON DUPLICATE KEY UPDATE pro_referer = '{$provider_data['pro_referer']}',
603 pro_company = '{$provider_data['pro_company']}', pro_initials = '{$provider_data['pro_initials']}',
604 pro_prefix = '{$provider_data['pro_prefix']}',
605 pro_lname = '{$provider_data['pro_lname']}', pro_street = '{$provider_data['pro_street']}',
606 pro_number = '{$provider_data['pro_number']}', pro_addition = '{$provider_data['pro_addition']}',
607 pro_city = '{$provider_data['pro_city']}', pro_zipcode = '{$provider_data['pro_zipcode']}',
608 pro_phone = '{$provider_data['pro_phone']}', pro_fax = '{$provider_data['pro_fax']}',
609 pro_email = '{$provider_data['pro_email']}'
611 $idpr = sqlInsert($querypr);
613 // referer if it's the case
614 if ( $referer_data['ref_code'] ) {
615 $queryre = ("INSERT INTO cl_referers(ref_pid, ref_code, ref_company, ref_initials, ref_prefix,
616 ref_lname, ref_street, ref_number, ref_addition, ref_city, ref_zipcode, ref_phone, ref_fax,
618 VALUES ($db_id, {$referer_data['ref_code']}, '{$referer_data['ref_company']}',
619 '{$referer_data['ref_initials']}', '{$referer_data['ref_prefix']}',
620 '{$referer_data['ref_lname']}', '{$referer_data['ref_street']}', '{$referer_data['ref_number']}',
621 '{$referer_data['ref_addition']}', '{$referer_data['ref_city']}', '{$referer_data['ref_zipcode']}',
622 '{$referer_data['ref_phone']}', '{$referer_data['ref_fax']}', '{$referer_data['ref_email']}')
623 ON DUPLICATE KEY UPDATE ref_code = {$referer_data['ref_code']},
624 ref_company = '{$referer_data['ref_company']}', ref_initials = '{$referer_data['ref_initials']}',
625 ref_prefix = '{$referer_data['ref_prefix']}',
626 ref_lname = '{$referer_data['ref_lname']}', ref_street = '{$referer_data['ref_street']}',
627 ref_number = '{$referer_data['ref_number']}', ref_addition = '{$referer_data['ref_addition']}',
628 ref_city = '{$referer_data['ref_city']}', ref_zipcode = '{$referer_data['ref_zipcode']}',
629 ref_phone = '{$referer_data['ref_phone']}', ref_fax = '{$referer_data['ref_fax']}',
630 ref_email = '{$referer_data['ref_email']}'
632 $idre = sqlInsert($queryre);
637 sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
638 $phone_biz,$phone_cell,$email,$pid);
643 // Supported input date formats are:
645 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
647 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
649 function fixDate($date, $default="0000-00-00") {
650 $fixed_date = $default;
652 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
653 $dmy = preg_split("'[/.-]'", $date);
655 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
657 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
658 if ($dmy[2] < 1000) $dmy[2] += 1900;
659 if ($dmy[2] < 1910) $dmy[2] += 100;
661 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
668 function updatePatientData($pid,$new)
670 /*******************************************************************
671 $real = getPatientData($pid);
672 $new['DOB'] = fixDate($new['DOB']);
673 while(list($key, $value) = each ($new))
674 $real[$key] = $value;
675 $real['date'] = "'+NOW()+'";
677 $sql = "insert into patient_data set ";
678 while(list($key, $value) = each($real))
679 $sql .= $key." = '$value', ";
680 $sql = substr($sql, 0, -2);
681 return sqlInsert($sql);
682 *******************************************************************/
684 // The above was broken, though seems intent to insert a new patient_data
685 // row for each update. A good idea, but nothing is doing that yet so
686 // the code below does not yet attempt it.
688 $new['DOB'] = fixDate($new['DOB']);
691 $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
692 // Check for brain damage:
693 if ($pid != $rez['pid']) {
694 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
695 $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
698 $sql = "UPDATE patient_data SET date = NOW()";
699 foreach ($new as $key => $value) {
700 $sql .= ", $key = '$value'";
702 $sql .= " WHERE id = '$db_id'";
703 $id = sqlInsert($sql);
705 sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
706 $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
707 $rez['phone_cell'],$rez['email'],$rez['pid']);
712 function newEmployerData( $pid,
721 return sqlInsert("insert into employer_data set
724 postal_code='$postal_code',
733 function updateEmployerData($pid, $new)
735 $old = getEmployerData($pid);
738 foreach (array('name','street','city','state','postal_code','country') as $key) {
739 $value = empty($old[$key]) ? '' : addslashes($old[$key]);
740 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
744 $set .= "$key = '$value', ";
747 $set .= "pid = '$pid', date = NOW()";
748 return sqlInsert("INSERT INTO employer_data SET $set");
753 // This updates or adds the given insurance data info, while retaining any
754 // previously added insurance_data rows that should be preserved.
755 // This does not directly support the maintenance of non-current insurance.
757 function newInsuranceData(
764 $subscriber_lname = "",
765 $subscriber_mname = "",
766 $subscriber_fname = "",
767 $subscriber_relationship = "",
769 $subscriber_DOB = "",
770 $subscriber_street = "",
771 $subscriber_postal_code = "",
772 $subscriber_city = "",
773 $subscriber_state = "",
774 $subscriber_country = "",
775 $subscriber_phone = "",
776 $subscriber_employer = "",
777 $subscriber_employer_street = "",
778 $subscriber_employer_city = "",
779 $subscriber_employer_postal_code = "",
780 $subscriber_employer_state = "",
781 $subscriber_employer_country = "",
783 $subscriber_sex = "",
784 $effective_date = "0000-00-00")
786 if (strlen($type) <= 0) return FALSE;
788 // If a bad date was passed, err on the side of caution.
789 $effective_date = fixDate($effective_date, date('Y-m-d'));
791 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
792 "pid = '$pid' AND type = '$type' ORDER BY date DESC");
793 $idrow = sqlFetchArray($idres);
795 // Replace the most recent entry in any of the following cases:
796 // * Its effective date is >= this effective date.
797 // * It is the first entry and it has no (insurance) provider.
798 // * There is no encounter that is earlier than the new effective date but
799 // on or after the old effective date.
800 // Otherwise insert a new entry.
804 if (strcmp($idrow['date'], $effective_date) > 0) {
808 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
812 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
813 "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
814 "date >= '" . $idrow['date'] . " 00:00:00'");
815 if ($ferow['count'] == 0) $replace = true;
822 // TBD: This is a bit dangerous in that a typo in entering the effective
823 // date can wipe out previous insurance history. So we want some data
824 // entry validation somewhere.
825 sqlStatement("DELETE FROM insurance_data WHERE " .
826 "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
827 "id != " . $idrow['id']);
830 $data['type'] = $type;
831 $data['provider'] = $provider;
832 $data['policy_number'] = $policy_number;
833 $data['group_number'] = $group_number;
834 $data['plan_name'] = $plan_name;
835 $data['subscriber_lname'] = $subscriber_lname;
836 $data['subscriber_mname'] = $subscriber_mname;
837 $data['subscriber_fname'] = $subscriber_fname;
838 $data['subscriber_relationship'] = $subscriber_relationship;
839 $data['subscriber_ss'] = $subscriber_ss;
840 $data['subscriber_DOB'] = $subscriber_DOB;
841 $data['subscriber_street'] = $subscriber_street;
842 $data['subscriber_postal_code'] = $subscriber_postal_code;
843 $data['subscriber_city'] = $subscriber_city;
844 $data['subscriber_state'] = $subscriber_state;
845 $data['subscriber_country'] = $subscriber_country;
846 $data['subscriber_phone'] = $subscriber_phone;
847 $data['subscriber_employer'] = $subscriber_employer;
848 $data['subscriber_employer_city'] = $subscriber_employer_city;
849 $data['subscriber_employer_street'] = $subscriber_employer_street;
850 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
851 $data['subscriber_employer_state'] = $subscriber_employer_state;
852 $data['subscriber_employer_country'] = $subscriber_employer_country;
853 $data['copay'] = $copay;
854 $data['subscriber_sex'] = $subscriber_sex;
856 $data['date'] = $effective_date;
857 updateInsuranceData($idrow['id'], $data);
861 return sqlInsert("INSERT INTO insurance_data SET
863 provider = '$provider',
864 policy_number = '$policy_number',
865 group_number = '$group_number',
866 plan_name = '$plan_name',
867 subscriber_lname = '$subscriber_lname',
868 subscriber_mname = '$subscriber_mname',
869 subscriber_fname = '$subscriber_fname',
870 subscriber_relationship = '$subscriber_relationship',
871 subscriber_ss = '$subscriber_ss',
872 subscriber_DOB = '$subscriber_DOB',
873 subscriber_street = '$subscriber_street',
874 subscriber_postal_code = '$subscriber_postal_code',
875 subscriber_city = '$subscriber_city',
876 subscriber_state = '$subscriber_state',
877 subscriber_country = '$subscriber_country',
878 subscriber_phone = '$subscriber_phone',
879 subscriber_employer = '$subscriber_employer',
880 subscriber_employer_city = '$subscriber_employer_city',
881 subscriber_employer_street = '$subscriber_employer_street',
882 subscriber_employer_postal_code = '$subscriber_employer_postal_code',
883 subscriber_employer_state = '$subscriber_employer_state',
884 subscriber_employer_country = '$subscriber_employer_country',
886 subscriber_sex = '$subscriber_sex',
888 date = '$effective_date'
893 // This is used internally only.
894 function updateInsuranceData($id, $new)
896 $fields = sqlListFields("insurance_data");
899 while(list($key, $value) = each ($new)) {
900 if (in_array($key, $fields)) {
905 $sql = "UPDATE insurance_data SET ";
906 while(list($key, $value) = each($use))
907 $sql .= $key . " = '$value', ";
908 $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
913 function newHistoryData($pid, $new=false) {
914 $sql = "insert into history_data set pid = '$pid', date = NOW()";
916 while(list($key, $value) = each($new)) {
917 if (!get_magic_quotes_gpc()) $value = addslashes($value);
918 $sql .= ", $key = '$value'";
921 return sqlInsert($sql);
924 function updateHistoryData($pid,$new)
926 $real = getHistoryData($pid);
927 while(list($key, $value) = each ($new))
928 $real[$key] = $value;
929 $real['date'] = "'+NOW()+'";
932 $sql = "insert into history_data set ";
933 while(list($key, $value) = each($real))
934 $sql .= $key." = '$value', ";
935 $sql = substr($sql, 0, -2);
938 return sqlInsert($sql);
941 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
942 $phone_biz,$phone_cell,$email,$pid="")
944 $db = $GLOBALS['adodb']['db'];
945 $customer_info = array();
947 $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
948 $result = $db->Execute($sql);
949 if ($result && !$result->EOF) {
950 $customer_info['foreign_update'] = true;
951 $customer_info['foreign_id'] = $result->fields['foreign_id'];
952 $customer_info['foreign_table'] = $result->fields['foreign_table'];
955 ///xml rpc code to connect to accounting package and add user to it
956 $customer_info['firstname'] = $fname;
957 $customer_info['lastname'] = $lname;
958 $customer_info['address'] = $street;
959 $customer_info['suburb'] = $city;
960 $customer_info['state'] = $state;
961 $customer_info['postcode'] = $postal_code;
963 //ezybiz wants state as a code rather than abbreviation
964 $customer_info['geo_zone_id'] = "";
965 $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
966 $db = $GLOBALS['adodb']['db'];
967 $result = $db->Execute($sql);
968 if ($result && !$result->EOF) {
969 $customer_info['geo_zone_id'] = $result->fields['zone_id'];
972 //ezybiz wants country as a code rather than abbreviation
973 $customer_info['geo_country_id'] = "";
974 $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
975 $db = $GLOBALS['adodb']['db'];
976 $result = $db->Execute($sql);
977 if ($result && !$result->EOF) {
978 $customer_info['geo_country_id'] = $result->fields['countries_id'];
981 $customer_info['phone1'] = $phone_home;
982 $customer_info['phone1comment'] = "Home Phone";
983 $customer_info['phone2'] = $phone_biz;
984 $customer_info['phone2comment'] = "Business Phone";
985 $customer_info['phone3'] = $phone_cell;
986 $customer_info['phone3comment'] = "Cell Phone";
987 $customer_info['email'] = $email;
988 $customer_info['customernumber'] = $pid;
990 $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
991 $ws = new WSWrapper($function);
993 // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
994 if (is_numeric($ws->value)) {
995 $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
996 $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1000 // Returns Date of Birth given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1001 function getPatientAge($dobYMD)
1003 $tdyYMD=date("Ymd");
1004 $yearDiff = substr($tdyYMD,0,4) - substr($dobYMD,0,4);
1005 $ageInMonths = ((substr($tdyYMD,0,4)*12)+substr($tdyYMD,4,2)) -
1006 ((substr($dobYMD,0,4)*12)+substr($dobYMD,4,2));
1007 $dayDiff = substr($tdyYMD,6,2) - substr($dobYMD,6,2);
1008 if ( $dayDiff < 0 ) {
1011 if ( $ageInMonths > 24 ) {
1012 $age = intval($ageInMonths/12);
1015 $age = "$ageInMonths month";
1020 function dateToDB ($date)
1022 $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1027 // ----------------------------------------------------------------------------
1029 * DROPDOWN FOR COUNTRIES
1031 * build a dropdown with all countries from geo_country_reference
1033 * @param int $selected - id for selected record
1034 * @param string $name - the name/id for select form
1035 * @return void - just echo the html encoded string
1037 function dropdown_countries($selected = 0, $name = 'country_code') {
1038 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1040 $string = "<select name='$name' id='$name'>";
1041 while ( $row = sqlFetchArray($r) ) {
1042 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1043 $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1046 $string .= '</select>';
1051 // ----------------------------------------------------------------------------
1053 * DROPDOWN FOR YES/NO
1055 * build a dropdown with two options (yes - 1, no - 0)
1057 * @param int $selected - id for selected record
1058 * @param string $name - the name/id for select form
1059 * @return void - just echo the html encoded string
1061 function dropdown_yesno($selected = 0, $name = 'yesno') {
1062 $string = "<select name='$name' id='$name'>";
1064 $selected = (int)$selected;
1065 if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1066 else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1068 $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1069 $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1070 $string .= '</select>';
1075 // ----------------------------------------------------------------------------
1077 * DROPDOWN FOR MALE/FEMALE options
1079 * build a dropdown with three options (unselected/male/female)
1081 * @param int $selected - id for selected record
1082 * @param string $name - the name/id for select form
1083 * @return void - just echo the html encoded string
1085 function dropdown_sex($selected = 0, $name = 'sex') {
1086 $string = "<select name='$name' id='$name'>";
1088 if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1089 else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1090 else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1092 $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1093 $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1094 $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1095 $string .= '</select>';
1100 // ----------------------------------------------------------------------------
1102 * DROPDOWN FOR MARITAL STATUS
1104 * build a dropdown with marital status
1106 * @param int $selected - id for selected record
1107 * @param string $name - the name/id for select form
1108 * @return void - just echo the html encoded string
1110 function dropdown_marital($selected = 0, $name = 'status') {
1111 $string = "<select name='$name' id='$name'>";
1113 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1115 foreach ( $statii as $st ) {
1116 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1117 $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1120 $string .= '</select>';
1125 // ----------------------------------------------------------------------------
1127 * DROPDOWN FOR PROVIDERS
1129 * build a dropdown with all providers
1131 * @param int $selected - id for selected record
1132 * @param string $name - the name/id for select form
1133 * @return void - just echo the html encoded string
1135 function dropdown_providers($selected = 0, $name = 'status') {
1136 $provideri = getProviderInfo();
1138 $string = "<select name='$name' id='$name'>";
1139 $string .= '<option value="">' .xl('Unassigned'). '</option>';
1140 foreach ( $provideri as $s ) {
1141 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1142 $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1145 $string .= '</select>';
1150 // ----------------------------------------------------------------------------
1152 * DROPDOWN FOR INSURANCE COMPANIES
1154 * build a dropdown with all insurers
1156 * @param int $selected - id for selected record
1157 * @param string $name - the name/id for select form
1158 * @return void - just echo the html encoded string
1160 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1161 $insurancei = getInsuranceProviders();
1163 $string = "<select name='$name' id='$name'>";
1164 $string .= '<option value="0">Onbekend</option>';
1165 foreach ( $insurancei as $iid => $iname ) {
1166 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1167 $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1170 $string .= '</select>';
1176 // ----------------------------------------------------------------------------
1180 * return the name or the country code, function of arguments
1182 * @param int $country_code
1183 * @param string $country_name
1184 * @return string | int - name or code
1186 function country_code($country_code = 0, $country_name = '') {
1188 if ( $country_code ) {
1189 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1191 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1194 $db = $GLOBALS['adodb']['db'];
1195 $result = $db->Execute($sql);
1196 if ($result && !$result->EOF) {
1197 $strint = $result->fields['res'];
1203 // ----------------------------------------------------------------------------
1205 * GET INSURANCE DATA
1208 * return the insurer(s) and some patient
1210 * @param int $pid - patient id
1211 * @param int $current 1-current 0-all insurers
1214 function get_insurers_nl($pid = 0, $current = 1) {
1215 if ( !$pid ) return FALSE;
1217 $join = 'insurance_companies ic ON ic.id = pi.pin_provider';
1218 $r = dsql_select('*', 'patient_insurers_NL pi', array('pin_pid' => $pid), 'pin_date DESC', $join);
1220 while ( $row = mysql_fetch_array($r) ) {
1224 return ( $current ? $rez[0] : $rez );
1228 // ----------------------------------------------------------------------------
1230 * SET INSURANCE DATA
1233 * set the insurer for a patient
1235 * @param int $pid - patient id
1236 * @param int $insid - insurer id
1239 function set_insurer_nl($pid = 0, $insid = 0, $date = '', $policy = '') {
1240 if ( !$pid || !$insid || ($date == '0000-00-00') ) return FALSE;
1242 $fields = array('pin_pid', 'pin_provider', 'pin_date', 'pin_policy');
1243 $values = array($pid, $insid, $date, $policy);
1244 dsql_insert('patient_insurers_NL', $fields, $values);
1247 // ----------------------------------------------------------------------------
1249 * FIND THE INSURERS STATUS FOR A PATIENT
1252 * return the answer for the question: is this the first insurer or not?
1254 * @param int $pid - patient id
1255 * @return int - the number of insurer records ( 0 - no insurer; >0 some insurers)
1257 function total_insurers($pid = 0) {
1258 if ( !$pid ) return FALSE;
1260 $r = dsql_select('COUNT(*) AS c', 'patient_insurers_NL', array('pin_pid' => $pid));
1261 $row = mysql_fetch_array($r);
1267 function DBToDate ($date)
1269 $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);