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 require_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 getInsuranceProvider($ins_id) {
42 $sql = "select name from insurance_companies where id=?";
43 $row = sqlQuery($sql,array($ins_id));
48 function getInsuranceProviders() {
52 $sql = "select name, id from insurance_companies order by name, id";
53 $rez = sqlStatement($sql);
54 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
55 $returnval[$row['id']] = $row['name'];
59 // Please leave this here. I have a user who wants to see zip codes and PO
60 // box numbers listed along with the insurance company names, as many companies
61 // have different billing addresses for different plans. -- Rod Roark
64 $sql = "select insurance_companies.name, insurance_companies.id, " .
65 "addresses.zip, addresses.line1 " .
66 "from insurance_companies, addresses " .
67 "where addresses.foreign_id = insurance_companies.id " .
68 "order by insurance_companies.name, addresses.zip";
70 $rez = sqlStatement($sql);
72 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
73 preg_match("/\d+/", $row['line1'], $matches);
74 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
75 "," . $matches[0] . ")";
82 function getProviders() {
83 $returnval = array("");
84 $sql = "select fname, lname from users where authorized = 1 and " .
85 "active = 1 and username != ''";
86 $rez = sqlStatement($sql);
87 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
88 if (($row["fname"] != "") && ($row["lname"] != "")) {
89 array_push($returnval, $row["fname"] . " " . $row["lname"]);
95 // ----------------------------------------------------------------------------
96 // Get one facility row. If the ID is not specified, then get either the
97 // "main" (billing) facility, or the default facility of the currently
98 // logged-in user. This was created to support genFacilityTitle() but
99 // may find additional uses.
101 function getFacility($facid=0) {
103 //create a sql binding array
104 $sqlBindArray = array();
107 $query = "SELECT * FROM facility WHERE id = ?";
108 array_push($sqlBindArray,$facid);
110 else if ($facid == 0) {
111 $query = "SELECT * FROM facility ORDER BY " .
112 "billing_location DESC, service_location, id LIMIT 1";
115 $query = "SELECT facility.* FROM users, facility WHERE " .
116 "users.id = ? AND " .
117 "facility.id = users.facility_id";
118 array_push($sqlBindArray,$_SESSION['authUserID']);
120 return sqlQuery($query,$sqlBindArray);
123 // Generate a report title including report name and facility name, address
126 function genFacilityTitle($repname='', $facid=0) {
128 $s .= "<table class='ftitletable'>\n";
130 $s .= " <td class='ftitlecell1'>$repname</td>\n";
131 $s .= " <td class='ftitlecell2'>\n";
132 $r = getFacility($facid);
134 $s .= "<b>" . htmlspecialchars( $r['name'], ENT_NOQUOTES) . "</b>\n";
135 if ($r['street']) $s .= "<br />" . htmlspecialchars( $r['street'], ENT_NOQUOTES) . "\n";
136 if ($r['city'] || $r['state'] || $r['postal_code']) {
138 if ($r['city']) $s .= htmlspecialchars( $r['city'], ENT_NOQUOTES);
140 if ($r['city']) $s .= ", \n";
141 $s .= htmlspecialchars( $r['state'], ENT_NOQUOTES);
143 if ($r['postal_code']) $s .= " " . htmlspecialchars( $r['postal_code'], ENT_NOQUOTES);
146 if ($r['country_code']) $s .= "<br />" . htmlspecialchars( $r['country_code'], ENT_NOQUOTES) . "\n";
147 if (preg_match('/[1-9]/', $r['phone'])) $s .= "<br />" . htmlspecialchars( $r['phone'], ENT_NOQUOTES) . "\n";
158 returns all facilities or just the id for the first one
159 (FACILITY FILTERING (lemonsoftware))
161 @param string - if 'first' return first facility ordered by id
162 @return array | int for 'first' case
164 function getFacilities($first = '') {
165 $r = sqlStatement("SELECT * FROM facility ORDER BY id");
167 while ( $row = sqlFetchArray($r) ) {
171 if ( $first == 'first') {
172 return $ret[0]['id'];
179 GET SERVICE FACILITIES
181 returns all service_location facilities or just the id for the first one
182 (FACILITY FILTERING (CHEMED))
184 @param string - if 'first' return first facility ordered by id
185 @return array | int for 'first' case
187 function getServiceFacilities($first = '') {
188 $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
190 while ( $row = sqlFetchArray($r) ) {
194 if ( $first == 'first') {
195 return $ret[0]['id'];
201 //(CHEMED) facility filter
202 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
204 if ($providers_only === 'any') {
205 $param1 = " AND authorized = 1 AND active = 1 ";
207 else if ($providers_only) {
208 $param1 = " AND authorized = 1 AND calendar = 1 ";
211 //--------------------------------
212 //(CHEMED) facility filter
215 if ($GLOBALS['restrict_user_facility']) {
216 $param2 = " AND (facility_id = $facility
220 where tablename = 'users'
226 $param2 = " AND facility_id = $facility ";
229 //--------------------------------
232 if ($providerID == "%") {
235 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
236 "from users where username != '' and active = 1 and id $command '" .
237 mysql_real_escape_string($providerID) . "' " . $param1 . $param2;
238 // sort by last name -- JRM June 2008
239 $query .= " ORDER BY lname, fname ";
240 $rez = sqlStatement($query);
241 for($iter=0; $row=sqlFetchArray($rez); $iter++)
242 $returnval[$iter]=$row;
244 //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
245 //accessible from $resultval['key']
248 $akeys = array_keys($returnval[0]);
249 foreach($akeys as $key) {
250 $returnval[0][$key] = $returnval[0][$key];
256 //same as above but does not reduce if only 1 row returned
257 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
259 if ($providers_only) {
260 $param1 = "AND authorized=1";
263 if ($providerID == "%") {
266 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
267 "from users where active = 1 and username != '' and id $command '" .
268 mysql_real_escape_string($providerID) . "' " . $param1;
270 $rez = sqlStatement($query);
271 for($iter=0; $row=sqlFetchArray($rez); $iter++)
272 $returnval[$iter]=$row;
277 function getProviderName($providerID) {
278 $pi = getProviderInfo($providerID, 'any');
279 if (strlen($pi[0]["lname"]) > 0) {
280 return $pi[0]['fname'] . " " . $pi[0]['lname'];
285 function getProviderId($providerName) {
286 $query = "select id from users where username = ?";
287 $rez = sqlStatement($query, array($providerName) );
288 for($iter=0; $row=sqlFetchArray($rez); $iter++)
289 $returnval[$iter]=$row;
293 function getEthnoRacials() {
294 $returnval = array("");
295 $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
296 $rez = sqlStatement($sql);
297 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
298 if (($row["ethnoracial"] != "")) {
299 array_push($returnval, $row["ethnoracial"]);
305 function getHistoryData($pid, $given = "*", $dateStart='',$dateEnd='')
308 if ($dateStart && $dateEnd) {
309 $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd) );
311 else if ($dateStart && !$dateEnd) {
312 $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart) );
314 else if (!$dateStart && $dateEnd) {
315 $res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd) );
318 $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid) );
324 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
325 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
327 $sql = "select $given from insurance_data as insd " .
328 "left join insurance_companies as ic on ic.id = insd.provider " .
329 "where pid = ? and type = ? order by date DESC limit 1";
330 return sqlQuery($sql, array($pid, $type) );
333 function getInsuranceDataByDate($pid, $date, $type,
334 $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
335 { // this must take the date in the following manner: YYYY-MM-DD
336 // this function recalls the insurance value that was most recently enterred from the
337 // given date. it will call up most recent records up to and on the date given,
338 // but not records enterred after the given date
339 $sql = "select $given from insurance_data as insd " .
340 "left join insurance_companies as ic on ic.id = provider " .
341 "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
342 "type=? order by date DESC limit 1";
343 return sqlQuery($sql, array($pid,$date,$type) );
346 function getEmployerData($pid, $given = "*")
348 $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
349 return sqlQuery($sql, array($pid) );
352 function _set_patient_inc_count($limit, $count, $where, $whereBindArray=array()) {
353 // When the limit is exceeded, find out what the unlimited count would be.
354 $GLOBALS['PATIENT_INC_COUNT'] = $count;
355 // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
356 if ($limit != "all") {
357 $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
358 $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
362 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")
364 // Allow the last name to be followed by a comma and some part of a first name.
365 // New behavior for searches:
366 // Allows comma alone followed by some part of a first name
367 // If the first letter of either name is capital, searches for name starting
368 // with given substring (the expected behavior). If it is lower case, it
369 // it searches for the substring anywhere in the name. This applies to either
370 // last name or first name or both. The arbitrary limit of 100 results is set
371 // in the sql query below. --Mark Leeds
372 $lname = trim($lname);
374 if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
375 $lname = trim($matches[1]);
376 $fname = trim($matches[2]);
378 $search_for_pieces1 = '';
379 $search_for_pieces2 = '';
380 if ($lname{0} != strtoupper($lname{0})) {$search_for_pieces1 = '%';}
381 if ($fname{0} != strtoupper($fname{0})) {$search_for_pieces2 = '%';}
383 $sqlBindArray = array();
384 $where = "lname LIKE ? AND fname LIKE ? ";
385 array_push($sqlBindArray, $search_for_pieces1.$lname."%", $search_for_pieces2.$fname."%");
386 if (!empty($GLOBALS['pt_restrict_field'])) {
387 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
388 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
389 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
390 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
391 array_push($sqlBindArray, $_SESSION{"authUser"});
395 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
396 if ($limit != "all") $sql .= " LIMIT $start, $limit";
398 $rez = sqlStatement($sql, $sqlBindArray);
400 for($iter=0; $row=sqlFetchArray($rez); $iter++)
401 $returnval[$iter] = $row;
403 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
407 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")
410 $sqlBindArray = array();
411 $where = "pubpid LIKE ? ";
412 array_push($sqlBindArray, $pid."%");
413 if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
414 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
415 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
416 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
417 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
418 array_push($sqlBindArray, $_SESSION{"authUser"});
422 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
423 if ($limit != "all") $sql .= " limit $start, $limit";
424 $rez = sqlStatement($sql, $sqlBindArray);
425 for($iter=0; $row=sqlFetchArray($rez); $iter++)
426 $returnval[$iter]=$row;
428 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
432 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")
434 $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%") );
436 $sqlBindArray = array();
438 for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
442 $where .= " ".add_escape_custom($row["field_id"])." like ? ";
443 array_push($sqlBindArray, "%".$searchTerm."%");
446 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
447 if ($limit != "all") $sql .= " limit $start, $limit";
448 $rez = sqlStatement($sql, $sqlBindArray);
449 for($iter=0; $row=sqlFetchArray($rez); $iter++)
450 $returnval[$iter]=$row;
451 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
455 function getByPatientDemographicsFilter($searchFields, $searchTerm = "%",
456 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
457 $orderby = "lname ASC, fname ASC", $limit="all", $start="0", $search_service_code='')
459 $layoutCols = split( '~', $searchFields );
460 $sqlBindArray = array();
463 foreach ($layoutCols as $val) {
464 if (empty($val)) continue;
469 $where .= " ".add_escape_custom($val)." = ? ";
470 array_push($sqlBindArray, $searchTerm);
473 $where .= " ".add_escape_custom($val)." like ? ";
474 array_push($sqlBindArray, $searchTerm."%");
479 // If no search terms, ensure valid syntax.
480 if ($i == 0) $where = "1 = 1";
482 // If a non-empty service code was given, then restrict to patients who
483 // have been provided that service. Since the code is used in a LIKE
484 // clause, % and _ wildcards are supported.
485 if ($search_service_code) {
486 $where = "( $where ) AND " .
487 "( SELECT COUNT(*) FROM billing AS b WHERE " .
488 "b.pid = patient_data.pid AND " .
489 "b.activity = 1 AND " .
490 "b.code_type != 'COPAY' AND " .
493 array_push($sqlBindArray, $search_service_code);
496 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
497 if ($limit != "all") $sql .= " limit $start, $limit";
498 $rez = sqlStatement($sql, $sqlBindArray);
499 for($iter=0; $row=sqlFetchArray($rez); $iter++)
500 $returnval[$iter]=$row;
501 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
505 // return a collection of Patient PIDs
506 // new arg style by JRM March 2008
507 // 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")
508 function getPatientPID($args)
511 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
512 $orderby = "lname ASC, fname ASC";
516 // alter default values if defined in the passed in args
517 if (isset($args['pid'])) { $pid = $args['pid']; }
518 if (isset($args['given'])) { $given = $args['given']; }
519 if (isset($args['orderby'])) { $orderby = $args['orderby']; }
520 if (isset($args['limit'])) { $limit = $args['limit']; }
521 if (isset($args['start'])) { $start = $args['start']; }
524 if ($pid == -1) $pid = "%";
525 elseif (empty($pid)) $pid = "NULL";
527 if (strstr($pid,"%")) $command = "like";
529 $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
530 if ($limit != "all") $sql .= " limit $start, $limit";
532 $rez = sqlStatement($sql);
533 for($iter=0; $row=sqlFetchArray($rez); $iter++)
534 $returnval[$iter]=$row;
539 /* return a patient's name in the format LAST, FIRST */
540 function getPatientName($pid) {
541 if (empty($pid)) return "";
542 $patientData = getPatientPID(array("pid"=>$pid));
543 if (empty($patientData[0]['lname'])) return "";
544 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
548 /* find patient data by DOB */
549 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
551 $DOB = fixDate($DOB, $DOB);
552 $sqlBindArray = array();
553 $where = "DOB like ? ";
554 array_push($sqlBindArray, $DOB."%");
555 if (!empty($GLOBALS['pt_restrict_field'])) {
556 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
557 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
558 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
559 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
560 array_push($sqlBindArray, $_SESSION{"authUser"});
564 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
566 if ($limit != "all") $sql .= " LIMIT $start, $limit";
568 $rez = sqlStatement($sql, $sqlBindArray);
569 for($iter=0; $row=sqlFetchArray($rez); $iter++)
570 $returnval[$iter]=$row;
572 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
576 /* find patient data by SSN */
577 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
579 $sqlBindArray = array();
580 $where = "ss LIKE ?";
581 array_push($sqlBindArray, $ss."%");
582 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
583 if ($limit != "all") $sql .= " LIMIT $start, $limit";
585 $rez = sqlStatement($sql, $sqlBindArray);
586 for($iter=0; $row=sqlFetchArray($rez); $iter++)
587 $returnval[$iter]=$row;
589 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
593 //(CHEMED) Search by phone number
594 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
596 $phone = ereg_replace( "[[:punct:]]","", $phone );
597 $sqlBindArray = array();
598 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
599 array_push($sqlBindArray, $phone);
600 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
601 if ($limit != "all") $sql .= " LIMIT $start, $limit";
603 $rez = sqlStatement($sql, $sqlBindArray);
604 for($iter=0; $row=sqlFetchArray($rez); $iter++)
605 $returnval[$iter]=$row;
607 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
611 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
613 $sql="select $given from patient_data order by $orderby";
616 $sql .= " limit $start, $limit";
618 $rez = sqlStatement($sql);
619 for($iter=0; $row=sqlFetchArray($rez); $iter++)
620 $returnval[$iter]=$row;
625 //----------------------input functions
626 function newPatientData( $db_id="",
644 $contact_relationship = "",
651 $migrantseasonal = "",
653 $monthly_income = "",
655 $financial_review = "",
668 $drivers_license = "",
674 $DOB = fixDate($DOB);
675 $regdate = fixDate($regdate);
678 $referral_source = '';
680 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
681 // Check for brain damage:
682 if ($db_id != $rez['id']) {
683 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
684 $rez['id'] . "' to '$db_id' for pid '$pid'";
687 $fitness = $rez['fitness'];
688 $referral_source = $rez['referral_source'];
691 // Get the default price level.
692 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
693 "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
694 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
696 $query = ("replace into patient_data set
705 postal_code='$postal_code',
708 country_code='$country_code',
709 drivers_license='$drivers_license',
711 occupation='$occupation',
712 phone_home='$phone_home',
713 phone_biz='$phone_biz',
714 phone_contact='$phone_contact',
716 contact_relationship='$contact_relationship',
717 referrer='$referrer',
718 referrerID='$referrerID',
720 language='$language',
721 ethnoracial='$ethnoracial',
722 interpretter='$interpretter',
723 migrantseasonal='$migrantseasonal',
724 family_size='$family_size',
725 monthly_income='$monthly_income',
726 homeless='$homeless',
727 financial_review='$financial_review',
730 providerID = '$providerID',
731 genericname1 = '$genericname1',
732 genericval1 = '$genericval1',
733 genericname2 = '$genericname2',
734 genericval2 = '$genericval2',
735 phone_cell = '$phone_cell',
736 pharmacy_id = '$pharmacy_id',
737 hipaa_mail = '$hipaa_mail',
738 hipaa_voice = '$hipaa_voice',
739 hipaa_notice = '$hipaa_notice',
740 hipaa_message = '$hipaa_message',
743 referral_source='$referral_source',
745 pricelevel='$pricelevel',
748 $id = sqlInsert($query);
751 // find the last inserted id for new patient case
752 $db_id = mysql_insert_id();
755 $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
757 sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
758 $phone_biz,$phone_cell,$email,$pid);
763 // Supported input date formats are:
765 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
767 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
769 function fixDate($date, $default="0000-00-00") {
770 $fixed_date = $default;
772 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
773 $dmy = preg_split("'[/.-]'", $date);
775 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
777 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
778 if ($dmy[2] < 1000) $dmy[2] += 1900;
779 if ($dmy[2] < 1910) $dmy[2] += 100;
781 // phone_country_code indicates format of ambiguous input dates.
782 if ($GLOBALS['phone_country_code'] == 1)
783 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
785 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
792 function pdValueOrNull($key, $value) {
793 if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
794 substr($key, 0, 8) == 'userdate') &&
795 (empty($value) || $value == '0000-00-00'))
804 // Create or update patient data from an array.
806 function updatePatientData($pid, $new, $create=false)
808 /*******************************************************************
809 $real = getPatientData($pid);
810 $new['DOB'] = fixDate($new['DOB']);
811 while(list($key, $value) = each ($new))
812 $real[$key] = $value;
813 $real['date'] = "'+NOW()+'";
815 $sql = "insert into patient_data set ";
816 while(list($key, $value) = each($real))
817 $sql .= $key." = '$value', ";
818 $sql = substr($sql, 0, -2);
819 return sqlInsert($sql);
820 *******************************************************************/
822 // The above was broken, though seems intent to insert a new patient_data
823 // row for each update. A good idea, but nothing is doing that yet so
824 // the code below does not yet attempt it.
826 $new['DOB'] = fixDate($new['DOB']);
829 $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
830 foreach ($new as $key => $value) {
831 if ($key == 'id') continue;
832 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
834 $db_id = sqlInsert($sql);
838 $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
839 // Check for brain damage:
840 if ($pid != $rez['pid']) {
841 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
842 $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
845 $sql = "UPDATE patient_data SET date = NOW()";
846 foreach ($new as $key => $value) {
847 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
849 $sql .= " WHERE id = '$db_id'";
853 $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
854 sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
855 $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
856 $rez['phone_cell'],$rez['email'],$rez['pid']);
861 function newEmployerData( $pid,
870 return sqlInsert("insert into employer_data set
873 postal_code='$postal_code',
882 // Create or update employer data from an array.
884 function updateEmployerData($pid, $new, $create=false)
886 $colnames = array('name','street','city','state','postal_code','country');
889 $set .= "pid = '$pid', date = NOW()";
890 foreach ($colnames as $key) {
891 $value = isset($new[$key]) ? $new[$key] : '';
892 $set .= ", `$key` = '$value'";
894 return sqlInsert("INSERT INTO employer_data SET $set");
898 $old = getEmployerData($pid);
900 foreach ($colnames as $key) {
901 $value = empty($old[$key]) ? '' : addslashes($old[$key]);
902 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
906 $set .= "`$key` = '$value', ";
909 $set .= "pid = '$pid', date = NOW()";
910 return sqlInsert("INSERT INTO employer_data SET $set");
916 // This updates or adds the given insurance data info, while retaining any
917 // previously added insurance_data rows that should be preserved.
918 // This does not directly support the maintenance of non-current insurance.
920 function newInsuranceData(
927 $subscriber_lname = "",
928 $subscriber_mname = "",
929 $subscriber_fname = "",
930 $subscriber_relationship = "",
932 $subscriber_DOB = "",
933 $subscriber_street = "",
934 $subscriber_postal_code = "",
935 $subscriber_city = "",
936 $subscriber_state = "",
937 $subscriber_country = "",
938 $subscriber_phone = "",
939 $subscriber_employer = "",
940 $subscriber_employer_street = "",
941 $subscriber_employer_city = "",
942 $subscriber_employer_postal_code = "",
943 $subscriber_employer_state = "",
944 $subscriber_employer_country = "",
946 $subscriber_sex = "",
947 $effective_date = "0000-00-00",
948 $accept_assignment = "TRUE")
950 if (strlen($type) <= 0) return FALSE;
952 // If a bad date was passed, err on the side of caution.
953 $effective_date = fixDate($effective_date, date('Y-m-d'));
955 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
956 "pid = '$pid' AND type = '$type' ORDER BY date DESC");
957 $idrow = sqlFetchArray($idres);
959 // Replace the most recent entry in any of the following cases:
960 // * Its effective date is >= this effective date.
961 // * It is the first entry and it has no (insurance) provider.
962 // * There is no encounter that is earlier than the new effective date but
963 // on or after the old effective date.
964 // Otherwise insert a new entry.
968 if (strcmp($idrow['date'], $effective_date) > 0) {
972 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
976 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
977 "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
978 "date >= '" . $idrow['date'] . " 00:00:00'");
979 if ($ferow['count'] == 0) $replace = true;
986 // TBD: This is a bit dangerous in that a typo in entering the effective
987 // date can wipe out previous insurance history. So we want some data
988 // entry validation somewhere.
989 sqlStatement("DELETE FROM insurance_data WHERE " .
990 "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
991 "id != " . $idrow['id']);
994 $data['type'] = $type;
995 $data['provider'] = $provider;
996 $data['policy_number'] = $policy_number;
997 $data['group_number'] = $group_number;
998 $data['plan_name'] = $plan_name;
999 $data['subscriber_lname'] = $subscriber_lname;
1000 $data['subscriber_mname'] = $subscriber_mname;
1001 $data['subscriber_fname'] = $subscriber_fname;
1002 $data['subscriber_relationship'] = $subscriber_relationship;
1003 $data['subscriber_ss'] = $subscriber_ss;
1004 $data['subscriber_DOB'] = $subscriber_DOB;
1005 $data['subscriber_street'] = $subscriber_street;
1006 $data['subscriber_postal_code'] = $subscriber_postal_code;
1007 $data['subscriber_city'] = $subscriber_city;
1008 $data['subscriber_state'] = $subscriber_state;
1009 $data['subscriber_country'] = $subscriber_country;
1010 $data['subscriber_phone'] = $subscriber_phone;
1011 $data['subscriber_employer'] = $subscriber_employer;
1012 $data['subscriber_employer_city'] = $subscriber_employer_city;
1013 $data['subscriber_employer_street'] = $subscriber_employer_street;
1014 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1015 $data['subscriber_employer_state'] = $subscriber_employer_state;
1016 $data['subscriber_employer_country'] = $subscriber_employer_country;
1017 $data['copay'] = $copay;
1018 $data['subscriber_sex'] = $subscriber_sex;
1019 $data['pid'] = $pid;
1020 $data['date'] = $effective_date;
1021 $data['accept_assignment'] = $accept_assignment;
1022 updateInsuranceData($idrow['id'], $data);
1023 return $idrow['id'];
1026 return sqlInsert("INSERT INTO insurance_data SET
1028 provider = '$provider',
1029 policy_number = '$policy_number',
1030 group_number = '$group_number',
1031 plan_name = '$plan_name',
1032 subscriber_lname = '$subscriber_lname',
1033 subscriber_mname = '$subscriber_mname',
1034 subscriber_fname = '$subscriber_fname',
1035 subscriber_relationship = '$subscriber_relationship',
1036 subscriber_ss = '$subscriber_ss',
1037 subscriber_DOB = '$subscriber_DOB',
1038 subscriber_street = '$subscriber_street',
1039 subscriber_postal_code = '$subscriber_postal_code',
1040 subscriber_city = '$subscriber_city',
1041 subscriber_state = '$subscriber_state',
1042 subscriber_country = '$subscriber_country',
1043 subscriber_phone = '$subscriber_phone',
1044 subscriber_employer = '$subscriber_employer',
1045 subscriber_employer_city = '$subscriber_employer_city',
1046 subscriber_employer_street = '$subscriber_employer_street',
1047 subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1048 subscriber_employer_state = '$subscriber_employer_state',
1049 subscriber_employer_country = '$subscriber_employer_country',
1051 subscriber_sex = '$subscriber_sex',
1053 date = '$effective_date',
1054 accept_assignment = '$accept_assignment'
1059 // This is used internally only.
1060 function updateInsuranceData($id, $new)
1062 $fields = sqlListFields("insurance_data");
1065 while(list($key, $value) = each ($new)) {
1066 if (in_array($key, $fields)) {
1067 $use[$key] = $value;
1071 $sql = "UPDATE insurance_data SET ";
1072 while(list($key, $value) = each($use))
1073 $sql .= "`$key` = '$value', ";
1074 $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1079 function newHistoryData($pid, $new=false) {
1080 $arraySqlBind = array();
1081 $sql = "insert into history_data set pid = ?, date = NOW()";
1082 array_push($arraySqlBind,$pid);
1084 while(list($key, $value) = each($new)) {
1085 array_push($arraySqlBind,$value);
1086 $sql .= ", `$key` = ?";
1089 return sqlInsert($sql, $arraySqlBind );
1092 function updateHistoryData($pid,$new)
1094 $real = getHistoryData($pid);
1095 while(list($key, $value) = each ($new))
1096 $real[$key] = $value;
1098 // need to unset date, so can reset it below
1099 unset($real['date']);
1101 $arraySqlBind = array();
1102 $sql = "insert into history_data set `date` = NOW(), ";
1103 while(list($key, $value) = each($real)) {
1104 array_push($arraySqlBind,$value);
1105 $sql .= "`$key` = ?, ";
1107 $sql = substr($sql, 0, -2);
1109 return sqlInsert($sql, $arraySqlBind );
1112 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1113 $phone_biz,$phone_cell,$email,$pid="")
1115 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1116 if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1118 $db = $GLOBALS['adodb']['db'];
1119 $customer_info = array();
1121 $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1122 $result = $db->Execute($sql);
1123 if ($result && !$result->EOF) {
1124 $customer_info['foreign_update'] = true;
1125 $customer_info['foreign_id'] = $result->fields['foreign_id'];
1126 $customer_info['foreign_table'] = $result->fields['foreign_table'];
1129 ///xml rpc code to connect to accounting package and add user to it
1130 $customer_info['firstname'] = $fname;
1131 $customer_info['lastname'] = $lname;
1132 $customer_info['address'] = $street;
1133 $customer_info['suburb'] = $city;
1134 $customer_info['state'] = $state;
1135 $customer_info['postcode'] = $postal_code;
1137 //ezybiz wants state as a code rather than abbreviation
1138 $customer_info['geo_zone_id'] = "";
1139 $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1140 $db = $GLOBALS['adodb']['db'];
1141 $result = $db->Execute($sql);
1142 if ($result && !$result->EOF) {
1143 $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1146 //ezybiz wants country as a code rather than abbreviation
1147 $customer_info['geo_country_id'] = "";
1148 $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1149 $db = $GLOBALS['adodb']['db'];
1150 $result = $db->Execute($sql);
1151 if ($result && !$result->EOF) {
1152 $customer_info['geo_country_id'] = $result->fields['countries_id'];
1155 $customer_info['phone1'] = $phone_home;
1156 $customer_info['phone1comment'] = "Home Phone";
1157 $customer_info['phone2'] = $phone_biz;
1158 $customer_info['phone2comment'] = "Business Phone";
1159 $customer_info['phone3'] = $phone_cell;
1160 $customer_info['phone3comment'] = "Cell Phone";
1161 $customer_info['email'] = $email;
1162 $customer_info['customernumber'] = $pid;
1164 $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1165 $ws = new WSWrapper($function);
1167 // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1168 if (is_numeric($ws->value)) {
1169 $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1170 $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
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 getPatientAge($dobYMD, $nowYMD=null)
1181 // strip any dashes from the DOB
1182 $dobYMD = preg_replace("/-/", "", $dobYMD);
1183 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1185 // set the 'now' date values
1186 if ($nowYMD == null) {
1187 $nowDay = date("d");
1188 $nowMonth = date("m");
1189 $nowYear = date("Y");
1192 $nowDay = substr($nowYMD,6,2);
1193 $nowMonth = substr($nowYMD,4,2);
1194 $nowYear = substr($nowYMD,0,4);
1197 $dayDiff = $nowDay - $dobDay;
1198 $monthDiff = $nowMonth - $dobMonth;
1199 $yearDiff = $nowYear - $dobYear;
1201 $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1203 if ( $ageInMonths > 24 ) {
1205 if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1206 else if ($monthDiff < 0) { $age -= 1; }
1209 $age = "$ageInMonths month";
1216 // Returns Age in days
1217 // in months if < 2 years old
1218 // in years if > 2 years old
1219 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1220 // (optional) nowYMD is a date in YYYYMMDD format
1221 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1224 // strip any dashes from the DOB
1225 $dobYMD = preg_replace("/-/", "", $dobYMD);
1226 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1228 // set the 'now' date values
1229 if ($nowYMD == null) {
1230 $nowDay = date("d");
1231 $nowMonth = date("m");
1232 $nowYear = date("Y");
1235 $nowDay = substr($nowYMD,6,2);
1236 $nowMonth = substr($nowYMD,4,2);
1237 $nowYear = substr($nowYMD,0,4);
1241 $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1242 $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1243 $timediff = $nowtime - $dobtime;
1244 $age = $timediff / 86400;
1249 function dateToDB ($date)
1251 $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1256 // ----------------------------------------------------------------------------
1258 * DROPDOWN FOR COUNTRIES
1260 * build a dropdown with all countries from geo_country_reference
1262 * @param int $selected - id for selected record
1263 * @param string $name - the name/id for select form
1264 * @return void - just echo the html encoded string
1266 function dropdown_countries($selected = 0, $name = 'country_code') {
1267 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1269 $string = "<select name='$name' id='$name'>";
1270 while ( $row = sqlFetchArray($r) ) {
1271 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1272 $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1275 $string .= '</select>';
1280 // ----------------------------------------------------------------------------
1282 * DROPDOWN FOR YES/NO
1284 * build a dropdown with two options (yes - 1, no - 0)
1286 * @param int $selected - id for selected record
1287 * @param string $name - the name/id for select form
1288 * @return void - just echo the html encoded string
1290 function dropdown_yesno($selected = 0, $name = 'yesno') {
1291 $string = "<select name='$name' id='$name'>";
1293 $selected = (int)$selected;
1294 if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1295 else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1297 $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1298 $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1299 $string .= '</select>';
1304 // ----------------------------------------------------------------------------
1306 * DROPDOWN FOR MALE/FEMALE options
1308 * build a dropdown with three options (unselected/male/female)
1310 * @param int $selected - id for selected record
1311 * @param string $name - the name/id for select form
1312 * @return void - just echo the html encoded string
1314 function dropdown_sex($selected = 0, $name = 'sex') {
1315 $string = "<select name='$name' id='$name'>";
1317 if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1318 else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1319 else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1321 $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1322 $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1323 $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1324 $string .= '</select>';
1329 // ----------------------------------------------------------------------------
1331 * DROPDOWN FOR MARITAL STATUS
1333 * build a dropdown with marital status
1335 * @param int $selected - id for selected record
1336 * @param string $name - the name/id for select form
1337 * @return void - just echo the html encoded string
1339 function dropdown_marital($selected = 0, $name = 'status') {
1340 $string = "<select name='$name' id='$name'>";
1342 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1344 foreach ( $statii as $st ) {
1345 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1346 $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1349 $string .= '</select>';
1354 // ----------------------------------------------------------------------------
1356 * DROPDOWN FOR PROVIDERS
1358 * build a dropdown with all providers
1360 * @param int $selected - id for selected record
1361 * @param string $name - the name/id for select form
1362 * @return void - just echo the html encoded string
1364 function dropdown_providers($selected = 0, $name = 'status') {
1365 $provideri = getProviderInfo();
1367 $string = "<select name='$name' id='$name'>";
1368 $string .= '<option value="">' .xl('Unassigned'). '</option>';
1369 foreach ( $provideri as $s ) {
1370 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1371 $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1374 $string .= '</select>';
1379 // ----------------------------------------------------------------------------
1381 * DROPDOWN FOR INSURANCE COMPANIES
1383 * build a dropdown with all insurers
1385 * @param int $selected - id for selected record
1386 * @param string $name - the name/id for select form
1387 * @return void - just echo the html encoded string
1389 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1390 $insurancei = getInsuranceProviders();
1392 $string = "<select name='$name' id='$name'>";
1393 $string .= '<option value="0">Onbekend</option>';
1394 foreach ( $insurancei as $iid => $iname ) {
1395 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1396 $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1399 $string .= '</select>';
1405 // ----------------------------------------------------------------------------
1409 * return the name or the country code, function of arguments
1411 * @param int $country_code
1412 * @param string $country_name
1413 * @return string | int - name or code
1415 function country_code($country_code = 0, $country_name = '') {
1417 if ( $country_code ) {
1418 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1420 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1423 $db = $GLOBALS['adodb']['db'];
1424 $result = $db->Execute($sql);
1425 if ($result && !$result->EOF) {
1426 $strint = $result->fields['res'];
1432 function DBToDate ($date)
1434 $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1438 function get_patient_balance($pid) {
1439 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1440 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1441 "pid = ? AND activity = 1", array($pid) );
1442 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1443 "pid = ?", array($pid) );
1444 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1445 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1446 "pid = ?", array($pid) );
1447 return sprintf('%01.2f', $brow['amount'] + $srow['amount']
1448 - $drow['payments'] - $drow['adjustments']);
1450 else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1451 // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1452 $conn = $GLOBALS['adodb']['db'];
1453 $customer_info['id'] = 0;
1454 $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1455 "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1456 "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1457 "im.foreign_table = 'customer'";
1458 $result = $conn->Execute($sql);
1459 if($result && !$result->EOF) {
1460 $customer_info['id'] = $result->fields['foreign_id'];
1462 $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1463 $ws = new WSWrapper($function);
1464 if(is_numeric($ws->value)) {
1465 return sprintf('%01.2f', $ws->value);
1471 // Function to check if patient is deceased.
1473 // $pid - patient id
1474 // $date - date checking if deceased (will default to current date if blank)
1476 // If deceased, then will return the number of
1477 // days that patient has been deceased.
1478 // If not deceased, then will return false.
1479 function is_patient_deceased($pid,$date='') {
1481 // Set date to current if not set
1482 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1484 // Query for deceased status (gets days deceased if patient is deceased)
1485 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1486 "FROM `patient_data` " .
1487 "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date) );
1489 if (empty($results)) {
1490 // Patient is alive, so return false
1494 // Patient is dead, so return the number of days patient has been deceased.
1495 // Don't let it be zero days or else will confuse calls to this function.
1496 if ($results['days_deceased'] === 0) {
1497 $results['days_deceased'] = 1;
1499 return $results['days_deceased'];