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 // Hard-coding this array because its values and meanings are fixed by the 837p
24 // standard and we don't want people messing with them.
25 $policy_types = array(
27 '12' => xl('Working Aged Beneficiary or Spouse with Employer Group Health Plan'),
28 '13' => xl('End-Stage Renal Disease Beneficiary in MCP with Employer`s Group Plan'),
29 '14' => xl('No-fault Insurance including Auto is Primary'),
30 '15' => xl('Worker`s Compensation'),
31 '16' => xl('Public Health Service (PHS) or Other Federal Agency'),
32 '41' => xl('Black Lung'),
33 '42' => xl('Veteran`s Administration'),
34 '43' => xl('Disabled Beneficiary Under Age 65 with Large Group Health Plan (LGHP)'),
35 '47' => xl('Other Liability Insurance is Primary'),
38 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS") {
39 $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
40 return sqlQuery($sql, array($pid) );
43 function getLanguages() {
44 $returnval = array('','english');
45 $sql = "select distinct lower(language) as language from patient_data";
46 $rez = sqlStatement($sql);
47 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
48 if (($row["language"] != "english") && ($row["language"] != "")) {
49 array_push($returnval, $row["language"]);
55 function getInsuranceProvider($ins_id) {
57 $sql = "select name from insurance_companies where id=?";
58 $row = sqlQuery($sql,array($ins_id));
63 function getInsuranceProviders() {
67 $sql = "select name, id from insurance_companies order by name, id";
68 $rez = sqlStatement($sql);
69 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
70 $returnval[$row['id']] = $row['name'];
74 // Please leave this here. I have a user who wants to see zip codes and PO
75 // box numbers listed along with the insurance company names, as many companies
76 // have different billing addresses for different plans. -- Rod Roark
79 $sql = "select insurance_companies.name, insurance_companies.id, " .
80 "addresses.zip, addresses.line1 " .
81 "from insurance_companies, addresses " .
82 "where addresses.foreign_id = insurance_companies.id " .
83 "order by insurance_companies.name, addresses.zip";
85 $rez = sqlStatement($sql);
87 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
88 preg_match("/\d+/", $row['line1'], $matches);
89 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
90 "," . $matches[0] . ")";
97 function getProviders() {
98 $returnval = array("");
99 $sql = "select fname, lname from users where authorized = 1 and " .
100 "active = 1 and username != ''";
101 $rez = sqlStatement($sql);
102 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
103 if (($row["fname"] != "") && ($row["lname"] != "")) {
104 array_push($returnval, $row["fname"] . " " . $row["lname"]);
110 // ----------------------------------------------------------------------------
111 // Get one facility row. If the ID is not specified, then get either the
112 // "main" (billing) facility, or the default facility of the currently
113 // logged-in user. This was created to support genFacilityTitle() but
114 // may find additional uses.
116 function getFacility($facid=0) {
118 //create a sql binding array
119 $sqlBindArray = array();
122 $query = "SELECT * FROM facility WHERE id = ?";
123 array_push($sqlBindArray,$facid);
125 else if ($facid == 0) {
126 $query = "SELECT * FROM facility ORDER BY " .
127 "billing_location DESC, service_location, id LIMIT 1";
130 $query = "SELECT facility.* FROM users, facility WHERE " .
131 "users.id = ? AND " .
132 "facility.id = users.facility_id";
133 array_push($sqlBindArray,$_SESSION['authUserID']);
135 return sqlQuery($query,$sqlBindArray);
138 // Generate a report title including report name and facility name, address
141 function genFacilityTitle($repname='', $facid=0) {
143 $s .= "<table class='ftitletable'>\n";
145 $s .= " <td class='ftitlecell1'>$repname</td>\n";
146 $s .= " <td class='ftitlecell2'>\n";
147 $r = getFacility($facid);
149 $s .= "<b>" . htmlspecialchars( $r['name'], ENT_NOQUOTES) . "</b>\n";
150 if ($r['street']) $s .= "<br />" . htmlspecialchars( $r['street'], ENT_NOQUOTES) . "\n";
151 if ($r['city'] || $r['state'] || $r['postal_code']) {
153 if ($r['city']) $s .= htmlspecialchars( $r['city'], ENT_NOQUOTES);
155 if ($r['city']) $s .= ", \n";
156 $s .= htmlspecialchars( $r['state'], ENT_NOQUOTES);
158 if ($r['postal_code']) $s .= " " . htmlspecialchars( $r['postal_code'], ENT_NOQUOTES);
161 if ($r['country_code']) $s .= "<br />" . htmlspecialchars( $r['country_code'], ENT_NOQUOTES) . "\n";
162 if (preg_match('/[1-9]/', $r['phone'])) $s .= "<br />" . htmlspecialchars( $r['phone'], ENT_NOQUOTES) . "\n";
173 returns all facilities or just the id for the first one
174 (FACILITY FILTERING (lemonsoftware))
176 @param string - if 'first' return first facility ordered by id
177 @return array | int for 'first' case
179 function getFacilities($first = '') {
180 $r = sqlStatement("SELECT * FROM facility ORDER BY id");
182 while ( $row = sqlFetchArray($r) ) {
186 if ( $first == 'first') {
187 return $ret[0]['id'];
194 GET SERVICE FACILITIES
196 returns all service_location facilities or just the id for the first one
197 (FACILITY FILTERING (CHEMED))
199 @param string - if 'first' return first facility ordered by id
200 @return array | int for 'first' case
202 function getServiceFacilities($first = '') {
203 $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
205 while ( $row = sqlFetchArray($r) ) {
209 if ( $first == 'first') {
210 return $ret[0]['id'];
216 //(CHEMED) facility filter
217 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
219 if ($providers_only === 'any') {
220 $param1 = " AND authorized = 1 AND active = 1 ";
222 else if ($providers_only) {
223 $param1 = " AND authorized = 1 AND calendar = 1 ";
226 //--------------------------------
227 //(CHEMED) facility filter
230 if ($GLOBALS['restrict_user_facility']) {
231 $param2 = " AND (facility_id = $facility
235 where tablename = 'users'
241 $param2 = " AND facility_id = $facility ";
244 //--------------------------------
247 if ($providerID == "%") {
250 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
251 "from users where username != '' and active = 1 and id $command '" .
252 mysql_real_escape_string($providerID) . "' " . $param1 . $param2;
253 // sort by last name -- JRM June 2008
254 $query .= " ORDER BY lname, fname ";
255 $rez = sqlStatement($query);
256 for($iter=0; $row=sqlFetchArray($rez); $iter++)
257 $returnval[$iter]=$row;
259 //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
260 //accessible from $resultval['key']
263 $akeys = array_keys($returnval[0]);
264 foreach($akeys as $key) {
265 $returnval[0][$key] = $returnval[0][$key];
271 //same as above but does not reduce if only 1 row returned
272 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
274 if ($providers_only) {
275 $param1 = "AND authorized=1";
278 if ($providerID == "%") {
281 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
282 "from users where active = 1 and username != '' and id $command '" .
283 mysql_real_escape_string($providerID) . "' " . $param1;
285 $rez = sqlStatement($query);
286 for($iter=0; $row=sqlFetchArray($rez); $iter++)
287 $returnval[$iter]=$row;
292 function getProviderName($providerID) {
293 $pi = getProviderInfo($providerID, 'any');
294 if (strlen($pi[0]["lname"]) > 0) {
295 return $pi[0]['fname'] . " " . $pi[0]['lname'];
300 function getProviderId($providerName) {
301 $query = "select id from users where username = ?";
302 $rez = sqlStatement($query, array($providerName) );
303 for($iter=0; $row=sqlFetchArray($rez); $iter++)
304 $returnval[$iter]=$row;
308 function getEthnoRacials() {
309 $returnval = array("");
310 $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
311 $rez = sqlStatement($sql);
312 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
313 if (($row["ethnoracial"] != "")) {
314 array_push($returnval, $row["ethnoracial"]);
320 function getHistoryData($pid, $given = "*", $dateStart='',$dateEnd='')
323 if ($dateStart && $dateEnd) {
324 $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd) );
326 else if ($dateStart && !$dateEnd) {
327 $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart) );
329 else if (!$dateStart && $dateEnd) {
330 $res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd) );
333 $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid) );
339 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
340 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
342 $sql = "select $given from insurance_data as insd " .
343 "left join insurance_companies as ic on ic.id = insd.provider " .
344 "where pid = ? and type = ? order by date DESC limit 1";
345 return sqlQuery($sql, array($pid, $type) );
348 function getInsuranceDataByDate($pid, $date, $type,
349 $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
350 { // this must take the date in the following manner: YYYY-MM-DD
351 // this function recalls the insurance value that was most recently enterred from the
352 // given date. it will call up most recent records up to and on the date given,
353 // but not records enterred after the given date
354 $sql = "select $given from insurance_data as insd " .
355 "left join insurance_companies as ic on ic.id = provider " .
356 "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
357 "type=? order by date DESC limit 1";
358 return sqlQuery($sql, array($pid,$date,$type) );
361 function getEmployerData($pid, $given = "*")
363 $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
364 return sqlQuery($sql, array($pid) );
367 function _set_patient_inc_count($limit, $count, $where, $whereBindArray=array()) {
368 // When the limit is exceeded, find out what the unlimited count would be.
369 $GLOBALS['PATIENT_INC_COUNT'] = $count;
370 // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
371 if ($limit != "all") {
372 $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
373 $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
377 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")
379 // Allow the last name to be followed by a comma and some part of a first name.
380 // New behavior for searches:
381 // Allows comma alone followed by some part of a first name
382 // If the first letter of either name is capital, searches for name starting
383 // with given substring (the expected behavior). If it is lower case, it
384 // it searches for the substring anywhere in the name. This applies to either
385 // last name or first name or both. The arbitrary limit of 100 results is set
386 // in the sql query below. --Mark Leeds
387 $lname = trim($lname);
389 if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
390 $lname = trim($matches[1]);
391 $fname = trim($matches[2]);
393 $search_for_pieces1 = '';
394 $search_for_pieces2 = '';
395 if ((strlen($lname) < 1)|| ($lname{0} != strtoupper($lname{0}))) {$search_for_pieces1 = '%';}
396 if ((strlen($fname) < 1)|| ($fname{0} != strtoupper($fname{0}))) {$search_for_pieces2 = '%';}
398 $sqlBindArray = array();
399 $where = "lname LIKE ? AND fname LIKE ? ";
400 array_push($sqlBindArray, $search_for_pieces1.$lname."%", $search_for_pieces2.$fname."%");
401 if (!empty($GLOBALS['pt_restrict_field'])) {
402 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
403 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
404 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
405 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
406 array_push($sqlBindArray, $_SESSION{"authUser"});
410 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
411 if ($limit != "all") $sql .= " LIMIT $start, $limit";
413 $rez = sqlStatement($sql, $sqlBindArray);
416 for($iter=0; $row=sqlFetchArray($rez); $iter++)
417 $returnval[$iter] = $row;
419 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
423 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")
426 $sqlBindArray = array();
427 $where = "pubpid LIKE ? ";
428 array_push($sqlBindArray, $pid."%");
429 if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
430 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
431 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
432 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
433 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
434 array_push($sqlBindArray, $_SESSION{"authUser"});
438 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
439 if ($limit != "all") $sql .= " limit $start, $limit";
440 $rez = sqlStatement($sql, $sqlBindArray);
441 for($iter=0; $row=sqlFetchArray($rez); $iter++)
442 $returnval[$iter]=$row;
444 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
448 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")
450 $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%") );
452 $sqlBindArray = array();
454 for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
458 $where .= " ".add_escape_custom($row["field_id"])." like ? ";
459 array_push($sqlBindArray, "%".$searchTerm."%");
462 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
463 if ($limit != "all") $sql .= " limit $start, $limit";
464 $rez = sqlStatement($sql, $sqlBindArray);
465 for($iter=0; $row=sqlFetchArray($rez); $iter++)
466 $returnval[$iter]=$row;
467 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
471 function getByPatientDemographicsFilter($searchFields, $searchTerm = "%",
472 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
473 $orderby = "lname ASC, fname ASC", $limit="all", $start="0", $search_service_code='')
475 $layoutCols = split( '~', $searchFields );
476 $sqlBindArray = array();
479 foreach ($layoutCols as $val) {
480 if (empty($val)) continue;
485 $where .= " ".add_escape_custom($val)." = ? ";
486 array_push($sqlBindArray, $searchTerm);
489 $where .= " ".add_escape_custom($val)." like ? ";
490 array_push($sqlBindArray, $searchTerm."%");
495 // If no search terms, ensure valid syntax.
496 if ($i == 0) $where = "1 = 1";
498 // If a non-empty service code was given, then restrict to patients who
499 // have been provided that service. Since the code is used in a LIKE
500 // clause, % and _ wildcards are supported.
501 if ($search_service_code) {
502 $where = "( $where ) AND " .
503 "( SELECT COUNT(*) FROM billing AS b WHERE " .
504 "b.pid = patient_data.pid AND " .
505 "b.activity = 1 AND " .
506 "b.code_type != 'COPAY' AND " .
509 array_push($sqlBindArray, $search_service_code);
512 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
513 if ($limit != "all") $sql .= " limit $start, $limit";
514 $rez = sqlStatement($sql, $sqlBindArray);
515 for($iter=0; $row=sqlFetchArray($rez); $iter++)
516 $returnval[$iter]=$row;
517 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
521 // return a collection of Patient PIDs
522 // new arg style by JRM March 2008
523 // 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")
524 function getPatientPID($args)
527 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
528 $orderby = "lname ASC, fname ASC";
532 // alter default values if defined in the passed in args
533 if (isset($args['pid'])) { $pid = $args['pid']; }
534 if (isset($args['given'])) { $given = $args['given']; }
535 if (isset($args['orderby'])) { $orderby = $args['orderby']; }
536 if (isset($args['limit'])) { $limit = $args['limit']; }
537 if (isset($args['start'])) { $start = $args['start']; }
540 if ($pid == -1) $pid = "%";
541 elseif (empty($pid)) $pid = "NULL";
543 if (strstr($pid,"%")) $command = "like";
545 $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
546 if ($limit != "all") $sql .= " limit $start, $limit";
548 $rez = sqlStatement($sql);
549 for($iter=0; $row=sqlFetchArray($rez); $iter++)
550 $returnval[$iter]=$row;
555 /* return a patient's name in the format LAST, FIRST */
556 function getPatientName($pid) {
557 if (empty($pid)) return "";
558 $patientData = getPatientPID(array("pid"=>$pid));
559 if (empty($patientData[0]['lname'])) return "";
560 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
564 /* find patient data by DOB */
565 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
567 $DOB = fixDate($DOB, $DOB);
568 $sqlBindArray = array();
569 $where = "DOB like ? ";
570 array_push($sqlBindArray, $DOB."%");
571 if (!empty($GLOBALS['pt_restrict_field'])) {
572 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
573 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
574 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
575 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
576 array_push($sqlBindArray, $_SESSION{"authUser"});
580 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
582 if ($limit != "all") $sql .= " LIMIT $start, $limit";
584 $rez = sqlStatement($sql, $sqlBindArray);
585 for($iter=0; $row=sqlFetchArray($rez); $iter++)
586 $returnval[$iter]=$row;
588 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
592 /* find patient data by SSN */
593 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
595 $sqlBindArray = array();
596 $where = "ss LIKE ?";
597 array_push($sqlBindArray, $ss."%");
598 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
599 if ($limit != "all") $sql .= " LIMIT $start, $limit";
601 $rez = sqlStatement($sql, $sqlBindArray);
602 for($iter=0; $row=sqlFetchArray($rez); $iter++)
603 $returnval[$iter]=$row;
605 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
609 //(CHEMED) Search by phone number
610 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
612 $phone = ereg_replace( "[[:punct:]]","", $phone );
613 $sqlBindArray = array();
614 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
615 array_push($sqlBindArray, $phone);
616 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
617 if ($limit != "all") $sql .= " LIMIT $start, $limit";
619 $rez = sqlStatement($sql, $sqlBindArray);
620 for($iter=0; $row=sqlFetchArray($rez); $iter++)
621 $returnval[$iter]=$row;
623 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
627 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
629 $sql="select $given from patient_data order by $orderby";
632 $sql .= " limit $start, $limit";
634 $rez = sqlStatement($sql);
635 for($iter=0; $row=sqlFetchArray($rez); $iter++)
636 $returnval[$iter]=$row;
641 //----------------------input functions
642 function newPatientData( $db_id="",
660 $contact_relationship = "",
667 $migrantseasonal = "",
669 $monthly_income = "",
671 $financial_review = "",
684 $drivers_license = "",
690 $DOB = fixDate($DOB);
691 $regdate = fixDate($regdate);
694 $referral_source = '';
696 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
697 // Check for brain damage:
698 if ($db_id != $rez['id']) {
699 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
700 $rez['id'] . "' to '$db_id' for pid '$pid'";
703 $fitness = $rez['fitness'];
704 $referral_source = $rez['referral_source'];
707 // Get the default price level.
708 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
709 "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
710 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
712 $query = ("replace into patient_data set
721 postal_code='$postal_code',
724 country_code='$country_code',
725 drivers_license='$drivers_license',
727 occupation='$occupation',
728 phone_home='$phone_home',
729 phone_biz='$phone_biz',
730 phone_contact='$phone_contact',
732 contact_relationship='$contact_relationship',
733 referrer='$referrer',
734 referrerID='$referrerID',
736 language='$language',
737 ethnoracial='$ethnoracial',
738 interpretter='$interpretter',
739 migrantseasonal='$migrantseasonal',
740 family_size='$family_size',
741 monthly_income='$monthly_income',
742 homeless='$homeless',
743 financial_review='$financial_review',
746 providerID = '$providerID',
747 genericname1 = '$genericname1',
748 genericval1 = '$genericval1',
749 genericname2 = '$genericname2',
750 genericval2 = '$genericval2',
751 phone_cell = '$phone_cell',
752 pharmacy_id = '$pharmacy_id',
753 hipaa_mail = '$hipaa_mail',
754 hipaa_voice = '$hipaa_voice',
755 hipaa_notice = '$hipaa_notice',
756 hipaa_message = '$hipaa_message',
759 referral_source='$referral_source',
761 pricelevel='$pricelevel',
764 $id = sqlInsert($query);
767 // find the last inserted id for new patient case
768 $db_id = mysql_insert_id();
771 $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
773 sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
774 $phone_biz,$phone_cell,$email,$pid);
779 // Supported input date formats are:
781 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
783 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
785 function fixDate($date, $default="0000-00-00") {
786 $fixed_date = $default;
788 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
789 $dmy = preg_split("'[/.-]'", $date);
791 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
793 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
794 if ($dmy[2] < 1000) $dmy[2] += 1900;
795 if ($dmy[2] < 1910) $dmy[2] += 100;
797 // phone_country_code indicates format of ambiguous input dates.
798 if ($GLOBALS['phone_country_code'] == 1)
799 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
801 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
808 function pdValueOrNull($key, $value) {
809 if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
810 substr($key, 0, 8) == 'userdate') &&
811 (empty($value) || $value == '0000-00-00'))
820 // Create or update patient data from an array.
822 function updatePatientData($pid, $new, $create=false)
824 /*******************************************************************
825 $real = getPatientData($pid);
826 $new['DOB'] = fixDate($new['DOB']);
827 while(list($key, $value) = each ($new))
828 $real[$key] = $value;
829 $real['date'] = "'+NOW()+'";
831 $sql = "insert into patient_data set ";
832 while(list($key, $value) = each($real))
833 $sql .= $key." = '$value', ";
834 $sql = substr($sql, 0, -2);
835 return sqlInsert($sql);
836 *******************************************************************/
838 // The above was broken, though seems intent to insert a new patient_data
839 // row for each update. A good idea, but nothing is doing that yet so
840 // the code below does not yet attempt it.
842 $new['DOB'] = fixDate($new['DOB']);
845 $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
846 foreach ($new as $key => $value) {
847 if ($key == 'id') continue;
848 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
850 $db_id = sqlInsert($sql);
854 $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
855 // Check for brain damage:
856 if ($pid != $rez['pid']) {
857 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
858 $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
861 $sql = "UPDATE patient_data SET date = NOW()";
862 foreach ($new as $key => $value) {
863 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
865 $sql .= " WHERE id = '$db_id'";
869 $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
870 sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
871 $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
872 $rez['phone_cell'],$rez['email'],$rez['pid']);
877 function newEmployerData( $pid,
886 return sqlInsert("insert into employer_data set
889 postal_code='$postal_code',
898 // Create or update employer data from an array.
900 function updateEmployerData($pid, $new, $create=false)
902 $colnames = array('name','street','city','state','postal_code','country');
905 $set .= "pid = '$pid', date = NOW()";
906 foreach ($colnames as $key) {
907 $value = isset($new[$key]) ? $new[$key] : '';
908 $set .= ", `$key` = '$value'";
910 return sqlInsert("INSERT INTO employer_data SET $set");
914 $old = getEmployerData($pid);
916 foreach ($colnames as $key) {
917 $value = empty($old[$key]) ? '' : addslashes($old[$key]);
918 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
922 $set .= "`$key` = '$value', ";
925 $set .= "pid = '$pid', date = NOW()";
926 return sqlInsert("INSERT INTO employer_data SET $set");
932 // This updates or adds the given insurance data info, while retaining any
933 // previously added insurance_data rows that should be preserved.
934 // This does not directly support the maintenance of non-current insurance.
936 function newInsuranceData(
943 $subscriber_lname = "",
944 $subscriber_mname = "",
945 $subscriber_fname = "",
946 $subscriber_relationship = "",
948 $subscriber_DOB = "",
949 $subscriber_street = "",
950 $subscriber_postal_code = "",
951 $subscriber_city = "",
952 $subscriber_state = "",
953 $subscriber_country = "",
954 $subscriber_phone = "",
955 $subscriber_employer = "",
956 $subscriber_employer_street = "",
957 $subscriber_employer_city = "",
958 $subscriber_employer_postal_code = "",
959 $subscriber_employer_state = "",
960 $subscriber_employer_country = "",
962 $subscriber_sex = "",
963 $effective_date = "0000-00-00",
964 $accept_assignment = "TRUE",
967 if (strlen($type) <= 0) return FALSE;
969 // If a bad date was passed, err on the side of caution.
970 $effective_date = fixDate($effective_date, date('Y-m-d'));
972 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
973 "pid = '$pid' AND type = '$type' ORDER BY date DESC");
974 $idrow = sqlFetchArray($idres);
976 // Replace the most recent entry in any of the following cases:
977 // * Its effective date is >= this effective date.
978 // * It is the first entry and it has no (insurance) provider.
979 // * There is no encounter that is earlier than the new effective date but
980 // on or after the old effective date.
981 // Otherwise insert a new entry.
985 if (strcmp($idrow['date'], $effective_date) > 0) {
989 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
993 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
994 "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
995 "date >= '" . $idrow['date'] . " 00:00:00'");
996 if ($ferow['count'] == 0) $replace = true;
1003 // TBD: This is a bit dangerous in that a typo in entering the effective
1004 // date can wipe out previous insurance history. So we want some data
1005 // entry validation somewhere.
1006 sqlStatement("DELETE FROM insurance_data WHERE " .
1007 "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
1008 "id != " . $idrow['id']);
1011 $data['type'] = $type;
1012 $data['provider'] = $provider;
1013 $data['policy_number'] = $policy_number;
1014 $data['group_number'] = $group_number;
1015 $data['plan_name'] = $plan_name;
1016 $data['subscriber_lname'] = $subscriber_lname;
1017 $data['subscriber_mname'] = $subscriber_mname;
1018 $data['subscriber_fname'] = $subscriber_fname;
1019 $data['subscriber_relationship'] = $subscriber_relationship;
1020 $data['subscriber_ss'] = $subscriber_ss;
1021 $data['subscriber_DOB'] = $subscriber_DOB;
1022 $data['subscriber_street'] = $subscriber_street;
1023 $data['subscriber_postal_code'] = $subscriber_postal_code;
1024 $data['subscriber_city'] = $subscriber_city;
1025 $data['subscriber_state'] = $subscriber_state;
1026 $data['subscriber_country'] = $subscriber_country;
1027 $data['subscriber_phone'] = $subscriber_phone;
1028 $data['subscriber_employer'] = $subscriber_employer;
1029 $data['subscriber_employer_city'] = $subscriber_employer_city;
1030 $data['subscriber_employer_street'] = $subscriber_employer_street;
1031 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1032 $data['subscriber_employer_state'] = $subscriber_employer_state;
1033 $data['subscriber_employer_country'] = $subscriber_employer_country;
1034 $data['copay'] = $copay;
1035 $data['subscriber_sex'] = $subscriber_sex;
1036 $data['pid'] = $pid;
1037 $data['date'] = $effective_date;
1038 $data['accept_assignment'] = $accept_assignment;
1039 $data['policy_type'] = $policy_type;
1040 updateInsuranceData($idrow['id'], $data);
1041 return $idrow['id'];
1044 return sqlInsert("INSERT INTO insurance_data SET
1046 provider = '$provider',
1047 policy_number = '$policy_number',
1048 group_number = '$group_number',
1049 plan_name = '$plan_name',
1050 subscriber_lname = '$subscriber_lname',
1051 subscriber_mname = '$subscriber_mname',
1052 subscriber_fname = '$subscriber_fname',
1053 subscriber_relationship = '$subscriber_relationship',
1054 subscriber_ss = '$subscriber_ss',
1055 subscriber_DOB = '$subscriber_DOB',
1056 subscriber_street = '$subscriber_street',
1057 subscriber_postal_code = '$subscriber_postal_code',
1058 subscriber_city = '$subscriber_city',
1059 subscriber_state = '$subscriber_state',
1060 subscriber_country = '$subscriber_country',
1061 subscriber_phone = '$subscriber_phone',
1062 subscriber_employer = '$subscriber_employer',
1063 subscriber_employer_city = '$subscriber_employer_city',
1064 subscriber_employer_street = '$subscriber_employer_street',
1065 subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1066 subscriber_employer_state = '$subscriber_employer_state',
1067 subscriber_employer_country = '$subscriber_employer_country',
1069 subscriber_sex = '$subscriber_sex',
1071 date = '$effective_date',
1072 accept_assignment = '$accept_assignment',
1073 policy_type = '$policy_type'
1078 // This is used internally only.
1079 function updateInsuranceData($id, $new)
1081 $fields = sqlListFields("insurance_data");
1084 while(list($key, $value) = each ($new)) {
1085 if (in_array($key, $fields)) {
1086 $use[$key] = $value;
1090 $sql = "UPDATE insurance_data SET ";
1091 while(list($key, $value) = each($use))
1092 $sql .= "`$key` = '$value', ";
1093 $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1098 function newHistoryData($pid, $new=false) {
1099 $arraySqlBind = array();
1100 $sql = "insert into history_data set pid = ?, date = NOW()";
1101 array_push($arraySqlBind,$pid);
1103 while(list($key, $value) = each($new)) {
1104 array_push($arraySqlBind,$value);
1105 $sql .= ", `$key` = ?";
1108 return sqlInsert($sql, $arraySqlBind );
1111 function updateHistoryData($pid,$new)
1113 $real = getHistoryData($pid);
1114 while(list($key, $value) = each ($new))
1115 $real[$key] = $value;
1117 // need to unset date, so can reset it below
1118 unset($real['date']);
1120 $arraySqlBind = array();
1121 $sql = "insert into history_data set `date` = NOW(), ";
1122 while(list($key, $value) = each($real)) {
1123 array_push($arraySqlBind,$value);
1124 $sql .= "`$key` = ?, ";
1126 $sql = substr($sql, 0, -2);
1128 return sqlInsert($sql, $arraySqlBind );
1131 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1132 $phone_biz,$phone_cell,$email,$pid="")
1134 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1135 if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1137 $db = $GLOBALS['adodb']['db'];
1138 $customer_info = array();
1140 $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1141 $result = $db->Execute($sql);
1142 if ($result && !$result->EOF) {
1143 $customer_info['foreign_update'] = true;
1144 $customer_info['foreign_id'] = $result->fields['foreign_id'];
1145 $customer_info['foreign_table'] = $result->fields['foreign_table'];
1148 ///xml rpc code to connect to accounting package and add user to it
1149 $customer_info['firstname'] = $fname;
1150 $customer_info['lastname'] = $lname;
1151 $customer_info['address'] = $street;
1152 $customer_info['suburb'] = $city;
1153 $customer_info['state'] = $state;
1154 $customer_info['postcode'] = $postal_code;
1156 //ezybiz wants state as a code rather than abbreviation
1157 $customer_info['geo_zone_id'] = "";
1158 $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1159 $db = $GLOBALS['adodb']['db'];
1160 $result = $db->Execute($sql);
1161 if ($result && !$result->EOF) {
1162 $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1165 //ezybiz wants country as a code rather than abbreviation
1166 $customer_info['geo_country_id'] = "";
1167 $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1168 $db = $GLOBALS['adodb']['db'];
1169 $result = $db->Execute($sql);
1170 if ($result && !$result->EOF) {
1171 $customer_info['geo_country_id'] = $result->fields['countries_id'];
1174 $customer_info['phone1'] = $phone_home;
1175 $customer_info['phone1comment'] = "Home Phone";
1176 $customer_info['phone2'] = $phone_biz;
1177 $customer_info['phone2comment'] = "Business Phone";
1178 $customer_info['phone3'] = $phone_cell;
1179 $customer_info['phone3comment'] = "Cell Phone";
1180 $customer_info['email'] = $email;
1181 $customer_info['customernumber'] = $pid;
1183 $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1184 $ws = new WSWrapper($function);
1186 // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1187 if (is_numeric($ws->value)) {
1188 $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1189 $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1194 // in months if < 2 years old
1195 // in years if > 2 years old
1196 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1197 // (optional) nowYMD is a date in YYYYMMDD format
1198 function getPatientAge($dobYMD, $nowYMD=null)
1200 // strip any dashes from the DOB
1201 $dobYMD = preg_replace("/-/", "", $dobYMD);
1202 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1204 // set the 'now' date values
1205 if ($nowYMD == null) {
1206 $nowDay = date("d");
1207 $nowMonth = date("m");
1208 $nowYear = date("Y");
1211 $nowDay = substr($nowYMD,6,2);
1212 $nowMonth = substr($nowYMD,4,2);
1213 $nowYear = substr($nowYMD,0,4);
1216 $dayDiff = $nowDay - $dobDay;
1217 $monthDiff = $nowMonth - $dobMonth;
1218 $yearDiff = $nowYear - $dobYear;
1220 $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1222 if ( $ageInMonths > 24 ) {
1224 if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1225 else if ($monthDiff < 0) { $age -= 1; }
1228 $age = "$ageInMonths month";
1235 // Returns Age in days
1236 // in months if < 2 years old
1237 // in years if > 2 years old
1238 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1239 // (optional) nowYMD is a date in YYYYMMDD format
1240 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1243 // strip any dashes from the DOB
1244 $dobYMD = preg_replace("/-/", "", $dobYMD);
1245 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1247 // set the 'now' date values
1248 if ($nowYMD == null) {
1249 $nowDay = date("d");
1250 $nowMonth = date("m");
1251 $nowYear = date("Y");
1254 $nowDay = substr($nowYMD,6,2);
1255 $nowMonth = substr($nowYMD,4,2);
1256 $nowYear = substr($nowYMD,0,4);
1260 $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1261 $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1262 $timediff = $nowtime - $dobtime;
1263 $age = $timediff / 86400;
1268 function dateToDB ($date)
1270 $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1275 // ----------------------------------------------------------------------------
1277 * DROPDOWN FOR COUNTRIES
1279 * build a dropdown with all countries from geo_country_reference
1281 * @param int $selected - id for selected record
1282 * @param string $name - the name/id for select form
1283 * @return void - just echo the html encoded string
1285 function dropdown_countries($selected = 0, $name = 'country_code') {
1286 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1288 $string = "<select name='$name' id='$name'>";
1289 while ( $row = sqlFetchArray($r) ) {
1290 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1291 $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1294 $string .= '</select>';
1299 // ----------------------------------------------------------------------------
1301 * DROPDOWN FOR YES/NO
1303 * build a dropdown with two options (yes - 1, no - 0)
1305 * @param int $selected - id for selected record
1306 * @param string $name - the name/id for select form
1307 * @return void - just echo the html encoded string
1309 function dropdown_yesno($selected = 0, $name = 'yesno') {
1310 $string = "<select name='$name' id='$name'>";
1312 $selected = (int)$selected;
1313 if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1314 else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1316 $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1317 $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1318 $string .= '</select>';
1323 // ----------------------------------------------------------------------------
1325 * DROPDOWN FOR MALE/FEMALE options
1327 * build a dropdown with three options (unselected/male/female)
1329 * @param int $selected - id for selected record
1330 * @param string $name - the name/id for select form
1331 * @return void - just echo the html encoded string
1333 function dropdown_sex($selected = 0, $name = 'sex') {
1334 $string = "<select name='$name' id='$name'>";
1336 if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1337 else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1338 else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1340 $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1341 $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1342 $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1343 $string .= '</select>';
1348 // ----------------------------------------------------------------------------
1350 * DROPDOWN FOR MARITAL STATUS
1352 * build a dropdown with marital status
1354 * @param int $selected - id for selected record
1355 * @param string $name - the name/id for select form
1356 * @return void - just echo the html encoded string
1358 function dropdown_marital($selected = 0, $name = 'status') {
1359 $string = "<select name='$name' id='$name'>";
1361 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1363 foreach ( $statii as $st ) {
1364 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1365 $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1368 $string .= '</select>';
1373 // ----------------------------------------------------------------------------
1375 * DROPDOWN FOR PROVIDERS
1377 * build a dropdown with all providers
1379 * @param int $selected - id for selected record
1380 * @param string $name - the name/id for select form
1381 * @return void - just echo the html encoded string
1383 function dropdown_providers($selected = 0, $name = 'status') {
1384 $provideri = getProviderInfo();
1386 $string = "<select name='$name' id='$name'>";
1387 $string .= '<option value="">' .xl('Unassigned'). '</option>';
1388 foreach ( $provideri as $s ) {
1389 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1390 $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1393 $string .= '</select>';
1398 // ----------------------------------------------------------------------------
1400 * DROPDOWN FOR INSURANCE COMPANIES
1402 * build a dropdown with all insurers
1404 * @param int $selected - id for selected record
1405 * @param string $name - the name/id for select form
1406 * @return void - just echo the html encoded string
1408 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1409 $insurancei = getInsuranceProviders();
1411 $string = "<select name='$name' id='$name'>";
1412 $string .= '<option value="0">Onbekend</option>';
1413 foreach ( $insurancei as $iid => $iname ) {
1414 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1415 $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1418 $string .= '</select>';
1424 // ----------------------------------------------------------------------------
1428 * return the name or the country code, function of arguments
1430 * @param int $country_code
1431 * @param string $country_name
1432 * @return string | int - name or code
1434 function country_code($country_code = 0, $country_name = '') {
1436 if ( $country_code ) {
1437 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1439 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1442 $db = $GLOBALS['adodb']['db'];
1443 $result = $db->Execute($sql);
1444 if ($result && !$result->EOF) {
1445 $strint = $result->fields['res'];
1451 function DBToDate ($date)
1453 $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1457 function get_patient_balance($pid) {
1458 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1459 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1460 "pid = ? AND activity = 1", array($pid) );
1461 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1462 "pid = ?", array($pid) );
1463 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1464 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1465 "pid = ?", array($pid) );
1466 return sprintf('%01.2f', $brow['amount'] + $srow['amount']
1467 - $drow['payments'] - $drow['adjustments']);
1469 else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1470 // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1471 $conn = $GLOBALS['adodb']['db'];
1472 $customer_info['id'] = 0;
1473 $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1474 "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1475 "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1476 "im.foreign_table = 'customer'";
1477 $result = $conn->Execute($sql);
1478 if($result && !$result->EOF) {
1479 $customer_info['id'] = $result->fields['foreign_id'];
1481 $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1482 $ws = new WSWrapper($function);
1483 if(is_numeric($ws->value)) {
1484 return sprintf('%01.2f', $ws->value);
1490 // Function to check if patient is deceased.
1492 // $pid - patient id
1493 // $date - date checking if deceased (will default to current date if blank)
1495 // If deceased, then will return the number of
1496 // days that patient has been deceased.
1497 // If not deceased, then will return false.
1498 function is_patient_deceased($pid,$date='') {
1500 // Set date to current if not set
1501 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1503 // Query for deceased status (gets days deceased if patient is deceased)
1504 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1505 "FROM `patient_data` " .
1506 "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date) );
1508 if (empty($results)) {
1509 // Patient is alive, so return false
1513 // Patient is dead, so return the number of days patient has been deceased.
1514 // Don't let it be zero days or else will confuse calls to this function.
1515 if ($results['days_deceased'] === 0) {
1516 $results['days_deceased'] = 1;
1518 return $results['days_deceased'];