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 ((strlen($lname) < 1)|| ($lname{0} != strtoupper($lname{0}))) {$search_for_pieces1 = '%';}
381 if ((strlen($fname) < 1)|| ($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);
401 for($iter=0; $row=sqlFetchArray($rez); $iter++)
402 $returnval[$iter] = $row;
404 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
408 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")
411 $sqlBindArray = array();
412 $where = "pubpid LIKE ? ";
413 array_push($sqlBindArray, $pid."%");
414 if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
415 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
416 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
417 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
418 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
419 array_push($sqlBindArray, $_SESSION{"authUser"});
423 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
424 if ($limit != "all") $sql .= " limit $start, $limit";
425 $rez = sqlStatement($sql, $sqlBindArray);
426 for($iter=0; $row=sqlFetchArray($rez); $iter++)
427 $returnval[$iter]=$row;
429 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
433 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")
435 $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%") );
437 $sqlBindArray = array();
439 for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
443 $where .= " ".add_escape_custom($row["field_id"])." like ? ";
444 array_push($sqlBindArray, "%".$searchTerm."%");
447 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
448 if ($limit != "all") $sql .= " limit $start, $limit";
449 $rez = sqlStatement($sql, $sqlBindArray);
450 for($iter=0; $row=sqlFetchArray($rez); $iter++)
451 $returnval[$iter]=$row;
452 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
456 function getByPatientDemographicsFilter($searchFields, $searchTerm = "%",
457 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
458 $orderby = "lname ASC, fname ASC", $limit="all", $start="0", $search_service_code='')
460 $layoutCols = split( '~', $searchFields );
461 $sqlBindArray = array();
464 foreach ($layoutCols as $val) {
465 if (empty($val)) continue;
470 $where .= " ".add_escape_custom($val)." = ? ";
471 array_push($sqlBindArray, $searchTerm);
474 $where .= " ".add_escape_custom($val)." like ? ";
475 array_push($sqlBindArray, $searchTerm."%");
480 // If no search terms, ensure valid syntax.
481 if ($i == 0) $where = "1 = 1";
483 // If a non-empty service code was given, then restrict to patients who
484 // have been provided that service. Since the code is used in a LIKE
485 // clause, % and _ wildcards are supported.
486 if ($search_service_code) {
487 $where = "( $where ) AND " .
488 "( SELECT COUNT(*) FROM billing AS b WHERE " .
489 "b.pid = patient_data.pid AND " .
490 "b.activity = 1 AND " .
491 "b.code_type != 'COPAY' AND " .
494 array_push($sqlBindArray, $search_service_code);
497 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
498 if ($limit != "all") $sql .= " limit $start, $limit";
499 $rez = sqlStatement($sql, $sqlBindArray);
500 for($iter=0; $row=sqlFetchArray($rez); $iter++)
501 $returnval[$iter]=$row;
502 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
506 // return a collection of Patient PIDs
507 // new arg style by JRM March 2008
508 // 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")
509 function getPatientPID($args)
512 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
513 $orderby = "lname ASC, fname ASC";
517 // alter default values if defined in the passed in args
518 if (isset($args['pid'])) { $pid = $args['pid']; }
519 if (isset($args['given'])) { $given = $args['given']; }
520 if (isset($args['orderby'])) { $orderby = $args['orderby']; }
521 if (isset($args['limit'])) { $limit = $args['limit']; }
522 if (isset($args['start'])) { $start = $args['start']; }
525 if ($pid == -1) $pid = "%";
526 elseif (empty($pid)) $pid = "NULL";
528 if (strstr($pid,"%")) $command = "like";
530 $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
531 if ($limit != "all") $sql .= " limit $start, $limit";
533 $rez = sqlStatement($sql);
534 for($iter=0; $row=sqlFetchArray($rez); $iter++)
535 $returnval[$iter]=$row;
540 /* return a patient's name in the format LAST, FIRST */
541 function getPatientName($pid) {
542 if (empty($pid)) return "";
543 $patientData = getPatientPID(array("pid"=>$pid));
544 if (empty($patientData[0]['lname'])) return "";
545 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
549 /* find patient data by DOB */
550 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
552 $DOB = fixDate($DOB, $DOB);
553 $sqlBindArray = array();
554 $where = "DOB like ? ";
555 array_push($sqlBindArray, $DOB."%");
556 if (!empty($GLOBALS['pt_restrict_field'])) {
557 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
558 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
559 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
560 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
561 array_push($sqlBindArray, $_SESSION{"authUser"});
565 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
567 if ($limit != "all") $sql .= " LIMIT $start, $limit";
569 $rez = sqlStatement($sql, $sqlBindArray);
570 for($iter=0; $row=sqlFetchArray($rez); $iter++)
571 $returnval[$iter]=$row;
573 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
577 /* find patient data by SSN */
578 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
580 $sqlBindArray = array();
581 $where = "ss LIKE ?";
582 array_push($sqlBindArray, $ss."%");
583 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
584 if ($limit != "all") $sql .= " LIMIT $start, $limit";
586 $rez = sqlStatement($sql, $sqlBindArray);
587 for($iter=0; $row=sqlFetchArray($rez); $iter++)
588 $returnval[$iter]=$row;
590 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
594 //(CHEMED) Search by phone number
595 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
597 $phone = ereg_replace( "[[:punct:]]","", $phone );
598 $sqlBindArray = array();
599 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
600 array_push($sqlBindArray, $phone);
601 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
602 if ($limit != "all") $sql .= " LIMIT $start, $limit";
604 $rez = sqlStatement($sql, $sqlBindArray);
605 for($iter=0; $row=sqlFetchArray($rez); $iter++)
606 $returnval[$iter]=$row;
608 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
612 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
614 $sql="select $given from patient_data order by $orderby";
617 $sql .= " limit $start, $limit";
619 $rez = sqlStatement($sql);
620 for($iter=0; $row=sqlFetchArray($rez); $iter++)
621 $returnval[$iter]=$row;
626 //----------------------input functions
627 function newPatientData( $db_id="",
645 $contact_relationship = "",
652 $migrantseasonal = "",
654 $monthly_income = "",
656 $financial_review = "",
669 $drivers_license = "",
675 $DOB = fixDate($DOB);
676 $regdate = fixDate($regdate);
679 $referral_source = '';
681 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
682 // Check for brain damage:
683 if ($db_id != $rez['id']) {
684 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
685 $rez['id'] . "' to '$db_id' for pid '$pid'";
688 $fitness = $rez['fitness'];
689 $referral_source = $rez['referral_source'];
692 // Get the default price level.
693 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
694 "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
695 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
697 $query = ("replace into patient_data set
706 postal_code='$postal_code',
709 country_code='$country_code',
710 drivers_license='$drivers_license',
712 occupation='$occupation',
713 phone_home='$phone_home',
714 phone_biz='$phone_biz',
715 phone_contact='$phone_contact',
717 contact_relationship='$contact_relationship',
718 referrer='$referrer',
719 referrerID='$referrerID',
721 language='$language',
722 ethnoracial='$ethnoracial',
723 interpretter='$interpretter',
724 migrantseasonal='$migrantseasonal',
725 family_size='$family_size',
726 monthly_income='$monthly_income',
727 homeless='$homeless',
728 financial_review='$financial_review',
731 providerID = '$providerID',
732 genericname1 = '$genericname1',
733 genericval1 = '$genericval1',
734 genericname2 = '$genericname2',
735 genericval2 = '$genericval2',
736 phone_cell = '$phone_cell',
737 pharmacy_id = '$pharmacy_id',
738 hipaa_mail = '$hipaa_mail',
739 hipaa_voice = '$hipaa_voice',
740 hipaa_notice = '$hipaa_notice',
741 hipaa_message = '$hipaa_message',
744 referral_source='$referral_source',
746 pricelevel='$pricelevel',
749 $id = sqlInsert($query);
752 // find the last inserted id for new patient case
753 $db_id = mysql_insert_id();
756 $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
758 sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
759 $phone_biz,$phone_cell,$email,$pid);
764 // Supported input date formats are:
766 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
768 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
770 function fixDate($date, $default="0000-00-00") {
771 $fixed_date = $default;
773 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
774 $dmy = preg_split("'[/.-]'", $date);
776 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
778 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
779 if ($dmy[2] < 1000) $dmy[2] += 1900;
780 if ($dmy[2] < 1910) $dmy[2] += 100;
782 // phone_country_code indicates format of ambiguous input dates.
783 if ($GLOBALS['phone_country_code'] == 1)
784 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
786 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
793 function pdValueOrNull($key, $value) {
794 if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
795 substr($key, 0, 8) == 'userdate') &&
796 (empty($value) || $value == '0000-00-00'))
805 // Create or update patient data from an array.
807 function updatePatientData($pid, $new, $create=false)
809 /*******************************************************************
810 $real = getPatientData($pid);
811 $new['DOB'] = fixDate($new['DOB']);
812 while(list($key, $value) = each ($new))
813 $real[$key] = $value;
814 $real['date'] = "'+NOW()+'";
816 $sql = "insert into patient_data set ";
817 while(list($key, $value) = each($real))
818 $sql .= $key." = '$value', ";
819 $sql = substr($sql, 0, -2);
820 return sqlInsert($sql);
821 *******************************************************************/
823 // The above was broken, though seems intent to insert a new patient_data
824 // row for each update. A good idea, but nothing is doing that yet so
825 // the code below does not yet attempt it.
827 $new['DOB'] = fixDate($new['DOB']);
830 $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
831 foreach ($new as $key => $value) {
832 if ($key == 'id') continue;
833 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
835 $db_id = sqlInsert($sql);
839 $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
840 // Check for brain damage:
841 if ($pid != $rez['pid']) {
842 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
843 $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
846 $sql = "UPDATE patient_data SET date = NOW()";
847 foreach ($new as $key => $value) {
848 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
850 $sql .= " WHERE id = '$db_id'";
854 $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
855 sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
856 $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
857 $rez['phone_cell'],$rez['email'],$rez['pid']);
862 function newEmployerData( $pid,
871 return sqlInsert("insert into employer_data set
874 postal_code='$postal_code',
883 // Create or update employer data from an array.
885 function updateEmployerData($pid, $new, $create=false)
887 $colnames = array('name','street','city','state','postal_code','country');
890 $set .= "pid = '$pid', date = NOW()";
891 foreach ($colnames as $key) {
892 $value = isset($new[$key]) ? $new[$key] : '';
893 $set .= ", `$key` = '$value'";
895 return sqlInsert("INSERT INTO employer_data SET $set");
899 $old = getEmployerData($pid);
901 foreach ($colnames as $key) {
902 $value = empty($old[$key]) ? '' : addslashes($old[$key]);
903 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
907 $set .= "`$key` = '$value', ";
910 $set .= "pid = '$pid', date = NOW()";
911 return sqlInsert("INSERT INTO employer_data SET $set");
917 // This updates or adds the given insurance data info, while retaining any
918 // previously added insurance_data rows that should be preserved.
919 // This does not directly support the maintenance of non-current insurance.
921 function newInsuranceData(
928 $subscriber_lname = "",
929 $subscriber_mname = "",
930 $subscriber_fname = "",
931 $subscriber_relationship = "",
933 $subscriber_DOB = "",
934 $subscriber_street = "",
935 $subscriber_postal_code = "",
936 $subscriber_city = "",
937 $subscriber_state = "",
938 $subscriber_country = "",
939 $subscriber_phone = "",
940 $subscriber_employer = "",
941 $subscriber_employer_street = "",
942 $subscriber_employer_city = "",
943 $subscriber_employer_postal_code = "",
944 $subscriber_employer_state = "",
945 $subscriber_employer_country = "",
947 $subscriber_sex = "",
948 $effective_date = "0000-00-00",
949 $accept_assignment = "TRUE")
951 if (strlen($type) <= 0) return FALSE;
953 // If a bad date was passed, err on the side of caution.
954 $effective_date = fixDate($effective_date, date('Y-m-d'));
956 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
957 "pid = '$pid' AND type = '$type' ORDER BY date DESC");
958 $idrow = sqlFetchArray($idres);
960 // Replace the most recent entry in any of the following cases:
961 // * Its effective date is >= this effective date.
962 // * It is the first entry and it has no (insurance) provider.
963 // * There is no encounter that is earlier than the new effective date but
964 // on or after the old effective date.
965 // Otherwise insert a new entry.
969 if (strcmp($idrow['date'], $effective_date) > 0) {
973 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
977 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
978 "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
979 "date >= '" . $idrow['date'] . " 00:00:00'");
980 if ($ferow['count'] == 0) $replace = true;
987 // TBD: This is a bit dangerous in that a typo in entering the effective
988 // date can wipe out previous insurance history. So we want some data
989 // entry validation somewhere.
990 sqlStatement("DELETE FROM insurance_data WHERE " .
991 "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
992 "id != " . $idrow['id']);
995 $data['type'] = $type;
996 $data['provider'] = $provider;
997 $data['policy_number'] = $policy_number;
998 $data['group_number'] = $group_number;
999 $data['plan_name'] = $plan_name;
1000 $data['subscriber_lname'] = $subscriber_lname;
1001 $data['subscriber_mname'] = $subscriber_mname;
1002 $data['subscriber_fname'] = $subscriber_fname;
1003 $data['subscriber_relationship'] = $subscriber_relationship;
1004 $data['subscriber_ss'] = $subscriber_ss;
1005 $data['subscriber_DOB'] = $subscriber_DOB;
1006 $data['subscriber_street'] = $subscriber_street;
1007 $data['subscriber_postal_code'] = $subscriber_postal_code;
1008 $data['subscriber_city'] = $subscriber_city;
1009 $data['subscriber_state'] = $subscriber_state;
1010 $data['subscriber_country'] = $subscriber_country;
1011 $data['subscriber_phone'] = $subscriber_phone;
1012 $data['subscriber_employer'] = $subscriber_employer;
1013 $data['subscriber_employer_city'] = $subscriber_employer_city;
1014 $data['subscriber_employer_street'] = $subscriber_employer_street;
1015 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1016 $data['subscriber_employer_state'] = $subscriber_employer_state;
1017 $data['subscriber_employer_country'] = $subscriber_employer_country;
1018 $data['copay'] = $copay;
1019 $data['subscriber_sex'] = $subscriber_sex;
1020 $data['pid'] = $pid;
1021 $data['date'] = $effective_date;
1022 $data['accept_assignment'] = $accept_assignment;
1023 updateInsuranceData($idrow['id'], $data);
1024 return $idrow['id'];
1027 return sqlInsert("INSERT INTO insurance_data SET
1029 provider = '$provider',
1030 policy_number = '$policy_number',
1031 group_number = '$group_number',
1032 plan_name = '$plan_name',
1033 subscriber_lname = '$subscriber_lname',
1034 subscriber_mname = '$subscriber_mname',
1035 subscriber_fname = '$subscriber_fname',
1036 subscriber_relationship = '$subscriber_relationship',
1037 subscriber_ss = '$subscriber_ss',
1038 subscriber_DOB = '$subscriber_DOB',
1039 subscriber_street = '$subscriber_street',
1040 subscriber_postal_code = '$subscriber_postal_code',
1041 subscriber_city = '$subscriber_city',
1042 subscriber_state = '$subscriber_state',
1043 subscriber_country = '$subscriber_country',
1044 subscriber_phone = '$subscriber_phone',
1045 subscriber_employer = '$subscriber_employer',
1046 subscriber_employer_city = '$subscriber_employer_city',
1047 subscriber_employer_street = '$subscriber_employer_street',
1048 subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1049 subscriber_employer_state = '$subscriber_employer_state',
1050 subscriber_employer_country = '$subscriber_employer_country',
1052 subscriber_sex = '$subscriber_sex',
1054 date = '$effective_date',
1055 accept_assignment = '$accept_assignment'
1060 // This is used internally only.
1061 function updateInsuranceData($id, $new)
1063 $fields = sqlListFields("insurance_data");
1066 while(list($key, $value) = each ($new)) {
1067 if (in_array($key, $fields)) {
1068 $use[$key] = $value;
1072 $sql = "UPDATE insurance_data SET ";
1073 while(list($key, $value) = each($use))
1074 $sql .= "`$key` = '$value', ";
1075 $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1080 function newHistoryData($pid, $new=false) {
1081 $arraySqlBind = array();
1082 $sql = "insert into history_data set pid = ?, date = NOW()";
1083 array_push($arraySqlBind,$pid);
1085 while(list($key, $value) = each($new)) {
1086 array_push($arraySqlBind,$value);
1087 $sql .= ", `$key` = ?";
1090 return sqlInsert($sql, $arraySqlBind );
1093 function updateHistoryData($pid,$new)
1095 $real = getHistoryData($pid);
1096 while(list($key, $value) = each ($new))
1097 $real[$key] = $value;
1099 // need to unset date, so can reset it below
1100 unset($real['date']);
1102 $arraySqlBind = array();
1103 $sql = "insert into history_data set `date` = NOW(), ";
1104 while(list($key, $value) = each($real)) {
1105 array_push($arraySqlBind,$value);
1106 $sql .= "`$key` = ?, ";
1108 $sql = substr($sql, 0, -2);
1110 return sqlInsert($sql, $arraySqlBind );
1113 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1114 $phone_biz,$phone_cell,$email,$pid="")
1116 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1117 if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1119 $db = $GLOBALS['adodb']['db'];
1120 $customer_info = array();
1122 $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1123 $result = $db->Execute($sql);
1124 if ($result && !$result->EOF) {
1125 $customer_info['foreign_update'] = true;
1126 $customer_info['foreign_id'] = $result->fields['foreign_id'];
1127 $customer_info['foreign_table'] = $result->fields['foreign_table'];
1130 ///xml rpc code to connect to accounting package and add user to it
1131 $customer_info['firstname'] = $fname;
1132 $customer_info['lastname'] = $lname;
1133 $customer_info['address'] = $street;
1134 $customer_info['suburb'] = $city;
1135 $customer_info['state'] = $state;
1136 $customer_info['postcode'] = $postal_code;
1138 //ezybiz wants state as a code rather than abbreviation
1139 $customer_info['geo_zone_id'] = "";
1140 $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1141 $db = $GLOBALS['adodb']['db'];
1142 $result = $db->Execute($sql);
1143 if ($result && !$result->EOF) {
1144 $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1147 //ezybiz wants country as a code rather than abbreviation
1148 $customer_info['geo_country_id'] = "";
1149 $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1150 $db = $GLOBALS['adodb']['db'];
1151 $result = $db->Execute($sql);
1152 if ($result && !$result->EOF) {
1153 $customer_info['geo_country_id'] = $result->fields['countries_id'];
1156 $customer_info['phone1'] = $phone_home;
1157 $customer_info['phone1comment'] = "Home Phone";
1158 $customer_info['phone2'] = $phone_biz;
1159 $customer_info['phone2comment'] = "Business Phone";
1160 $customer_info['phone3'] = $phone_cell;
1161 $customer_info['phone3comment'] = "Cell Phone";
1162 $customer_info['email'] = $email;
1163 $customer_info['customernumber'] = $pid;
1165 $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1166 $ws = new WSWrapper($function);
1168 // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1169 if (is_numeric($ws->value)) {
1170 $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1171 $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1176 // in months if < 2 years old
1177 // in years if > 2 years old
1178 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1179 // (optional) nowYMD is a date in YYYYMMDD format
1180 function getPatientAge($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);
1198 $dayDiff = $nowDay - $dobDay;
1199 $monthDiff = $nowMonth - $dobMonth;
1200 $yearDiff = $nowYear - $dobYear;
1202 $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1204 if ( $ageInMonths > 24 ) {
1206 if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1207 else if ($monthDiff < 0) { $age -= 1; }
1210 $age = "$ageInMonths month";
1217 // Returns Age in days
1218 // in months if < 2 years old
1219 // in years if > 2 years old
1220 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1221 // (optional) nowYMD is a date in YYYYMMDD format
1222 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1225 // strip any dashes from the DOB
1226 $dobYMD = preg_replace("/-/", "", $dobYMD);
1227 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1229 // set the 'now' date values
1230 if ($nowYMD == null) {
1231 $nowDay = date("d");
1232 $nowMonth = date("m");
1233 $nowYear = date("Y");
1236 $nowDay = substr($nowYMD,6,2);
1237 $nowMonth = substr($nowYMD,4,2);
1238 $nowYear = substr($nowYMD,0,4);
1242 $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1243 $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1244 $timediff = $nowtime - $dobtime;
1245 $age = $timediff / 86400;
1250 function dateToDB ($date)
1252 $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1257 // ----------------------------------------------------------------------------
1259 * DROPDOWN FOR COUNTRIES
1261 * build a dropdown with all countries from geo_country_reference
1263 * @param int $selected - id for selected record
1264 * @param string $name - the name/id for select form
1265 * @return void - just echo the html encoded string
1267 function dropdown_countries($selected = 0, $name = 'country_code') {
1268 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1270 $string = "<select name='$name' id='$name'>";
1271 while ( $row = sqlFetchArray($r) ) {
1272 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1273 $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1276 $string .= '</select>';
1281 // ----------------------------------------------------------------------------
1283 * DROPDOWN FOR YES/NO
1285 * build a dropdown with two options (yes - 1, no - 0)
1287 * @param int $selected - id for selected record
1288 * @param string $name - the name/id for select form
1289 * @return void - just echo the html encoded string
1291 function dropdown_yesno($selected = 0, $name = 'yesno') {
1292 $string = "<select name='$name' id='$name'>";
1294 $selected = (int)$selected;
1295 if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1296 else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1298 $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1299 $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1300 $string .= '</select>';
1305 // ----------------------------------------------------------------------------
1307 * DROPDOWN FOR MALE/FEMALE options
1309 * build a dropdown with three options (unselected/male/female)
1311 * @param int $selected - id for selected record
1312 * @param string $name - the name/id for select form
1313 * @return void - just echo the html encoded string
1315 function dropdown_sex($selected = 0, $name = 'sex') {
1316 $string = "<select name='$name' id='$name'>";
1318 if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1319 else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1320 else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1322 $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1323 $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1324 $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1325 $string .= '</select>';
1330 // ----------------------------------------------------------------------------
1332 * DROPDOWN FOR MARITAL STATUS
1334 * build a dropdown with marital status
1336 * @param int $selected - id for selected record
1337 * @param string $name - the name/id for select form
1338 * @return void - just echo the html encoded string
1340 function dropdown_marital($selected = 0, $name = 'status') {
1341 $string = "<select name='$name' id='$name'>";
1343 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1345 foreach ( $statii as $st ) {
1346 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1347 $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1350 $string .= '</select>';
1355 // ----------------------------------------------------------------------------
1357 * DROPDOWN FOR PROVIDERS
1359 * build a dropdown with all providers
1361 * @param int $selected - id for selected record
1362 * @param string $name - the name/id for select form
1363 * @return void - just echo the html encoded string
1365 function dropdown_providers($selected = 0, $name = 'status') {
1366 $provideri = getProviderInfo();
1368 $string = "<select name='$name' id='$name'>";
1369 $string .= '<option value="">' .xl('Unassigned'). '</option>';
1370 foreach ( $provideri as $s ) {
1371 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1372 $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1375 $string .= '</select>';
1380 // ----------------------------------------------------------------------------
1382 * DROPDOWN FOR INSURANCE COMPANIES
1384 * build a dropdown with all insurers
1386 * @param int $selected - id for selected record
1387 * @param string $name - the name/id for select form
1388 * @return void - just echo the html encoded string
1390 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1391 $insurancei = getInsuranceProviders();
1393 $string = "<select name='$name' id='$name'>";
1394 $string .= '<option value="0">Onbekend</option>';
1395 foreach ( $insurancei as $iid => $iname ) {
1396 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1397 $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1400 $string .= '</select>';
1406 // ----------------------------------------------------------------------------
1410 * return the name or the country code, function of arguments
1412 * @param int $country_code
1413 * @param string $country_name
1414 * @return string | int - name or code
1416 function country_code($country_code = 0, $country_name = '') {
1418 if ( $country_code ) {
1419 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1421 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1424 $db = $GLOBALS['adodb']['db'];
1425 $result = $db->Execute($sql);
1426 if ($result && !$result->EOF) {
1427 $strint = $result->fields['res'];
1433 function DBToDate ($date)
1435 $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1439 function get_patient_balance($pid) {
1440 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1441 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1442 "pid = ? AND activity = 1", array($pid) );
1443 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1444 "pid = ?", array($pid) );
1445 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1446 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1447 "pid = ?", array($pid) );
1448 return sprintf('%01.2f', $brow['amount'] + $srow['amount']
1449 - $drow['payments'] - $drow['adjustments']);
1451 else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1452 // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1453 $conn = $GLOBALS['adodb']['db'];
1454 $customer_info['id'] = 0;
1455 $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1456 "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1457 "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1458 "im.foreign_table = 'customer'";
1459 $result = $conn->Execute($sql);
1460 if($result && !$result->EOF) {
1461 $customer_info['id'] = $result->fields['foreign_id'];
1463 $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1464 $ws = new WSWrapper($function);
1465 if(is_numeric($ws->value)) {
1466 return sprintf('%01.2f', $ws->value);
1472 // Function to check if patient is deceased.
1474 // $pid - patient id
1475 // $date - date checking if deceased (will default to current date if blank)
1477 // If deceased, then will return the number of
1478 // days that patient has been deceased.
1479 // If not deceased, then will return false.
1480 function is_patient_deceased($pid,$date='') {
1482 // Set date to current if not set
1483 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1485 // Query for deceased status (gets days deceased if patient is deceased)
1486 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1487 "FROM `patient_data` " .
1488 "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date) );
1490 if (empty($results)) {
1491 // Patient is alive, so return false
1495 // Patient is dead, so return the number of days patient has been deceased.
1496 // Don't let it be zero days or else will confuse calls to this function.
1497 if ($results['days_deceased'] === 0) {
1498 $results['days_deceased'] = 1;
1500 return $results['days_deceased'];