2 // This program is free software; you can redistribute it and/or
3 // modify it under the terms of the GNU General Public License
4 // as published by the Free Software Foundation; either version 2
5 // of the License, or (at your option) any later version.
7 include_once("{$GLOBALS['srcdir']}/sql.inc");
8 require_once(dirname(__FILE__) . "/classes/WSWrapper.class.php");
9 require_once("{$GLOBALS['srcdir']}/formdata.inc.php");
11 // These are for sports team use:
12 $PLAYER_FITNESSES = array(
15 xl('Restricted Training'),
19 xl('International Duty')
21 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
23 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS") {
24 $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
25 return sqlQuery($sql, array($pid) );
28 function getLanguages() {
29 $returnval = array('','english');
30 $sql = "select distinct lower(language) as language from patient_data";
31 $rez = sqlStatement($sql);
32 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
33 if (($row["language"] != "english") && ($row["language"] != "")) {
34 array_push($returnval, $row["language"]);
40 function getInsuranceProviders() {
44 $sql = "select name, id from insurance_companies order by name, id";
45 $rez = sqlStatement($sql);
46 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
47 $returnval[$row['id']] = $row['name'];
51 // Please leave this here. I have a user who wants to see zip codes and PO
52 // box numbers listed along with the insurance company names, as many companies
53 // have different billing addresses for different plans. -- Rod Roark
56 $sql = "select insurance_companies.name, insurance_companies.id, " .
57 "addresses.zip, addresses.line1 " .
58 "from insurance_companies, addresses " .
59 "where addresses.foreign_id = insurance_companies.id " .
60 "order by insurance_companies.name, addresses.zip";
62 $rez = sqlStatement($sql);
64 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
65 preg_match("/\d+/", $row['line1'], $matches);
66 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
67 "," . $matches[0] . ")";
74 function getProviders() {
75 $returnval = array("");
76 $sql = "select fname, lname from users where authorized = 1 and " .
77 "active = 1 and username != ''";
78 $rez = sqlStatement($sql);
79 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
80 if (($row["fname"] != "") && ($row["lname"] != "")) {
81 array_push($returnval, $row["fname"] . " " . $row["lname"]);
87 // ----------------------------------------------------------------------------
88 // Get one facility row. If the ID is not specified, then get either the
89 // "main" (billing) facility, or the default facility of the currently
90 // logged-in user. This was created to support genFacilityTitle() but
91 // may find additional uses.
93 function getFacility($facid=0) {
95 //create a sql binding array
96 $sqlBindArray = array();
99 $query = "SELECT * FROM facility WHERE id = ?";
100 array_push($sqlBindArray,$facid);
102 else if ($facid == 0) {
103 $query = "SELECT * FROM facility ORDER BY " .
104 "billing_location DESC, service_location, id LIMIT 1";
107 $query = "SELECT facility.* FROM users, facility WHERE " .
108 "users.id = ? AND " .
109 "facility.id = users.facility_id";
110 array_push($sqlBindArray,$_SESSION['authUserID']);
112 return sqlQuery($query,$sqlBindArray);
115 // Generate a report title including report name and facility name, address
118 function genFacilityTitle($repname='', $facid=0) {
120 $s .= "<table class='ftitletable'>\n";
122 $s .= " <td class='ftitlecell1'>$repname</td>\n";
123 $s .= " <td class='ftitlecell2'>\n";
124 $r = getFacility($facid);
126 $s .= "<b>" . htmlspecialchars( $r['name'], ENT_NOQUOTES) . "</b>\n";
127 if ($r['street']) $s .= "<br />" . htmlspecialchars( $r['street'], ENT_NOQUOTES) . "\n";
128 if ($r['city'] || $r['state'] || $r['postal_code']) {
130 if ($r['city']) $s .= htmlspecialchars( $r['city'], ENT_NOQUOTES);
132 if ($r['city']) $s .= ", \n";
133 $s .= htmlspecialchars( $r['state'], ENT_NOQUOTES);
135 if ($r['postal_code']) $s .= " " . htmlspecialchars( $r['postal_code'], ENT_NOQUOTES);
138 if ($r['country_code']) $s .= "<br />" . htmlspecialchars( $r['country_code'], ENT_NOQUOTES) . "\n";
139 if (preg_match('/[1-9]/', $r['phone'])) $s .= "<br />" . htmlspecialchars( $r['phone'], ENT_NOQUOTES) . "\n";
150 returns all facilities or just the id for the first one
151 (FACILITY FILTERING (lemonsoftware))
153 @param string - if 'first' return first facility ordered by id
154 @return array | int for 'first' case
156 function getFacilities($first = '') {
157 $r = sqlStatement("SELECT * FROM facility ORDER BY id");
159 while ( $row = sqlFetchArray($r) ) {
163 if ( $first == 'first') {
164 return $ret[0]['id'];
171 GET SERVICE FACILITIES
173 returns all service_location facilities or just the id for the first one
174 (FACILITY FILTERING (CHEMED))
176 @param string - if 'first' return first facility ordered by id
177 @return array | int for 'first' case
179 function getServiceFacilities($first = '') {
180 $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
182 while ( $row = sqlFetchArray($r) ) {
186 if ( $first == 'first') {
187 return $ret[0]['id'];
193 //(CHEMED) facility filter
194 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
196 if ($providers_only === 'any') {
197 $param1 = " AND authorized = 1 AND active = 1 ";
199 else if ($providers_only) {
200 $param1 = " AND authorized = 1 AND calendar = 1 ";
203 //--------------------------------
204 //(CHEMED) facility filter
207 if ($GLOBALS['restrict_user_facility']) {
208 $param2 = " AND (facility_id = $facility
212 where tablename = 'users'
218 $param2 = " AND facility_id = $facility ";
221 //--------------------------------
224 if ($providerID == "%") {
227 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
228 "from users where username != '' and active = 1 and id $command '" .
229 mysql_real_escape_string($providerID) . "' " . $param1 . $param2;
230 // sort by last name -- JRM June 2008
231 $query .= " ORDER BY lname, fname ";
232 $rez = sqlStatement($query);
233 for($iter=0; $row=sqlFetchArray($rez); $iter++)
234 $returnval[$iter]=$row;
236 //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
237 //accessible from $resultval['key']
240 $akeys = array_keys($returnval[0]);
241 foreach($akeys as $key) {
242 $returnval[0][$key] = $returnval[0][$key];
248 //same as above but does not reduce if only 1 row returned
249 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
251 if ($providers_only) {
252 $param1 = "AND authorized=1";
255 if ($providerID == "%") {
258 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
259 "from users where active = 1 and username != '' and id $command '" .
260 mysql_real_escape_string($providerID) . "' " . $param1;
262 $rez = sqlStatement($query);
263 for($iter=0; $row=sqlFetchArray($rez); $iter++)
264 $returnval[$iter]=$row;
269 function getProviderName($providerID) {
270 $pi = getProviderInfo($providerID, 'any');
271 if (strlen($pi[0]["lname"]) > 0) {
272 return $pi[0]['fname'] . " " . $pi[0]['lname'];
277 function getProviderId($providerName) {
278 $query = "select id from users where username = ?";
279 $rez = sqlStatement($query, array($providerName) );
280 for($iter=0; $row=sqlFetchArray($rez); $iter++)
281 $returnval[$iter]=$row;
285 function getEthnoRacials() {
286 $returnval = array("");
287 $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
288 $rez = sqlStatement($sql);
289 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
290 if (($row["ethnoracial"] != "")) {
291 array_push($returnval, $row["ethnoracial"]);
297 function getHistoryData($pid, $given = "*")
299 $sql = "select $given from history_data where pid=? order by date DESC limit 0,1";
300 return sqlQuery($sql, array($pid) );
303 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
304 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
306 $sql = "select $given from insurance_data as insd " .
307 "left join insurance_companies as ic on ic.id = insd.provider " .
308 "where pid = ? and type = ? order by date DESC limit 1";
309 return sqlQuery($sql, array($pid, $type) );
312 function getInsuranceDataByDate($pid, $date, $type,
313 $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
314 { // this must take the date in the following manner: YYYY-MM-DD
315 // this function recalls the insurance value that was most recently enterred from the
316 // given date. it will call up most recent records up to and on the date given,
317 // but not records enterred after the given date
318 $sql = "select $given from insurance_data as insd " .
319 "left join insurance_companies as ic on ic.id = provider " .
320 "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
321 "type=? order by date DESC limit 1";
322 return sqlQuery($sql, array($pid,$date,$type) );
325 function getEmployerData($pid, $given = "*")
327 $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
328 return sqlQuery($sql, array($pid) );
331 function _set_patient_inc_count($limit, $count, $where, $whereBindArray=array()) {
332 // When the limit is exceeded, find out what the unlimited count would be.
333 $GLOBALS['PATIENT_INC_COUNT'] = $count;
334 // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
335 if ($limit != "all") {
336 $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
337 $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
341 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")
343 // Allow the last name to be followed by a comma and some part of a first name.
344 // New behavior for searches:
345 // Allows comma alone followed by some part of a first name
346 // If the first letter of either name is capital, searches for name starting
347 // with given substring (the expected behavior). If it is lower case, it
348 // it searches for the substring anywhere in the name. This applies to either
349 // last name or first name or both. The arbitrary limit of 100 results is set
350 // in the sql query below. --Mark Leeds
351 $lname = trim($lname);
353 if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
354 $lname = trim($matches[1]);
355 $fname = trim($matches[2]);
357 $search_for_pieces1 = '';
358 $search_for_pieces2 = '';
359 if ($lname{0} != strtoupper($lname{0})) {$search_for_pieces1 = '%';}
360 if ($fname{0} != strtoupper($fname{0})) {$search_for_pieces2 = '%';}
362 $sqlBindArray = array();
363 $where = "lname LIKE ? AND fname LIKE ? ";
364 array_push($sqlBindArray, $search_for_pieces1.$lname."%", $search_for_pieces2.$fname."%");
365 if (!empty($GLOBALS['pt_restrict_field'])) {
366 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
367 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
368 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
369 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
370 array_push($sqlBindArray, $_SESSION{"authUser"});
374 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
375 if ($limit != "all") $sql .= " LIMIT $start, $limit";
377 $rez = sqlStatement($sql, $sqlBindArray);
379 for($iter=0; $row=sqlFetchArray($rez); $iter++)
380 $returnval[$iter] = $row;
382 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
386 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")
389 $sqlBindArray = array();
390 $where = "pubpid LIKE ? ";
391 array_push($sqlBindArray, $pid."%");
392 if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
393 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
394 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
395 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
396 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
397 array_push($sqlBindArray, $_SESSION{"authUser"});
401 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
402 if ($limit != "all") $sql .= " limit $start, $limit";
403 $rez = sqlStatement($sql, $sqlBindArray);
404 for($iter=0; $row=sqlFetchArray($rez); $iter++)
405 $returnval[$iter]=$row;
407 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
411 function getByPatientDemographics($searchTerm = "%", $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")
413 $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%") );
415 $sqlBindArray = array();
417 for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
421 $where .= " ".add_escape_custom($row["field_id"])." like ? ";
422 array_push($sqlBindArray, "%".$searchTerm."%");
425 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
426 if ($limit != "all") $sql .= " limit $start, $limit";
427 $rez = sqlStatement($sql, $sqlBindArray);
428 for($iter=0; $row=sqlFetchArray($rez); $iter++)
429 $returnval[$iter]=$row;
430 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
434 function getByPatientDemographicsFilter($searchFields, $searchTerm = "%", $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" )
436 $layoutCols = split( '~', $searchFields );
437 $sqlBindArray = array();
440 foreach ($layoutCols as $val ) {
445 $where .= " ".add_escape_custom($val)." = ? ";
446 array_push($sqlBindArray, $searchTerm);
449 $where .= " ".add_escape_custom($val)." like ? ";
450 array_push($sqlBindArray, $searchTerm."%");
454 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
455 if ($limit != "all") $sql .= " limit $start, $limit";
456 $rez = sqlStatement($sql, $sqlBindArray);
457 for($iter=0; $row=sqlFetchArray($rez); $iter++)
458 $returnval[$iter]=$row;
459 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
463 // return a collection of Patient PIDs
464 // new arg style by JRM March 2008
465 // 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")
466 function getPatientPID($args)
469 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
470 $orderby = "lname ASC, fname ASC";
474 // alter default values if defined in the passed in args
475 if (isset($args['pid'])) { $pid = $args['pid']; }
476 if (isset($args['given'])) { $given = $args['given']; }
477 if (isset($args['orderby'])) { $orderby = $args['orderby']; }
478 if (isset($args['limit'])) { $limit = $args['limit']; }
479 if (isset($args['start'])) { $start = $args['start']; }
482 if ($pid == -1) $pid = "%";
483 elseif (empty($pid)) $pid = "NULL";
485 if (strstr($pid,"%")) $command = "like";
487 $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
488 if ($limit != "all") $sql .= " limit $start, $limit";
490 $rez = sqlStatement($sql);
491 for($iter=0; $row=sqlFetchArray($rez); $iter++)
492 $returnval[$iter]=$row;
497 /* return a patient's name in the format LAST, FIRST */
498 function getPatientName($pid) {
499 if (empty($pid)) return "";
500 $patientData = getPatientPID(array("pid"=>$pid));
501 if (empty($patientData[0]['lname'])) return "";
502 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
506 /* find patient data by DOB */
507 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
509 $DOB = fixDate($DOB, $DOB);
510 $sqlBindArray = array();
511 $where = "DOB like ? ";
512 array_push($sqlBindArray, $DOB."%");
513 if (!empty($GLOBALS['pt_restrict_field'])) {
514 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
515 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
516 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
517 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
518 array_push($sqlBindArray, $_SESSION{"authUser"});
522 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
524 if ($limit != "all") $sql .= " LIMIT $start, $limit";
526 $rez = sqlStatement($sql, $sqlBindArray);
527 for($iter=0; $row=sqlFetchArray($rez); $iter++)
528 $returnval[$iter]=$row;
530 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
534 /* find patient data by SSN */
535 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
537 $sqlBindArray = array();
538 $where = "ss LIKE ?";
539 array_push($sqlBindArray, $ss."%");
540 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
541 if ($limit != "all") $sql .= " LIMIT $start, $limit";
543 $rez = sqlStatement($sql, $sqlBindArray);
544 for($iter=0; $row=sqlFetchArray($rez); $iter++)
545 $returnval[$iter]=$row;
547 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
551 //(CHEMED) Search by phone number
552 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
554 $phone = ereg_replace( "[[:punct:]]","", $phone );
555 $sqlBindArray = array();
556 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
557 array_push($sqlBindArray, $phone);
558 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
559 if ($limit != "all") $sql .= " LIMIT $start, $limit";
561 $rez = sqlStatement($sql, $sqlBindArray);
562 for($iter=0; $row=sqlFetchArray($rez); $iter++)
563 $returnval[$iter]=$row;
565 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
569 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
571 $sql="select $given from patient_data order by $orderby";
574 $sql .= " limit $start, $limit";
576 $rez = sqlStatement($sql);
577 for($iter=0; $row=sqlFetchArray($rez); $iter++)
578 $returnval[$iter]=$row;
583 //----------------------input functions
584 function newPatientData( $db_id="",
602 $contact_relationship = "",
609 $migrantseasonal = "",
611 $monthly_income = "",
613 $financial_review = "",
626 $drivers_license = "",
632 $DOB = fixDate($DOB);
633 $regdate = fixDate($regdate);
636 $referral_source = '';
638 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
639 // Check for brain damage:
640 if ($db_id != $rez['id']) {
641 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
642 $rez['id'] . "' to '$db_id' for pid '$pid'";
645 $fitness = $rez['fitness'];
646 $referral_source = $rez['referral_source'];
649 // Get the default price level.
650 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
651 "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
652 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
654 $query = ("replace into patient_data set
663 postal_code='$postal_code',
666 country_code='$country_code',
667 drivers_license='$drivers_license',
669 occupation='$occupation',
670 phone_home='$phone_home',
671 phone_biz='$phone_biz',
672 phone_contact='$phone_contact',
674 contact_relationship='$contact_relationship',
675 referrer='$referrer',
676 referrerID='$referrerID',
678 language='$language',
679 ethnoracial='$ethnoracial',
680 interpretter='$interpretter',
681 migrantseasonal='$migrantseasonal',
682 family_size='$family_size',
683 monthly_income='$monthly_income',
684 homeless='$homeless',
685 financial_review='$financial_review',
688 providerID = '$providerID',
689 genericname1 = '$genericname1',
690 genericval1 = '$genericval1',
691 genericname2 = '$genericname2',
692 genericval2 = '$genericval2',
693 phone_cell = '$phone_cell',
694 pharmacy_id = '$pharmacy_id',
695 hipaa_mail = '$hipaa_mail',
696 hipaa_voice = '$hipaa_voice',
697 hipaa_notice = '$hipaa_notice',
698 hipaa_message = '$hipaa_message',
701 referral_source='$referral_source',
703 pricelevel='$pricelevel',
706 $id = sqlInsert($query);
709 // find the last inserted id for new patient case
710 $db_id = mysql_insert_id();
713 $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
715 sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
716 $phone_biz,$phone_cell,$email,$pid);
721 // Supported input date formats are:
723 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
725 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
727 function fixDate($date, $default="0000-00-00") {
728 $fixed_date = $default;
730 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
731 $dmy = preg_split("'[/.-]'", $date);
733 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
735 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
736 if ($dmy[2] < 1000) $dmy[2] += 1900;
737 if ($dmy[2] < 1910) $dmy[2] += 100;
739 // phone_country_code indicates format of ambiguous input dates.
740 if ($GLOBALS['phone_country_code'] == 1)
741 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
743 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
750 function pdValueOrNull($key, $value) {
751 if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
752 substr($key, 0, 8) == 'userdate') &&
753 (empty($value) || $value == '0000-00-00'))
762 // Create or update patient data from an array.
764 function updatePatientData($pid, $new, $create=false)
766 /*******************************************************************
767 $real = getPatientData($pid);
768 $new['DOB'] = fixDate($new['DOB']);
769 while(list($key, $value) = each ($new))
770 $real[$key] = $value;
771 $real['date'] = "'+NOW()+'";
773 $sql = "insert into patient_data set ";
774 while(list($key, $value) = each($real))
775 $sql .= $key." = '$value', ";
776 $sql = substr($sql, 0, -2);
777 return sqlInsert($sql);
778 *******************************************************************/
780 // The above was broken, though seems intent to insert a new patient_data
781 // row for each update. A good idea, but nothing is doing that yet so
782 // the code below does not yet attempt it.
784 $new['DOB'] = fixDate($new['DOB']);
787 $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
788 foreach ($new as $key => $value) {
789 if ($key == 'id') continue;
790 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
792 $db_id = sqlInsert($sql);
796 $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
797 // Check for brain damage:
798 if ($pid != $rez['pid']) {
799 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
800 $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
803 $sql = "UPDATE patient_data SET date = NOW()";
804 foreach ($new as $key => $value) {
805 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
807 $sql .= " WHERE id = '$db_id'";
811 $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
812 sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
813 $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
814 $rez['phone_cell'],$rez['email'],$rez['pid']);
819 function newEmployerData( $pid,
828 return sqlInsert("insert into employer_data set
831 postal_code='$postal_code',
840 // Create or update employer data from an array.
842 function updateEmployerData($pid, $new, $create=false)
844 $colnames = array('name','street','city','state','postal_code','country');
847 $set .= "pid = '$pid', date = NOW()";
848 foreach ($colnames as $key) {
849 $value = isset($new[$key]) ? $new[$key] : '';
850 $set .= ", `$key` = '$value'";
852 return sqlInsert("INSERT INTO employer_data SET $set");
856 $old = getEmployerData($pid);
858 foreach ($colnames as $key) {
859 $value = empty($old[$key]) ? '' : addslashes($old[$key]);
860 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
864 $set .= "`$key` = '$value', ";
867 $set .= "pid = '$pid', date = NOW()";
868 return sqlInsert("INSERT INTO employer_data SET $set");
874 // This updates or adds the given insurance data info, while retaining any
875 // previously added insurance_data rows that should be preserved.
876 // This does not directly support the maintenance of non-current insurance.
878 function newInsuranceData(
885 $subscriber_lname = "",
886 $subscriber_mname = "",
887 $subscriber_fname = "",
888 $subscriber_relationship = "",
890 $subscriber_DOB = "",
891 $subscriber_street = "",
892 $subscriber_postal_code = "",
893 $subscriber_city = "",
894 $subscriber_state = "",
895 $subscriber_country = "",
896 $subscriber_phone = "",
897 $subscriber_employer = "",
898 $subscriber_employer_street = "",
899 $subscriber_employer_city = "",
900 $subscriber_employer_postal_code = "",
901 $subscriber_employer_state = "",
902 $subscriber_employer_country = "",
904 $subscriber_sex = "",
905 $effective_date = "0000-00-00",
906 $accept_assignment = "TRUE")
908 if (strlen($type) <= 0) return FALSE;
910 // If a bad date was passed, err on the side of caution.
911 $effective_date = fixDate($effective_date, date('Y-m-d'));
913 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
914 "pid = '$pid' AND type = '$type' ORDER BY date DESC");
915 $idrow = sqlFetchArray($idres);
917 // Replace the most recent entry in any of the following cases:
918 // * Its effective date is >= this effective date.
919 // * It is the first entry and it has no (insurance) provider.
920 // * There is no encounter that is earlier than the new effective date but
921 // on or after the old effective date.
922 // Otherwise insert a new entry.
926 if (strcmp($idrow['date'], $effective_date) > 0) {
930 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
934 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
935 "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
936 "date >= '" . $idrow['date'] . " 00:00:00'");
937 if ($ferow['count'] == 0) $replace = true;
944 // TBD: This is a bit dangerous in that a typo in entering the effective
945 // date can wipe out previous insurance history. So we want some data
946 // entry validation somewhere.
947 sqlStatement("DELETE FROM insurance_data WHERE " .
948 "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
949 "id != " . $idrow['id']);
952 $data['type'] = $type;
953 $data['provider'] = $provider;
954 $data['policy_number'] = $policy_number;
955 $data['group_number'] = $group_number;
956 $data['plan_name'] = $plan_name;
957 $data['subscriber_lname'] = $subscriber_lname;
958 $data['subscriber_mname'] = $subscriber_mname;
959 $data['subscriber_fname'] = $subscriber_fname;
960 $data['subscriber_relationship'] = $subscriber_relationship;
961 $data['subscriber_ss'] = $subscriber_ss;
962 $data['subscriber_DOB'] = $subscriber_DOB;
963 $data['subscriber_street'] = $subscriber_street;
964 $data['subscriber_postal_code'] = $subscriber_postal_code;
965 $data['subscriber_city'] = $subscriber_city;
966 $data['subscriber_state'] = $subscriber_state;
967 $data['subscriber_country'] = $subscriber_country;
968 $data['subscriber_phone'] = $subscriber_phone;
969 $data['subscriber_employer'] = $subscriber_employer;
970 $data['subscriber_employer_city'] = $subscriber_employer_city;
971 $data['subscriber_employer_street'] = $subscriber_employer_street;
972 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
973 $data['subscriber_employer_state'] = $subscriber_employer_state;
974 $data['subscriber_employer_country'] = $subscriber_employer_country;
975 $data['copay'] = $copay;
976 $data['subscriber_sex'] = $subscriber_sex;
978 $data['date'] = $effective_date;
979 $data['accept_assignment'] = $accept_assignment;
980 updateInsuranceData($idrow['id'], $data);
984 return sqlInsert("INSERT INTO insurance_data SET
986 provider = '$provider',
987 policy_number = '$policy_number',
988 group_number = '$group_number',
989 plan_name = '$plan_name',
990 subscriber_lname = '$subscriber_lname',
991 subscriber_mname = '$subscriber_mname',
992 subscriber_fname = '$subscriber_fname',
993 subscriber_relationship = '$subscriber_relationship',
994 subscriber_ss = '$subscriber_ss',
995 subscriber_DOB = '$subscriber_DOB',
996 subscriber_street = '$subscriber_street',
997 subscriber_postal_code = '$subscriber_postal_code',
998 subscriber_city = '$subscriber_city',
999 subscriber_state = '$subscriber_state',
1000 subscriber_country = '$subscriber_country',
1001 subscriber_phone = '$subscriber_phone',
1002 subscriber_employer = '$subscriber_employer',
1003 subscriber_employer_city = '$subscriber_employer_city',
1004 subscriber_employer_street = '$subscriber_employer_street',
1005 subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1006 subscriber_employer_state = '$subscriber_employer_state',
1007 subscriber_employer_country = '$subscriber_employer_country',
1009 subscriber_sex = '$subscriber_sex',
1011 date = '$effective_date',
1012 accept_assignment = '$accept_assignment'
1017 // This is used internally only.
1018 function updateInsuranceData($id, $new)
1020 $fields = sqlListFields("insurance_data");
1023 while(list($key, $value) = each ($new)) {
1024 if (in_array($key, $fields)) {
1025 $use[$key] = $value;
1029 $sql = "UPDATE insurance_data SET ";
1030 while(list($key, $value) = each($use))
1031 $sql .= "`$key` = '$value', ";
1032 $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1037 function newHistoryData($pid, $new=false) {
1038 $arraySqlBind = array();
1039 $sql = "insert into history_data set pid = ?, date = NOW()";
1040 array_push($arraySqlBind,$pid);
1042 while(list($key, $value) = each($new)) {
1043 array_push($arraySqlBind,$value);
1044 $sql .= ", `$key` = ?";
1047 return sqlInsert($sql, $arraySqlBind );
1050 function updateHistoryData($pid,$new)
1052 $real = getHistoryData($pid);
1053 while(list($key, $value) = each ($new))
1054 $real[$key] = $value;
1056 // need to unset date, so can reset it below
1057 unset($real['date']);
1059 $arraySqlBind = array();
1060 $sql = "insert into history_data set `date` = NOW(), ";
1061 while(list($key, $value) = each($real)) {
1062 array_push($arraySqlBind,$value);
1063 $sql .= "`$key` = ?, ";
1065 $sql = substr($sql, 0, -2);
1067 return sqlInsert($sql, $arraySqlBind );
1070 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1071 $phone_biz,$phone_cell,$email,$pid="")
1073 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1074 if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1076 $db = $GLOBALS['adodb']['db'];
1077 $customer_info = array();
1079 $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1080 $result = $db->Execute($sql);
1081 if ($result && !$result->EOF) {
1082 $customer_info['foreign_update'] = true;
1083 $customer_info['foreign_id'] = $result->fields['foreign_id'];
1084 $customer_info['foreign_table'] = $result->fields['foreign_table'];
1087 ///xml rpc code to connect to accounting package and add user to it
1088 $customer_info['firstname'] = $fname;
1089 $customer_info['lastname'] = $lname;
1090 $customer_info['address'] = $street;
1091 $customer_info['suburb'] = $city;
1092 $customer_info['state'] = $state;
1093 $customer_info['postcode'] = $postal_code;
1095 //ezybiz wants state as a code rather than abbreviation
1096 $customer_info['geo_zone_id'] = "";
1097 $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1098 $db = $GLOBALS['adodb']['db'];
1099 $result = $db->Execute($sql);
1100 if ($result && !$result->EOF) {
1101 $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1104 //ezybiz wants country as a code rather than abbreviation
1105 $customer_info['geo_country_id'] = "";
1106 $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1107 $db = $GLOBALS['adodb']['db'];
1108 $result = $db->Execute($sql);
1109 if ($result && !$result->EOF) {
1110 $customer_info['geo_country_id'] = $result->fields['countries_id'];
1113 $customer_info['phone1'] = $phone_home;
1114 $customer_info['phone1comment'] = "Home Phone";
1115 $customer_info['phone2'] = $phone_biz;
1116 $customer_info['phone2comment'] = "Business Phone";
1117 $customer_info['phone3'] = $phone_cell;
1118 $customer_info['phone3comment'] = "Cell Phone";
1119 $customer_info['email'] = $email;
1120 $customer_info['customernumber'] = $pid;
1122 $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1123 $ws = new WSWrapper($function);
1125 // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1126 if (is_numeric($ws->value)) {
1127 $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1128 $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1133 // in months if < 2 years old
1134 // in years if > 2 years old
1135 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1136 // (optional) nowYMD is a date in YYYYMMDD format
1137 function getPatientAge($dobYMD, $nowYMD=null)
1139 // strip any dashes from the DOB
1140 $dobYMD = preg_replace("/-/", "", $dobYMD);
1141 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1143 // set the 'now' date values
1144 if ($nowYMD == null) {
1145 $nowDay = date("d");
1146 $nowMonth = date("m");
1147 $nowYear = date("Y");
1150 $nowDay = substr($nowYMD,6,2);
1151 $nowMonth = substr($nowYMD,4,2);
1152 $nowYear = substr($nowYMD,0,4);
1155 $dayDiff = $nowDay - $dobDay;
1156 $monthDiff = $nowMonth - $dobMonth;
1157 $yearDiff = $nowYear - $dobYear;
1159 $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1161 if ( $ageInMonths > 24 ) {
1163 if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1164 else if ($monthDiff < 0) { $age -= 1; }
1167 $age = "$ageInMonths month";
1174 // Returns Age in days
1175 // in months if < 2 years old
1176 // in years if > 2 years old
1177 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1178 // (optional) nowYMD is a date in YYYYMMDD format
1179 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1182 // strip any dashes from the DOB
1183 $dobYMD = preg_replace("/-/", "", $dobYMD);
1184 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1186 // set the 'now' date values
1187 if ($nowYMD == null) {
1188 $nowDay = date("d");
1189 $nowMonth = date("m");
1190 $nowYear = date("Y");
1193 $nowDay = substr($nowYMD,6,2);
1194 $nowMonth = substr($nowYMD,4,2);
1195 $nowYear = substr($nowYMD,0,4);
1199 $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1200 $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1201 $timediff = $nowtime - $dobtime;
1202 $age = $timediff / 86400;
1207 function dateToDB ($date)
1209 $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1214 // ----------------------------------------------------------------------------
1216 * DROPDOWN FOR COUNTRIES
1218 * build a dropdown with all countries from geo_country_reference
1220 * @param int $selected - id for selected record
1221 * @param string $name - the name/id for select form
1222 * @return void - just echo the html encoded string
1224 function dropdown_countries($selected = 0, $name = 'country_code') {
1225 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1227 $string = "<select name='$name' id='$name'>";
1228 while ( $row = sqlFetchArray($r) ) {
1229 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1230 $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1233 $string .= '</select>';
1238 // ----------------------------------------------------------------------------
1240 * DROPDOWN FOR YES/NO
1242 * build a dropdown with two options (yes - 1, no - 0)
1244 * @param int $selected - id for selected record
1245 * @param string $name - the name/id for select form
1246 * @return void - just echo the html encoded string
1248 function dropdown_yesno($selected = 0, $name = 'yesno') {
1249 $string = "<select name='$name' id='$name'>";
1251 $selected = (int)$selected;
1252 if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1253 else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1255 $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1256 $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1257 $string .= '</select>';
1262 // ----------------------------------------------------------------------------
1264 * DROPDOWN FOR MALE/FEMALE options
1266 * build a dropdown with three options (unselected/male/female)
1268 * @param int $selected - id for selected record
1269 * @param string $name - the name/id for select form
1270 * @return void - just echo the html encoded string
1272 function dropdown_sex($selected = 0, $name = 'sex') {
1273 $string = "<select name='$name' id='$name'>";
1275 if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1276 else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1277 else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1279 $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1280 $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1281 $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1282 $string .= '</select>';
1287 // ----------------------------------------------------------------------------
1289 * DROPDOWN FOR MARITAL STATUS
1291 * build a dropdown with marital status
1293 * @param int $selected - id for selected record
1294 * @param string $name - the name/id for select form
1295 * @return void - just echo the html encoded string
1297 function dropdown_marital($selected = 0, $name = 'status') {
1298 $string = "<select name='$name' id='$name'>";
1300 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1302 foreach ( $statii as $st ) {
1303 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1304 $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1307 $string .= '</select>';
1312 // ----------------------------------------------------------------------------
1314 * DROPDOWN FOR PROVIDERS
1316 * build a dropdown with all providers
1318 * @param int $selected - id for selected record
1319 * @param string $name - the name/id for select form
1320 * @return void - just echo the html encoded string
1322 function dropdown_providers($selected = 0, $name = 'status') {
1323 $provideri = getProviderInfo();
1325 $string = "<select name='$name' id='$name'>";
1326 $string .= '<option value="">' .xl('Unassigned'). '</option>';
1327 foreach ( $provideri as $s ) {
1328 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1329 $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1332 $string .= '</select>';
1337 // ----------------------------------------------------------------------------
1339 * DROPDOWN FOR INSURANCE COMPANIES
1341 * build a dropdown with all insurers
1343 * @param int $selected - id for selected record
1344 * @param string $name - the name/id for select form
1345 * @return void - just echo the html encoded string
1347 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1348 $insurancei = getInsuranceProviders();
1350 $string = "<select name='$name' id='$name'>";
1351 $string .= '<option value="0">Onbekend</option>';
1352 foreach ( $insurancei as $iid => $iname ) {
1353 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1354 $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1357 $string .= '</select>';
1363 // ----------------------------------------------------------------------------
1367 * return the name or the country code, function of arguments
1369 * @param int $country_code
1370 * @param string $country_name
1371 * @return string | int - name or code
1373 function country_code($country_code = 0, $country_name = '') {
1375 if ( $country_code ) {
1376 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1378 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1381 $db = $GLOBALS['adodb']['db'];
1382 $result = $db->Execute($sql);
1383 if ($result && !$result->EOF) {
1384 $strint = $result->fields['res'];
1390 function DBToDate ($date)
1392 $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1396 function get_patient_balance($pid) {
1397 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1398 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1399 "pid = ? AND activity = 1", array($pid) );
1400 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1401 "pid = ?", array($pid) );
1402 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1403 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1404 "pid = ?", array($pid) );
1405 return sprintf('%01.2f', $brow['amount'] + $srow['amount']
1406 - $drow['payments'] - $drow['adjustments']);
1408 else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1409 // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1410 $conn = $GLOBALS['adodb']['db'];
1411 $customer_info['id'] = 0;
1412 $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1413 "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1414 "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1415 "im.foreign_table = 'customer'";
1416 $result = $conn->Execute($sql);
1417 if($result && !$result->EOF) {
1418 $customer_info['id'] = $result->fields['foreign_id'];
1420 $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1421 $ws = new WSWrapper($function);
1422 if(is_numeric($ws->value)) {
1423 return sprintf('%01.2f', $ws->value);