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 AND ( info IS NULL OR info NOT LIKE '%Nocalendar%' ) ";
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 // sort by last name -- JRM June 2008
166 $query .= " ORDER BY lname, fname ";
167 $rez = sqlStatement($query);
168 for($iter=0; $row=sqlFetchArray($rez); $iter++)
169 $returnval[$iter]=$row;
171 //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
172 //accessible from $resultval['key']
175 $akeys = array_keys($returnval[0]);
176 foreach($akeys as $key) {
178 $returnval[0][$key] = $returnval[0][$key];
184 //same as above but does not reduce if only 1 row returned
185 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
187 if ($providers_only) {
188 $param1 = "AND authorized=1";
191 if ($providerID == "%") {
194 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
195 "from users where active = 1 and username != '' and id $command '" .
196 mysql_real_escape_string($providerID) . "' " . $param1;
198 $rez = sqlStatement($query);
199 for($iter=0; $row=sqlFetchArray($rez); $iter++)
200 $returnval[$iter]=$row;
205 function getProviderName($providerID) {
206 $pi = getProviderInfo($providerID);
207 if (strlen($pi[0]["lname"]) > 0) {
208 return $pi[0]['fname'] . " " . $pi[0]['lname'];
213 function getProviderId($providerName) {
214 $query = "select id from users where username = '". mysql_real_escape_string($providerName)."'";
215 $rez = sqlStatement($query);
216 for($iter=0; $row=sqlFetchArray($rez); $iter++)
217 $returnval[$iter]=$row;
221 function getEthnoRacials() {
222 $returnval = array("");
223 $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
224 $rez = sqlStatement($sql);
225 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
226 if (($row["ethnoracial"] != "")) {
227 array_push($returnval, $row["ethnoracial"]);
233 function getHistoryData($pid, $given = "*")
235 $sql = "select $given from history_data where pid='$pid' order by date DESC limit 0,1";
236 return sqlQuery($sql);
239 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
240 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
242 $sql = "select $given from insurance_data as insd " .
243 "left join insurance_companies as ic on ic.id = insd.provider " .
244 "where pid = '$pid' and type = '$type' order by date DESC limit 1";
245 return sqlQuery($sql);
248 function getInsuranceDataByDate($pid, $date, $type,
249 $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
250 { // this must take the date in the following manner: YYYY-MM-DD
251 // this function recalls the insurance value that was most recently enterred from the
252 // given date. it will call up most recent records up to and on the date given,
253 // but not records enterred after the given date
254 $sql = "select $given from insurance_data as insd " .
255 "left join insurance_companies as ic on ic.id = provider " .
256 "where pid = '$pid' and date_format(date,'%Y-%m-%d') <= '$date' and " .
257 "type='$type' order by date DESC limit 1";
258 return sqlQuery($sql);
261 function getEmployerData($pid, $given = "*")
263 $sql = "select $given from employer_data where pid='$pid' order by date DESC limit 0,1";
264 return sqlQuery($sql);
267 function _set_patient_inc_count($limit, $count, $where) {
268 // When the limit is exceeded, find out what the unlimited count would be.
269 $GLOBALS['PATIENT_INC_COUNT'] = $count;
270 if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
271 $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where");
272 $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
276 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")
278 // Allow the last name to be followed by a comma and some part of a first name.
279 // New behavior for searches:
280 // Allows comma alone followed by some part of a first name
281 // If the first letter of either name is capital, searches for name starting
282 // with given substring (the expected behavior). If it is lower case, it
283 // it searches for the substring anywhere in the name. This applies to either
284 // last name or first name or both. The arbitrary limit of 100 results is set
285 // in the sql query below. --Mark Leeds
286 $lname = trim($lname);
288 if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
289 $lname = trim($matches[1]);
290 $fname = trim($matches[2]);
292 $search_for_pieces1 = '';
293 $search_for_pieces2 = '';
294 if ($lname{0} != strtoupper($lname{0})) {$search_for_pieces1 = '%';}
295 if ($fname{0} != strtoupper($fname{0})) {$search_for_pieces2 = '%';}
297 $where = "lname LIKE '" . $search_for_pieces1 . "$lname%' " .
298 "AND fname LIKE '" . $search_for_pieces2 . "$fname%'";
299 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
300 if ($limit != "all") $sql .= " LIMIT $start, $limit";
302 $rez = sqlStatement($sql);
304 for($iter=0; $row=sqlFetchArray($rez); $iter++)
305 $returnval[$iter] = $row;
307 _set_patient_inc_count($limit, count($returnval), $where);
311 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")
313 $where = "pubpid LIKE '$pid%'";
314 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
315 if ($limit != "all") $sql .= " limit $start, $limit";
316 $rez = sqlStatement($sql);
317 for($iter=0; $row=sqlFetchArray($rez); $iter++)
318 $returnval[$iter]=$row;
320 _set_patient_inc_count($limit, count($returnval), $where);
324 // return a collection of Patient PIDs
325 // new arg style by JRM March 2008
326 // 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")
327 function getPatientPID($args)
330 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
331 $orderby = "lname ASC, fname ASC";
335 // alter default values if defined in the passed in args
336 if (isset($args['pid'])) { $pid = $args['pid']; }
337 if (isset($args['given'])) { $given = $args['given']; }
338 if (isset($args['orderby'])) { $orderby = $args['orderby']; }
339 if (isset($args['limit'])) { $limit = $args['limit']; }
340 if (isset($args['start'])) { $start = $args['start']; }
343 if ($pid == -1) $pid = "%";
344 elseif (empty($pid)) $pid = "NULL";
346 if (strstr($pid,"%")) $command = "like";
348 $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
349 if ($limit != "all") $sql .= " limit $start, $limit";
351 $rez = sqlStatement($sql);
352 for($iter=0; $row=sqlFetchArray($rez); $iter++)
353 $returnval[$iter]=$row;
358 /* return a patient's name in the format LAST, FIRST */
359 function getPatientName($pid) {
360 if (empty($pid)) return "";
361 $patientData = getPatientPID(array("pid"=>$pid));
362 if (empty($patientData[0]['lname'])) return "";
363 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
367 /* find patient data by DOB */
368 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
370 $DOB = fixDate($DOB, $DOB);
371 $where = "DOB like '$DOB%'";
372 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
373 if ($limit != "all") $sql .= " LIMIT $start, $limit";
375 $rez = sqlStatement($sql);
376 for($iter=0; $row=sqlFetchArray($rez); $iter++)
377 $returnval[$iter]=$row;
379 _set_patient_inc_count($limit, count($returnval), $where);
383 /* find patient data by SSN */
384 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
386 $where = "ss LIKE '$ss%'";
387 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
388 if ($limit != "all") $sql .= " LIMIT $start, $limit";
390 $rez = sqlStatement($sql);
391 for($iter=0; $row=sqlFetchArray($rez); $iter++)
392 $returnval[$iter]=$row;
394 _set_patient_inc_count($limit, count($returnval), $where);
398 //(CHEMED) Search by phone number
399 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
401 $phone = ereg_replace( "[[:punct:]]","", $phone );
402 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP '$phone'";
403 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
404 if ($limit != "all") $sql .= " LIMIT $start, $limit";
406 $rez = sqlStatement($sql);
407 for($iter=0; $row=sqlFetchArray($rez); $iter++)
408 $returnval[$iter]=$row;
410 _set_patient_inc_count($limit, count($returnval), $where);
414 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
416 $sql="select $given from patient_data order by $orderby";
419 $sql .= " limit $start, $limit";
421 $rez = sqlStatement($sql);
422 for($iter=0; $row=sqlFetchArray($rez); $iter++)
423 $returnval[$iter]=$row;
428 //----------------------input functions
429 function newPatientData( $db_id="",
452 $contact_relationship = "",
459 $migrantseasonal = "",
461 $monthly_income = "",
463 $financial_review = "",
476 $drivers_license = "",
482 $prefixlastpartner = "",
485 $provider_data = array(),
486 $referer_data = array()
491 $DOB = fixDate($DOB);
492 $regdate = fixDate($regdate);
495 $referral_source = '';
497 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
498 // Check for brain damage:
499 if ($db_id != $rez['id']) {
500 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
501 $rez['id'] . "' to '$db_id' for pid '$pid'";
504 $fitness = $rez['fitness'];
505 $referral_source = $rez['referral_source'];
508 // Get the default price level.
509 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
510 "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
511 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
513 $query = ("replace into patient_data set
522 postal_code='$postal_code',
525 country_code='$country_code',
526 drivers_license='$drivers_license',
528 occupation='$occupation',
529 phone_home='$phone_home',
530 phone_biz='$phone_biz',
531 phone_contact='$phone_contact',
533 contact_relationship='$contact_relationship',
534 referrer='$referrer',
535 referrerID='$referrerID',
537 language='$language',
538 ethnoracial='$ethnoracial',
539 interpretter='$interpretter',
540 migrantseasonal='$migrantseasonal',
541 family_size='$family_size',
542 monthly_income='$monthly_income',
543 homeless='$homeless',
544 financial_review='$financial_review',
547 providerID = '$providerID',
548 genericname1 = '$genericname1',
549 genericval1 = '$genericval1',
550 genericname2 = '$genericname2',
551 genericval2 = '$genericval2',
552 phone_cell = '$phone_cell',
553 pharmacy_id = '$pharmacy_id',
554 hipaa_mail = '$hipaa_mail',
555 hipaa_voice = '$hipaa_voice',
556 hipaa_notice = '$hipaa_notice',
557 hipaa_message = '$hipaa_message',
560 referral_source='$referral_source',
562 pricelevel='$pricelevel',
565 $id = sqlInsert($query);
569 // find the last inserted id for new patient case
570 $db_id = empty($GLOBALS['dutchpc']) ? mysql_insert_id() : dsql_lastid();
574 $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
577 if ( $GLOBALS['dutchpc'] ) {
578 $init = strtoupper(preg_replace('/[\s\.\-_0-9]/','',$initials));
580 $querynl = ("REPLACE INTO patient_data_NL SET
582 pdn_pxlast = '$prefixlast',
583 pdn_pxlastpar = '$prefixlastpartner',
584 pdn_lastpar = '$lastpartner',
585 pdn_street = '$nstreet',
587 pdn_addition = '$nadd',
588 pdn_initials = '$init'
591 if ( $db_id ) $idnl = sqlInsert($querynl); // only if exists
598 if ( $GLOBALS['dutchpc'] && $db_id && $provider_data && $referer_data) {
599 $querypr = ("INSERT INTO cl_providers(pro_pid, pro_company, pro_initials, pro_prefix, pro_lname,
600 pro_street, pro_number, pro_addition, pro_city, pro_zipcode, pro_phone, pro_fax, pro_email, pro_referer )
601 VALUES ($db_id, '{$provider_data['pro_company']}', '{$provider_data['pro_initials']}',
602 '{$provider_data['pro_prefix']}', '{$provider_data['pro_lname']}',
603 '{$provider_data['pro_street']}', '{$provider_data['pro_number']}', '{$provider_data['pro_addition']}',
604 '{$provider_data['pro_city']}', '{$provider_data['pro_zipcode']}',
605 '{$provider_data['pro_phone']}', '{$provider_data['pro_fax']}', '{$provider_data['pro_email']}',
606 '{$provider_data['pro_referer']}')
607 ON DUPLICATE KEY UPDATE pro_referer = '{$provider_data['pro_referer']}',
608 pro_company = '{$provider_data['pro_company']}', pro_initials = '{$provider_data['pro_initials']}',
609 pro_prefix = '{$provider_data['pro_prefix']}',
610 pro_lname = '{$provider_data['pro_lname']}', pro_street = '{$provider_data['pro_street']}',
611 pro_number = '{$provider_data['pro_number']}', pro_addition = '{$provider_data['pro_addition']}',
612 pro_city = '{$provider_data['pro_city']}', pro_zipcode = '{$provider_data['pro_zipcode']}',
613 pro_phone = '{$provider_data['pro_phone']}', pro_fax = '{$provider_data['pro_fax']}',
614 pro_email = '{$provider_data['pro_email']}'
616 $idpr = sqlInsert($querypr);
618 // referer if it's the case
619 if ( $referer_data['ref_code'] ) {
620 $queryre = ("INSERT INTO cl_referers(ref_pid, ref_code, ref_company, ref_initials, ref_prefix,
621 ref_lname, ref_street, ref_number, ref_addition, ref_city, ref_zipcode, ref_phone, ref_fax,
623 VALUES ($db_id, {$referer_data['ref_code']}, '{$referer_data['ref_company']}',
624 '{$referer_data['ref_initials']}', '{$referer_data['ref_prefix']}',
625 '{$referer_data['ref_lname']}', '{$referer_data['ref_street']}', '{$referer_data['ref_number']}',
626 '{$referer_data['ref_addition']}', '{$referer_data['ref_city']}', '{$referer_data['ref_zipcode']}',
627 '{$referer_data['ref_phone']}', '{$referer_data['ref_fax']}', '{$referer_data['ref_email']}')
628 ON DUPLICATE KEY UPDATE ref_code = {$referer_data['ref_code']},
629 ref_company = '{$referer_data['ref_company']}', ref_initials = '{$referer_data['ref_initials']}',
630 ref_prefix = '{$referer_data['ref_prefix']}',
631 ref_lname = '{$referer_data['ref_lname']}', ref_street = '{$referer_data['ref_street']}',
632 ref_number = '{$referer_data['ref_number']}', ref_addition = '{$referer_data['ref_addition']}',
633 ref_city = '{$referer_data['ref_city']}', ref_zipcode = '{$referer_data['ref_zipcode']}',
634 ref_phone = '{$referer_data['ref_phone']}', ref_fax = '{$referer_data['ref_fax']}',
635 ref_email = '{$referer_data['ref_email']}'
637 $idre = sqlInsert($queryre);
642 sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
643 $phone_biz,$phone_cell,$email,$pid);
648 // Supported input date formats are:
650 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
652 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
654 function fixDate($date, $default="0000-00-00") {
655 $fixed_date = $default;
657 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
658 $dmy = preg_split("'[/.-]'", $date);
660 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
662 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
663 if ($dmy[2] < 1000) $dmy[2] += 1900;
664 if ($dmy[2] < 1910) $dmy[2] += 100;
666 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
673 // Create or update patient data from an array.
675 function updatePatientData($pid, $new, $create=false)
677 /*******************************************************************
678 $real = getPatientData($pid);
679 $new['DOB'] = fixDate($new['DOB']);
680 while(list($key, $value) = each ($new))
681 $real[$key] = $value;
682 $real['date'] = "'+NOW()+'";
684 $sql = "insert into patient_data set ";
685 while(list($key, $value) = each($real))
686 $sql .= $key." = '$value', ";
687 $sql = substr($sql, 0, -2);
688 return sqlInsert($sql);
689 *******************************************************************/
691 // The above was broken, though seems intent to insert a new patient_data
692 // row for each update. A good idea, but nothing is doing that yet so
693 // the code below does not yet attempt it.
695 $new['DOB'] = fixDate($new['DOB']);
698 $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
699 foreach ($new as $key => $value) {
700 if ($key == 'id') continue;
701 $sql .= ", $key = '$value'";
703 $db_id = sqlInsert($sql);
707 $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
708 // Check for brain damage:
709 if ($pid != $rez['pid']) {
710 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
711 $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
714 $sql = "UPDATE patient_data SET date = NOW()";
715 foreach ($new as $key => $value) {
716 $sql .= ", $key = '$value'";
718 $sql .= " WHERE id = '$db_id'";
722 $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
723 sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
724 $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
725 $rez['phone_cell'],$rez['email'],$rez['pid']);
730 function newEmployerData( $pid,
739 return sqlInsert("insert into employer_data set
742 postal_code='$postal_code',
751 // Create or update employer data from an array.
753 function updateEmployerData($pid, $new, $create=false)
755 $colnames = array('name','street','city','state','postal_code','country');
758 $set .= "pid = '$pid', date = NOW()";
759 foreach ($colnames as $key) {
760 $value = isset($new[$key]) ? $new[$key] : '';
761 $set .= ", $key = '$value'";
763 return sqlInsert("INSERT INTO employer_data SET $set");
767 $old = getEmployerData($pid);
769 foreach ($colnames as $key) {
770 $value = empty($old[$key]) ? '' : addslashes($old[$key]);
771 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
775 $set .= "$key = '$value', ";
778 $set .= "pid = '$pid', date = NOW()";
779 return sqlInsert("INSERT INTO employer_data SET $set");
785 // This updates or adds the given insurance data info, while retaining any
786 // previously added insurance_data rows that should be preserved.
787 // This does not directly support the maintenance of non-current insurance.
789 function newInsuranceData(
796 $subscriber_lname = "",
797 $subscriber_mname = "",
798 $subscriber_fname = "",
799 $subscriber_relationship = "",
801 $subscriber_DOB = "",
802 $subscriber_street = "",
803 $subscriber_postal_code = "",
804 $subscriber_city = "",
805 $subscriber_state = "",
806 $subscriber_country = "",
807 $subscriber_phone = "",
808 $subscriber_employer = "",
809 $subscriber_employer_street = "",
810 $subscriber_employer_city = "",
811 $subscriber_employer_postal_code = "",
812 $subscriber_employer_state = "",
813 $subscriber_employer_country = "",
815 $subscriber_sex = "",
816 $effective_date = "0000-00-00",
817 $accept_assignment = "TRUE")
819 if (strlen($type) <= 0) return FALSE;
821 // If a bad date was passed, err on the side of caution.
822 $effective_date = fixDate($effective_date, date('Y-m-d'));
824 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
825 "pid = '$pid' AND type = '$type' ORDER BY date DESC");
826 $idrow = sqlFetchArray($idres);
828 // Replace the most recent entry in any of the following cases:
829 // * Its effective date is >= this effective date.
830 // * It is the first entry and it has no (insurance) provider.
831 // * There is no encounter that is earlier than the new effective date but
832 // on or after the old effective date.
833 // Otherwise insert a new entry.
837 if (strcmp($idrow['date'], $effective_date) > 0) {
841 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
845 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
846 "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
847 "date >= '" . $idrow['date'] . " 00:00:00'");
848 if ($ferow['count'] == 0) $replace = true;
855 // TBD: This is a bit dangerous in that a typo in entering the effective
856 // date can wipe out previous insurance history. So we want some data
857 // entry validation somewhere.
858 sqlStatement("DELETE FROM insurance_data WHERE " .
859 "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
860 "id != " . $idrow['id']);
863 $data['type'] = $type;
864 $data['provider'] = $provider;
865 $data['policy_number'] = $policy_number;
866 $data['group_number'] = $group_number;
867 $data['plan_name'] = $plan_name;
868 $data['subscriber_lname'] = $subscriber_lname;
869 $data['subscriber_mname'] = $subscriber_mname;
870 $data['subscriber_fname'] = $subscriber_fname;
871 $data['subscriber_relationship'] = $subscriber_relationship;
872 $data['subscriber_ss'] = $subscriber_ss;
873 $data['subscriber_DOB'] = $subscriber_DOB;
874 $data['subscriber_street'] = $subscriber_street;
875 $data['subscriber_postal_code'] = $subscriber_postal_code;
876 $data['subscriber_city'] = $subscriber_city;
877 $data['subscriber_state'] = $subscriber_state;
878 $data['subscriber_country'] = $subscriber_country;
879 $data['subscriber_phone'] = $subscriber_phone;
880 $data['subscriber_employer'] = $subscriber_employer;
881 $data['subscriber_employer_city'] = $subscriber_employer_city;
882 $data['subscriber_employer_street'] = $subscriber_employer_street;
883 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
884 $data['subscriber_employer_state'] = $subscriber_employer_state;
885 $data['subscriber_employer_country'] = $subscriber_employer_country;
886 $data['copay'] = $copay;
887 $data['subscriber_sex'] = $subscriber_sex;
889 $data['date'] = $effective_date;
890 $data['accept_assignment'] = $accept_assignment;
891 updateInsuranceData($idrow['id'], $data);
895 return sqlInsert("INSERT INTO insurance_data SET
897 provider = '$provider',
898 policy_number = '$policy_number',
899 group_number = '$group_number',
900 plan_name = '$plan_name',
901 subscriber_lname = '$subscriber_lname',
902 subscriber_mname = '$subscriber_mname',
903 subscriber_fname = '$subscriber_fname',
904 subscriber_relationship = '$subscriber_relationship',
905 subscriber_ss = '$subscriber_ss',
906 subscriber_DOB = '$subscriber_DOB',
907 subscriber_street = '$subscriber_street',
908 subscriber_postal_code = '$subscriber_postal_code',
909 subscriber_city = '$subscriber_city',
910 subscriber_state = '$subscriber_state',
911 subscriber_country = '$subscriber_country',
912 subscriber_phone = '$subscriber_phone',
913 subscriber_employer = '$subscriber_employer',
914 subscriber_employer_city = '$subscriber_employer_city',
915 subscriber_employer_street = '$subscriber_employer_street',
916 subscriber_employer_postal_code = '$subscriber_employer_postal_code',
917 subscriber_employer_state = '$subscriber_employer_state',
918 subscriber_employer_country = '$subscriber_employer_country',
920 subscriber_sex = '$subscriber_sex',
922 date = '$effective_date',
923 accept_assignment = '$accept_assignment'
928 // This is used internally only.
929 function updateInsuranceData($id, $new)
931 $fields = sqlListFields("insurance_data");
934 while(list($key, $value) = each ($new)) {
935 if (in_array($key, $fields)) {
940 $sql = "UPDATE insurance_data SET ";
941 while(list($key, $value) = each($use))
942 $sql .= $key . " = '$value', ";
943 $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
948 function newHistoryData($pid, $new=false) {
949 $sql = "insert into history_data set pid = '$pid', date = NOW()";
951 while(list($key, $value) = each($new)) {
952 if (!get_magic_quotes_gpc()) $value = addslashes($value);
953 $sql .= ", $key = '$value'";
956 return sqlInsert($sql);
959 function updateHistoryData($pid,$new)
961 $real = getHistoryData($pid);
962 while(list($key, $value) = each ($new))
963 $real[$key] = $value;
964 $real['date'] = "'+NOW()+'";
967 $sql = "insert into history_data set ";
968 while(list($key, $value) = each($real))
969 $sql .= $key." = '$value', ";
970 $sql = substr($sql, 0, -2);
973 return sqlInsert($sql);
976 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
977 $phone_biz,$phone_cell,$email,$pid="")
979 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
980 if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
982 $db = $GLOBALS['adodb']['db'];
983 $customer_info = array();
985 $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
986 $result = $db->Execute($sql);
987 if ($result && !$result->EOF) {
988 $customer_info['foreign_update'] = true;
989 $customer_info['foreign_id'] = $result->fields['foreign_id'];
990 $customer_info['foreign_table'] = $result->fields['foreign_table'];
993 ///xml rpc code to connect to accounting package and add user to it
994 $customer_info['firstname'] = $fname;
995 $customer_info['lastname'] = $lname;
996 $customer_info['address'] = $street;
997 $customer_info['suburb'] = $city;
998 $customer_info['state'] = $state;
999 $customer_info['postcode'] = $postal_code;
1001 //ezybiz wants state as a code rather than abbreviation
1002 $customer_info['geo_zone_id'] = "";
1003 $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1004 $db = $GLOBALS['adodb']['db'];
1005 $result = $db->Execute($sql);
1006 if ($result && !$result->EOF) {
1007 $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1010 //ezybiz wants country as a code rather than abbreviation
1011 $customer_info['geo_country_id'] = "";
1012 $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1013 $db = $GLOBALS['adodb']['db'];
1014 $result = $db->Execute($sql);
1015 if ($result && !$result->EOF) {
1016 $customer_info['geo_country_id'] = $result->fields['countries_id'];
1019 $customer_info['phone1'] = $phone_home;
1020 $customer_info['phone1comment'] = "Home Phone";
1021 $customer_info['phone2'] = $phone_biz;
1022 $customer_info['phone2comment'] = "Business Phone";
1023 $customer_info['phone3'] = $phone_cell;
1024 $customer_info['phone3comment'] = "Cell Phone";
1025 $customer_info['email'] = $email;
1026 $customer_info['customernumber'] = $pid;
1028 $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1029 $ws = new WSWrapper($function);
1031 // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1032 if (is_numeric($ws->value)) {
1033 $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1034 $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1039 // in months if < 2 years old
1040 // in years if > 2 years old
1041 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1042 // (optional) nowYMD is a date in YYYYMMDD format
1043 function getPatientAge($dobYMD, $nowYMD=null)
1045 // strip any dashes from the DOB
1046 $dobYMD = preg_replace("/-/", "", $dobYMD);
1047 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1049 // set the 'now' date values
1050 if ($nowYMD == null) {
1051 $nowDay = date("d");
1052 $nowMonth = date("m");
1053 $nowYear = date("Y");
1056 $nowDay = substr($nowYMD,6,2);
1057 $nowMonth = substr($nowYMD,4,2);
1058 $nowYear = substr($nowYMD,0,4);
1061 $dayDiff = $nowDay - $dobDay;
1062 $monthDiff = $nowMonth - $dobMonth;
1063 $yearDiff = $nowYear - $dobYear;
1065 $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1067 if ( $ageInMonths > 24 ) {
1069 if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1070 else if ($monthDiff < 0) { $age -= 1; }
1073 $age = "$ageInMonths month";
1079 function dateToDB ($date)
1081 $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1086 // ----------------------------------------------------------------------------
1088 * DROPDOWN FOR COUNTRIES
1090 * build a dropdown with all countries from geo_country_reference
1092 * @param int $selected - id for selected record
1093 * @param string $name - the name/id for select form
1094 * @return void - just echo the html encoded string
1096 function dropdown_countries($selected = 0, $name = 'country_code') {
1097 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1099 $string = "<select name='$name' id='$name'>";
1100 while ( $row = sqlFetchArray($r) ) {
1101 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1102 $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1105 $string .= '</select>';
1110 // ----------------------------------------------------------------------------
1112 * DROPDOWN FOR YES/NO
1114 * build a dropdown with two options (yes - 1, no - 0)
1116 * @param int $selected - id for selected record
1117 * @param string $name - the name/id for select form
1118 * @return void - just echo the html encoded string
1120 function dropdown_yesno($selected = 0, $name = 'yesno') {
1121 $string = "<select name='$name' id='$name'>";
1123 $selected = (int)$selected;
1124 if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1125 else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1127 $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1128 $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1129 $string .= '</select>';
1134 // ----------------------------------------------------------------------------
1136 * DROPDOWN FOR MALE/FEMALE options
1138 * build a dropdown with three options (unselected/male/female)
1140 * @param int $selected - id for selected record
1141 * @param string $name - the name/id for select form
1142 * @return void - just echo the html encoded string
1144 function dropdown_sex($selected = 0, $name = 'sex') {
1145 $string = "<select name='$name' id='$name'>";
1147 if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1148 else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1149 else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1151 $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1152 $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1153 $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1154 $string .= '</select>';
1159 // ----------------------------------------------------------------------------
1161 * DROPDOWN FOR MARITAL STATUS
1163 * build a dropdown with marital status
1165 * @param int $selected - id for selected record
1166 * @param string $name - the name/id for select form
1167 * @return void - just echo the html encoded string
1169 function dropdown_marital($selected = 0, $name = 'status') {
1170 $string = "<select name='$name' id='$name'>";
1172 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1174 foreach ( $statii as $st ) {
1175 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1176 $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1179 $string .= '</select>';
1184 // ----------------------------------------------------------------------------
1186 * DROPDOWN FOR PROVIDERS
1188 * build a dropdown with all providers
1190 * @param int $selected - id for selected record
1191 * @param string $name - the name/id for select form
1192 * @return void - just echo the html encoded string
1194 function dropdown_providers($selected = 0, $name = 'status') {
1195 $provideri = getProviderInfo();
1197 $string = "<select name='$name' id='$name'>";
1198 $string .= '<option value="">' .xl('Unassigned'). '</option>';
1199 foreach ( $provideri as $s ) {
1200 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1201 $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1204 $string .= '</select>';
1209 // ----------------------------------------------------------------------------
1211 * DROPDOWN FOR INSURANCE COMPANIES
1213 * build a dropdown with all insurers
1215 * @param int $selected - id for selected record
1216 * @param string $name - the name/id for select form
1217 * @return void - just echo the html encoded string
1219 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1220 $insurancei = getInsuranceProviders();
1222 $string = "<select name='$name' id='$name'>";
1223 $string .= '<option value="0">Onbekend</option>';
1224 foreach ( $insurancei as $iid => $iname ) {
1225 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1226 $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1229 $string .= '</select>';
1235 // ----------------------------------------------------------------------------
1239 * return the name or the country code, function of arguments
1241 * @param int $country_code
1242 * @param string $country_name
1243 * @return string | int - name or code
1245 function country_code($country_code = 0, $country_name = '') {
1247 if ( $country_code ) {
1248 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1250 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1253 $db = $GLOBALS['adodb']['db'];
1254 $result = $db->Execute($sql);
1255 if ($result && !$result->EOF) {
1256 $strint = $result->fields['res'];
1262 // ----------------------------------------------------------------------------
1264 * GET INSURANCE DATA
1267 * return the insurer(s) and some patient
1269 * @param int $pid - patient id
1270 * @param int $current 1-current 0-all insurers
1273 function get_insurers_nl($pid = 0, $current = 1) {
1274 if ( !$pid ) return FALSE;
1276 $join = 'insurance_companies ic ON ic.id = pi.pin_provider';
1277 $r = dsql_select('*', 'patient_insurers_NL pi', array('pin_pid' => $pid), 'pin_date DESC', $join);
1279 while ( $row = mysql_fetch_array($r) ) {
1283 return ( $current ? $rez[0] : $rez );
1287 // ----------------------------------------------------------------------------
1289 * SET INSURANCE DATA
1292 * set the insurer for a patient
1294 * @param int $pid - patient id
1295 * @param int $insid - insurer id
1298 function set_insurer_nl($pid = 0, $insid = 0, $date = '', $policy = '') {
1299 if ( !$pid || !$insid || ($date == '0000-00-00') ) return FALSE;
1301 $fields = array('pin_pid', 'pin_provider', 'pin_date', 'pin_policy');
1302 $values = array($pid, $insid, $date, $policy);
1303 dsql_insert('patient_insurers_NL', $fields, $values);
1306 // ----------------------------------------------------------------------------
1308 * FIND THE INSURERS STATUS FOR A PATIENT
1311 * return the answer for the question: is this the first insurer or not?
1313 * @param int $pid - patient id
1314 * @return int - the number of insurer records ( 0 - no insurer; >0 some insurers)
1316 function total_insurers($pid = 0) {
1317 if ( !$pid ) return FALSE;
1319 $r = dsql_select('COUNT(*) AS c', 'patient_insurers_NL', array('pin_pid' => $pid));
1320 $row = mysql_fetch_array($r);
1325 function DBToDate ($date)
1327 $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1331 function get_patient_balance($pid) {
1332 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1333 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1334 "pid = '$pid' AND activity = 1");
1335 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1337 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1338 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1340 return sprintf('%01.2f', $brow['amount'] + $srow['amount']
1341 - $drow['payments'] - $drow['adjustments']);
1343 else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1344 // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1345 $conn = $GLOBALS['adodb']['db'];
1346 $customer_info['id'] = 0;
1347 $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1348 "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1349 "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1350 "im.foreign_table = 'customer'";
1351 $result = $conn->Execute($sql);
1352 if($result && !$result->EOF) {
1353 $customer_info['id'] = $result->fields['foreign_id'];
1355 $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1356 $ws = new WSWrapper($function);
1357 if(is_numeric($ws->value)) {
1358 return sprintf('%01.2f', $ws->value);