3 * patient.inc includes functions for manipulating patient information.
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
11 require_once("{$GLOBALS['srcdir']}/sql.inc");
12 require_once(dirname(__FILE__) . "/classes/WSWrapper.class.php");
13 require_once("{$GLOBALS['srcdir']}/formdata.inc.php");
15 // These are for sports team use:
16 $PLAYER_FITNESSES = array(
19 xl('Restricted Training'),
23 xl('International Duty')
25 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
27 // Hard-coding this array because its values and meanings are fixed by the 837p
28 // standard and we don't want people messing with them.
29 $policy_types = array(
31 '12' => xl('Working Aged Beneficiary or Spouse with Employer Group Health Plan'),
32 '13' => xl('End-Stage Renal Disease Beneficiary in MCP with Employer`s Group Plan'),
33 '14' => xl('No-fault Insurance including Auto is Primary'),
34 '15' => xl('Worker`s Compensation'),
35 '16' => xl('Public Health Service (PHS) or Other Federal Agency'),
36 '41' => xl('Black Lung'),
37 '42' => xl('Veteran`s Administration'),
38 '43' => xl('Disabled Beneficiary Under Age 65 with Large Group Health Plan (LGHP)'),
39 '47' => xl('Other Liability Insurance is Primary'),
43 * Get a patient's demographic data.
45 * @param int $pid The PID of the patient
46 * @param string $given an optional subsection of the patient's demographic
48 * @return array The requested subsection of a patient's demographic data.
49 * If no subsection was given, returns everything, with the
50 * date of birth as the last field.
52 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS") {
53 $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
54 return sqlQuery($sql, array($pid) );
57 function getLanguages() {
58 $returnval = array('','english');
59 $sql = "select distinct lower(language) as language from patient_data";
60 $rez = sqlStatement($sql);
61 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
62 if (($row["language"] != "english") && ($row["language"] != "")) {
63 array_push($returnval, $row["language"]);
69 function getInsuranceProvider($ins_id) {
71 $sql = "select name from insurance_companies where id=?";
72 $row = sqlQuery($sql,array($ins_id));
77 function getInsuranceProviders() {
81 $sql = "select name, id from insurance_companies order by name, id";
82 $rez = sqlStatement($sql);
83 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
84 $returnval[$row['id']] = $row['name'];
88 // Please leave this here. I have a user who wants to see zip codes and PO
89 // box numbers listed along with the insurance company names, as many companies
90 // have different billing addresses for different plans. -- Rod Roark
93 $sql = "select insurance_companies.name, insurance_companies.id, " .
94 "addresses.zip, addresses.line1 " .
95 "from insurance_companies, addresses " .
96 "where addresses.foreign_id = insurance_companies.id " .
97 "order by insurance_companies.name, addresses.zip";
99 $rez = sqlStatement($sql);
101 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
102 preg_match("/\d+/", $row['line1'], $matches);
103 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
104 "," . $matches[0] . ")";
111 function getProviders() {
112 $returnval = array("");
113 $sql = "select fname, lname from users where authorized = 1 and " .
114 "active = 1 and username != ''";
115 $rez = sqlStatement($sql);
116 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
117 if (($row["fname"] != "") && ($row["lname"] != "")) {
118 array_push($returnval, $row["fname"] . " " . $row["lname"]);
124 // ----------------------------------------------------------------------------
125 // Get one facility row. If the ID is not specified, then get either the
126 // "main" (billing) facility, or the default facility of the currently
127 // logged-in user. This was created to support genFacilityTitle() but
128 // may find additional uses.
130 function getFacility($facid=0) {
132 //create a sql binding array
133 $sqlBindArray = array();
136 $query = "SELECT * FROM facility WHERE id = ?";
137 array_push($sqlBindArray,$facid);
139 else if ($facid == 0) {
140 $query = "SELECT * FROM facility ORDER BY " .
141 "billing_location DESC, service_location, id LIMIT 1";
144 $query = "SELECT facility.* FROM users, facility WHERE " .
145 "users.id = ? AND " .
146 "facility.id = users.facility_id";
147 array_push($sqlBindArray,$_SESSION['authUserID']);
149 return sqlQuery($query,$sqlBindArray);
152 // Generate a report title including report name and facility name, address
155 function genFacilityTitle($repname='', $facid=0) {
157 $s .= "<table class='ftitletable'>\n";
159 $s .= " <td class='ftitlecell1'>$repname</td>\n";
160 $s .= " <td class='ftitlecell2'>\n";
161 $r = getFacility($facid);
163 $s .= "<b>" . htmlspecialchars( $r['name'], ENT_NOQUOTES) . "</b>\n";
164 if ($r['street']) $s .= "<br />" . htmlspecialchars( $r['street'], ENT_NOQUOTES) . "\n";
165 if ($r['city'] || $r['state'] || $r['postal_code']) {
167 if ($r['city']) $s .= htmlspecialchars( $r['city'], ENT_NOQUOTES);
169 if ($r['city']) $s .= ", \n";
170 $s .= htmlspecialchars( $r['state'], ENT_NOQUOTES);
172 if ($r['postal_code']) $s .= " " . htmlspecialchars( $r['postal_code'], ENT_NOQUOTES);
175 if ($r['country_code']) $s .= "<br />" . htmlspecialchars( $r['country_code'], ENT_NOQUOTES) . "\n";
176 if (preg_match('/[1-9]/', $r['phone'])) $s .= "<br />" . htmlspecialchars( $r['phone'], ENT_NOQUOTES) . "\n";
187 returns all facilities or just the id for the first one
188 (FACILITY FILTERING (lemonsoftware))
190 @param string - if 'first' return first facility ordered by id
191 @return array | int for 'first' case
193 function getFacilities($first = '') {
194 $r = sqlStatement("SELECT * FROM facility ORDER BY id");
196 while ( $row = sqlFetchArray($r) ) {
200 if ( $first == 'first') {
201 return $ret[0]['id'];
208 GET SERVICE FACILITIES
210 returns all service_location facilities or just the id for the first one
211 (FACILITY FILTERING (CHEMED))
213 @param string - if 'first' return first facility ordered by id
214 @return array | int for 'first' case
216 function getServiceFacilities($first = '') {
217 $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
219 while ( $row = sqlFetchArray($r) ) {
223 if ( $first == 'first') {
224 return $ret[0]['id'];
230 //(CHEMED) facility filter
231 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
233 if ($providers_only === 'any') {
234 $param1 = " AND authorized = 1 AND active = 1 ";
236 else if ($providers_only) {
237 $param1 = " AND authorized = 1 AND calendar = 1 ";
240 //--------------------------------
241 //(CHEMED) facility filter
244 if ($GLOBALS['restrict_user_facility']) {
245 $param2 = " AND (facility_id = $facility
249 where tablename = 'users'
255 $param2 = " AND facility_id = $facility ";
258 //--------------------------------
261 if ($providerID == "%") {
264 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
265 "from users where username != '' and active = 1 and id $command '" .
266 mysql_real_escape_string($providerID) . "' " . $param1 . $param2;
267 // sort by last name -- JRM June 2008
268 $query .= " ORDER BY lname, fname ";
269 $rez = sqlStatement($query);
270 for($iter=0; $row=sqlFetchArray($rez); $iter++)
271 $returnval[$iter]=$row;
273 //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
274 //accessible from $resultval['key']
277 $akeys = array_keys($returnval[0]);
278 foreach($akeys as $key) {
279 $returnval[0][$key] = $returnval[0][$key];
285 //same as above but does not reduce if only 1 row returned
286 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
288 if ($providers_only) {
289 $param1 = "AND authorized=1";
292 if ($providerID == "%") {
295 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
296 "from users where active = 1 and username != '' and id $command '" .
297 mysql_real_escape_string($providerID) . "' " . $param1;
299 $rez = sqlStatement($query);
300 for($iter=0; $row=sqlFetchArray($rez); $iter++)
301 $returnval[$iter]=$row;
306 function getProviderName($providerID) {
307 $pi = getProviderInfo($providerID, 'any');
308 if (strlen($pi[0]["lname"]) > 0) {
309 return $pi[0]['fname'] . " " . $pi[0]['lname'];
314 function getProviderId($providerName) {
315 $query = "select id from users where username = ?";
316 $rez = sqlStatement($query, array($providerName) );
317 for($iter=0; $row=sqlFetchArray($rez); $iter++)
318 $returnval[$iter]=$row;
322 function getEthnoRacials() {
323 $returnval = array("");
324 $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
325 $rez = sqlStatement($sql);
326 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
327 if (($row["ethnoracial"] != "")) {
328 array_push($returnval, $row["ethnoracial"]);
334 function getHistoryData($pid, $given = "*", $dateStart='',$dateEnd='')
337 if ($dateStart && $dateEnd) {
338 $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd) );
340 else if ($dateStart && !$dateEnd) {
341 $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart) );
343 else if (!$dateStart && $dateEnd) {
344 $res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd) );
347 $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid) );
353 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
354 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
356 $sql = "select $given from insurance_data as insd " .
357 "left join insurance_companies as ic on ic.id = insd.provider " .
358 "where pid = ? and type = ? order by date DESC limit 1";
359 return sqlQuery($sql, array($pid, $type) );
362 function getInsuranceDataByDate($pid, $date, $type,
363 $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
364 { // this must take the date in the following manner: YYYY-MM-DD
365 // this function recalls the insurance value that was most recently enterred from the
366 // given date. it will call up most recent records up to and on the date given,
367 // but not records enterred after the given date
368 $sql = "select $given from insurance_data as insd " .
369 "left join insurance_companies as ic on ic.id = provider " .
370 "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
371 "type=? order by date DESC limit 1";
372 return sqlQuery($sql, array($pid,$date,$type) );
375 function getEmployerData($pid, $given = "*")
377 $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
378 return sqlQuery($sql, array($pid) );
381 function _set_patient_inc_count($limit, $count, $where, $whereBindArray=array()) {
382 // When the limit is exceeded, find out what the unlimited count would be.
383 $GLOBALS['PATIENT_INC_COUNT'] = $count;
384 // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
385 if ($limit != "all") {
386 $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
387 $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
391 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")
393 // Allow the last name to be followed by a comma and some part of a first name.
394 // New behavior for searches:
395 // Allows comma alone followed by some part of a first name
396 // If the first letter of either name is capital, searches for name starting
397 // with given substring (the expected behavior). If it is lower case, it
398 // it searches for the substring anywhere in the name. This applies to either
399 // last name or first name or both. The arbitrary limit of 100 results is set
400 // in the sql query below. --Mark Leeds
401 $lname = trim($lname);
403 if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
404 $lname = trim($matches[1]);
405 $fname = trim($matches[2]);
407 $search_for_pieces1 = '';
408 $search_for_pieces2 = '';
409 if ((strlen($lname) < 1)|| ($lname{0} != strtoupper($lname{0}))) {$search_for_pieces1 = '%';}
410 if ((strlen($fname) < 1)|| ($fname{0} != strtoupper($fname{0}))) {$search_for_pieces2 = '%';}
412 $sqlBindArray = array();
413 $where = "lname LIKE ? AND fname LIKE ? ";
414 array_push($sqlBindArray, $search_for_pieces1.$lname."%", $search_for_pieces2.$fname."%");
415 if (!empty($GLOBALS['pt_restrict_field'])) {
416 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
417 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
418 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
419 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
420 array_push($sqlBindArray, $_SESSION{"authUser"});
424 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
425 if ($limit != "all") $sql .= " LIMIT $start, $limit";
427 $rez = sqlStatement($sql, $sqlBindArray);
430 for($iter=0; $row=sqlFetchArray($rez); $iter++)
431 $returnval[$iter] = $row;
433 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
437 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")
440 $sqlBindArray = array();
441 $where = "pubpid LIKE ? ";
442 array_push($sqlBindArray, $pid."%");
443 if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
444 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
445 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
446 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
447 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
448 array_push($sqlBindArray, $_SESSION{"authUser"});
452 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
453 if ($limit != "all") $sql .= " limit $start, $limit";
454 $rez = sqlStatement($sql, $sqlBindArray);
455 for($iter=0; $row=sqlFetchArray($rez); $iter++)
456 $returnval[$iter]=$row;
458 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
462 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")
464 $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%") );
466 $sqlBindArray = array();
468 for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
472 $where .= " ".add_escape_custom($row["field_id"])." like ? ";
473 array_push($sqlBindArray, "%".$searchTerm."%");
476 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
477 if ($limit != "all") $sql .= " limit $start, $limit";
478 $rez = sqlStatement($sql, $sqlBindArray);
479 for($iter=0; $row=sqlFetchArray($rez); $iter++)
480 $returnval[$iter]=$row;
481 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
485 function getByPatientDemographicsFilter($searchFields, $searchTerm = "%",
486 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
487 $orderby = "lname ASC, fname ASC", $limit="all", $start="0", $search_service_code='')
489 $layoutCols = split( '~', $searchFields );
490 $sqlBindArray = array();
493 foreach ($layoutCols as $val) {
494 if (empty($val)) continue;
499 $where .= " ".add_escape_custom($val)." = ? ";
500 array_push($sqlBindArray, $searchTerm);
503 $where .= " ".add_escape_custom($val)." like ? ";
504 array_push($sqlBindArray, $searchTerm."%");
509 // If no search terms, ensure valid syntax.
510 if ($i == 0) $where = "1 = 1";
512 // If a non-empty service code was given, then restrict to patients who
513 // have been provided that service. Since the code is used in a LIKE
514 // clause, % and _ wildcards are supported.
515 if ($search_service_code) {
516 $where = "( $where ) AND " .
517 "( SELECT COUNT(*) FROM billing AS b WHERE " .
518 "b.pid = patient_data.pid AND " .
519 "b.activity = 1 AND " .
520 "b.code_type != 'COPAY' AND " .
523 array_push($sqlBindArray, $search_service_code);
526 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
527 if ($limit != "all") $sql .= " limit $start, $limit";
528 $rez = sqlStatement($sql, $sqlBindArray);
529 for($iter=0; $row=sqlFetchArray($rez); $iter++)
530 $returnval[$iter]=$row;
531 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
535 // return a collection of Patient PIDs
536 // new arg style by JRM March 2008
537 // 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")
538 function getPatientPID($args)
541 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
542 $orderby = "lname ASC, fname ASC";
546 // alter default values if defined in the passed in args
547 if (isset($args['pid'])) { $pid = $args['pid']; }
548 if (isset($args['given'])) { $given = $args['given']; }
549 if (isset($args['orderby'])) { $orderby = $args['orderby']; }
550 if (isset($args['limit'])) { $limit = $args['limit']; }
551 if (isset($args['start'])) { $start = $args['start']; }
554 if ($pid == -1) $pid = "%";
555 elseif (empty($pid)) $pid = "NULL";
557 if (strstr($pid,"%")) $command = "like";
559 $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
560 if ($limit != "all") $sql .= " limit $start, $limit";
562 $rez = sqlStatement($sql);
563 for($iter=0; $row=sqlFetchArray($rez); $iter++)
564 $returnval[$iter]=$row;
569 /* return a patient's name in the format LAST, FIRST */
570 function getPatientName($pid) {
571 if (empty($pid)) return "";
572 $patientData = getPatientPID(array("pid"=>$pid));
573 if (empty($patientData[0]['lname'])) return "";
574 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
578 /* find patient data by DOB */
579 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
581 $DOB = fixDate($DOB, $DOB);
582 $sqlBindArray = array();
583 $where = "DOB like ? ";
584 array_push($sqlBindArray, $DOB."%");
585 if (!empty($GLOBALS['pt_restrict_field'])) {
586 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
587 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
588 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
589 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
590 array_push($sqlBindArray, $_SESSION{"authUser"});
594 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
596 if ($limit != "all") $sql .= " LIMIT $start, $limit";
598 $rez = sqlStatement($sql, $sqlBindArray);
599 for($iter=0; $row=sqlFetchArray($rez); $iter++)
600 $returnval[$iter]=$row;
602 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
606 /* find patient data by SSN */
607 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
609 $sqlBindArray = array();
610 $where = "ss LIKE ?";
611 array_push($sqlBindArray, $ss."%");
612 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
613 if ($limit != "all") $sql .= " LIMIT $start, $limit";
615 $rez = sqlStatement($sql, $sqlBindArray);
616 for($iter=0; $row=sqlFetchArray($rez); $iter++)
617 $returnval[$iter]=$row;
619 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
623 //(CHEMED) Search by phone number
624 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
626 $phone = ereg_replace( "[[:punct:]]","", $phone );
627 $sqlBindArray = array();
628 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
629 array_push($sqlBindArray, $phone);
630 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
631 if ($limit != "all") $sql .= " LIMIT $start, $limit";
633 $rez = sqlStatement($sql, $sqlBindArray);
634 for($iter=0; $row=sqlFetchArray($rez); $iter++)
635 $returnval[$iter]=$row;
637 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
641 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
643 $sql="select $given from patient_data order by $orderby";
646 $sql .= " limit $start, $limit";
648 $rez = sqlStatement($sql);
649 for($iter=0; $row=sqlFetchArray($rez); $iter++)
650 $returnval[$iter]=$row;
655 //----------------------input functions
656 function newPatientData( $db_id="",
674 $contact_relationship = "",
681 $migrantseasonal = "",
683 $monthly_income = "",
685 $financial_review = "",
698 $drivers_license = "",
704 $DOB = fixDate($DOB);
705 $regdate = fixDate($regdate);
708 $referral_source = '';
710 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
711 // Check for brain damage:
712 if ($db_id != $rez['id']) {
713 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
714 $rez['id'] . "' to '$db_id' for pid '$pid'";
717 $fitness = $rez['fitness'];
718 $referral_source = $rez['referral_source'];
721 // Get the default price level.
722 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
723 "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
724 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
726 $query = ("replace into patient_data set
735 postal_code='$postal_code',
738 country_code='$country_code',
739 drivers_license='$drivers_license',
741 occupation='$occupation',
742 phone_home='$phone_home',
743 phone_biz='$phone_biz',
744 phone_contact='$phone_contact',
746 contact_relationship='$contact_relationship',
747 referrer='$referrer',
748 referrerID='$referrerID',
750 language='$language',
751 ethnoracial='$ethnoracial',
752 interpretter='$interpretter',
753 migrantseasonal='$migrantseasonal',
754 family_size='$family_size',
755 monthly_income='$monthly_income',
756 homeless='$homeless',
757 financial_review='$financial_review',
760 providerID = '$providerID',
761 genericname1 = '$genericname1',
762 genericval1 = '$genericval1',
763 genericname2 = '$genericname2',
764 genericval2 = '$genericval2',
765 phone_cell = '$phone_cell',
766 pharmacy_id = '$pharmacy_id',
767 hipaa_mail = '$hipaa_mail',
768 hipaa_voice = '$hipaa_voice',
769 hipaa_notice = '$hipaa_notice',
770 hipaa_message = '$hipaa_message',
773 referral_source='$referral_source',
775 pricelevel='$pricelevel',
778 $id = sqlInsert($query);
781 // find the last inserted id for new patient case
782 $db_id = mysql_insert_id();
785 $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
787 sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
788 $phone_biz,$phone_cell,$email,$pid);
793 // Supported input date formats are:
795 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
797 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
799 function fixDate($date, $default="0000-00-00") {
800 $fixed_date = $default;
802 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
803 $dmy = preg_split("'[/.-]'", $date);
805 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
807 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
808 if ($dmy[2] < 1000) $dmy[2] += 1900;
809 if ($dmy[2] < 1910) $dmy[2] += 100;
811 // phone_country_code indicates format of ambiguous input dates.
812 if ($GLOBALS['phone_country_code'] == 1)
813 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
815 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
822 function pdValueOrNull($key, $value) {
823 if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
824 substr($key, 0, 8) == 'userdate') &&
825 (empty($value) || $value == '0000-00-00'))
834 // Create or update patient data from an array.
836 function updatePatientData($pid, $new, $create=false)
838 /*******************************************************************
839 $real = getPatientData($pid);
840 $new['DOB'] = fixDate($new['DOB']);
841 while(list($key, $value) = each ($new))
842 $real[$key] = $value;
843 $real['date'] = "'+NOW()+'";
845 $sql = "insert into patient_data set ";
846 while(list($key, $value) = each($real))
847 $sql .= $key." = '$value', ";
848 $sql = substr($sql, 0, -2);
849 return sqlInsert($sql);
850 *******************************************************************/
852 // The above was broken, though seems intent to insert a new patient_data
853 // row for each update. A good idea, but nothing is doing that yet so
854 // the code below does not yet attempt it.
856 $new['DOB'] = fixDate($new['DOB']);
859 $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
860 foreach ($new as $key => $value) {
861 if ($key == 'id') continue;
862 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
864 $db_id = sqlInsert($sql);
868 $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
869 // Check for brain damage:
870 if ($pid != $rez['pid']) {
871 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
872 $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
875 $sql = "UPDATE patient_data SET date = NOW()";
876 foreach ($new as $key => $value) {
877 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
879 $sql .= " WHERE id = '$db_id'";
883 $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
884 sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
885 $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
886 $rez['phone_cell'],$rez['email'],$rez['pid']);
891 function newEmployerData( $pid,
900 return sqlInsert("insert into employer_data set
903 postal_code='$postal_code',
912 // Create or update employer data from an array.
914 function updateEmployerData($pid, $new, $create=false)
916 $colnames = array('name','street','city','state','postal_code','country');
919 $set .= "pid = '$pid', date = NOW()";
920 foreach ($colnames as $key) {
921 $value = isset($new[$key]) ? $new[$key] : '';
922 $set .= ", `$key` = '$value'";
924 return sqlInsert("INSERT INTO employer_data SET $set");
928 $old = getEmployerData($pid);
930 foreach ($colnames as $key) {
931 $value = empty($old[$key]) ? '' : addslashes($old[$key]);
932 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
936 $set .= "`$key` = '$value', ";
939 $set .= "pid = '$pid', date = NOW()";
940 return sqlInsert("INSERT INTO employer_data SET $set");
946 // This updates or adds the given insurance data info, while retaining any
947 // previously added insurance_data rows that should be preserved.
948 // This does not directly support the maintenance of non-current insurance.
950 function newInsuranceData(
957 $subscriber_lname = "",
958 $subscriber_mname = "",
959 $subscriber_fname = "",
960 $subscriber_relationship = "",
962 $subscriber_DOB = "",
963 $subscriber_street = "",
964 $subscriber_postal_code = "",
965 $subscriber_city = "",
966 $subscriber_state = "",
967 $subscriber_country = "",
968 $subscriber_phone = "",
969 $subscriber_employer = "",
970 $subscriber_employer_street = "",
971 $subscriber_employer_city = "",
972 $subscriber_employer_postal_code = "",
973 $subscriber_employer_state = "",
974 $subscriber_employer_country = "",
976 $subscriber_sex = "",
977 $effective_date = "0000-00-00",
978 $accept_assignment = "TRUE",
981 if (strlen($type) <= 0) return FALSE;
983 // If a bad date was passed, err on the side of caution.
984 $effective_date = fixDate($effective_date, date('Y-m-d'));
986 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
987 "pid = '$pid' AND type = '$type' ORDER BY date DESC");
988 $idrow = sqlFetchArray($idres);
990 // Replace the most recent entry in any of the following cases:
991 // * Its effective date is >= this effective date.
992 // * It is the first entry and it has no (insurance) provider.
993 // * There is no encounter that is earlier than the new effective date but
994 // on or after the old effective date.
995 // Otherwise insert a new entry.
999 if (strcmp($idrow['date'], $effective_date) > 0) {
1003 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1007 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1008 "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
1009 "date >= '" . $idrow['date'] . " 00:00:00'");
1010 if ($ferow['count'] == 0) $replace = true;
1017 // TBD: This is a bit dangerous in that a typo in entering the effective
1018 // date can wipe out previous insurance history. So we want some data
1019 // entry validation somewhere.
1020 sqlStatement("DELETE FROM insurance_data WHERE " .
1021 "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
1022 "id != " . $idrow['id']);
1025 $data['type'] = $type;
1026 $data['provider'] = $provider;
1027 $data['policy_number'] = $policy_number;
1028 $data['group_number'] = $group_number;
1029 $data['plan_name'] = $plan_name;
1030 $data['subscriber_lname'] = $subscriber_lname;
1031 $data['subscriber_mname'] = $subscriber_mname;
1032 $data['subscriber_fname'] = $subscriber_fname;
1033 $data['subscriber_relationship'] = $subscriber_relationship;
1034 $data['subscriber_ss'] = $subscriber_ss;
1035 $data['subscriber_DOB'] = $subscriber_DOB;
1036 $data['subscriber_street'] = $subscriber_street;
1037 $data['subscriber_postal_code'] = $subscriber_postal_code;
1038 $data['subscriber_city'] = $subscriber_city;
1039 $data['subscriber_state'] = $subscriber_state;
1040 $data['subscriber_country'] = $subscriber_country;
1041 $data['subscriber_phone'] = $subscriber_phone;
1042 $data['subscriber_employer'] = $subscriber_employer;
1043 $data['subscriber_employer_city'] = $subscriber_employer_city;
1044 $data['subscriber_employer_street'] = $subscriber_employer_street;
1045 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1046 $data['subscriber_employer_state'] = $subscriber_employer_state;
1047 $data['subscriber_employer_country'] = $subscriber_employer_country;
1048 $data['copay'] = $copay;
1049 $data['subscriber_sex'] = $subscriber_sex;
1050 $data['pid'] = $pid;
1051 $data['date'] = $effective_date;
1052 $data['accept_assignment'] = $accept_assignment;
1053 $data['policy_type'] = $policy_type;
1054 updateInsuranceData($idrow['id'], $data);
1055 return $idrow['id'];
1058 return sqlInsert("INSERT INTO insurance_data SET
1060 provider = '$provider',
1061 policy_number = '$policy_number',
1062 group_number = '$group_number',
1063 plan_name = '$plan_name',
1064 subscriber_lname = '$subscriber_lname',
1065 subscriber_mname = '$subscriber_mname',
1066 subscriber_fname = '$subscriber_fname',
1067 subscriber_relationship = '$subscriber_relationship',
1068 subscriber_ss = '$subscriber_ss',
1069 subscriber_DOB = '$subscriber_DOB',
1070 subscriber_street = '$subscriber_street',
1071 subscriber_postal_code = '$subscriber_postal_code',
1072 subscriber_city = '$subscriber_city',
1073 subscriber_state = '$subscriber_state',
1074 subscriber_country = '$subscriber_country',
1075 subscriber_phone = '$subscriber_phone',
1076 subscriber_employer = '$subscriber_employer',
1077 subscriber_employer_city = '$subscriber_employer_city',
1078 subscriber_employer_street = '$subscriber_employer_street',
1079 subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1080 subscriber_employer_state = '$subscriber_employer_state',
1081 subscriber_employer_country = '$subscriber_employer_country',
1083 subscriber_sex = '$subscriber_sex',
1085 date = '$effective_date',
1086 accept_assignment = '$accept_assignment',
1087 policy_type = '$policy_type'
1092 // This is used internally only.
1093 function updateInsuranceData($id, $new)
1095 $fields = sqlListFields("insurance_data");
1098 while(list($key, $value) = each ($new)) {
1099 if (in_array($key, $fields)) {
1100 $use[$key] = $value;
1104 $sql = "UPDATE insurance_data SET ";
1105 while(list($key, $value) = each($use))
1106 $sql .= "`$key` = '$value', ";
1107 $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1112 function newHistoryData($pid, $new=false) {
1113 $arraySqlBind = array();
1114 $sql = "insert into history_data set pid = ?, date = NOW()";
1115 array_push($arraySqlBind,$pid);
1117 while(list($key, $value) = each($new)) {
1118 array_push($arraySqlBind,$value);
1119 $sql .= ", `$key` = ?";
1122 return sqlInsert($sql, $arraySqlBind );
1125 function updateHistoryData($pid,$new)
1127 $real = getHistoryData($pid);
1128 while(list($key, $value) = each ($new))
1129 $real[$key] = $value;
1131 // need to unset date, so can reset it below
1132 unset($real['date']);
1134 $arraySqlBind = array();
1135 $sql = "insert into history_data set `date` = NOW(), ";
1136 while(list($key, $value) = each($real)) {
1137 array_push($arraySqlBind,$value);
1138 $sql .= "`$key` = ?, ";
1140 $sql = substr($sql, 0, -2);
1142 return sqlInsert($sql, $arraySqlBind );
1145 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1146 $phone_biz,$phone_cell,$email,$pid="")
1148 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1149 if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1151 $db = $GLOBALS['adodb']['db'];
1152 $customer_info = array();
1154 $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1155 $result = $db->Execute($sql);
1156 if ($result && !$result->EOF) {
1157 $customer_info['foreign_update'] = true;
1158 $customer_info['foreign_id'] = $result->fields['foreign_id'];
1159 $customer_info['foreign_table'] = $result->fields['foreign_table'];
1162 ///xml rpc code to connect to accounting package and add user to it
1163 $customer_info['firstname'] = $fname;
1164 $customer_info['lastname'] = $lname;
1165 $customer_info['address'] = $street;
1166 $customer_info['suburb'] = $city;
1167 $customer_info['state'] = $state;
1168 $customer_info['postcode'] = $postal_code;
1170 //ezybiz wants state as a code rather than abbreviation
1171 $customer_info['geo_zone_id'] = "";
1172 $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1173 $db = $GLOBALS['adodb']['db'];
1174 $result = $db->Execute($sql);
1175 if ($result && !$result->EOF) {
1176 $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1179 //ezybiz wants country as a code rather than abbreviation
1180 $customer_info['geo_country_id'] = "";
1181 $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1182 $db = $GLOBALS['adodb']['db'];
1183 $result = $db->Execute($sql);
1184 if ($result && !$result->EOF) {
1185 $customer_info['geo_country_id'] = $result->fields['countries_id'];
1188 $customer_info['phone1'] = $phone_home;
1189 $customer_info['phone1comment'] = "Home Phone";
1190 $customer_info['phone2'] = $phone_biz;
1191 $customer_info['phone2comment'] = "Business Phone";
1192 $customer_info['phone3'] = $phone_cell;
1193 $customer_info['phone3comment'] = "Cell Phone";
1194 $customer_info['email'] = $email;
1195 $customer_info['customernumber'] = $pid;
1197 $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1198 $ws = new WSWrapper($function);
1200 // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1201 if (is_numeric($ws->value)) {
1202 $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1203 $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1208 // in months if < 2 years old
1209 // in years if > 2 years old
1210 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1211 // (optional) nowYMD is a date in YYYYMMDD format
1212 function getPatientAge($dobYMD, $nowYMD=null)
1214 // strip any dashes from the DOB
1215 $dobYMD = preg_replace("/-/", "", $dobYMD);
1216 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1218 // set the 'now' date values
1219 if ($nowYMD == null) {
1220 $nowDay = date("d");
1221 $nowMonth = date("m");
1222 $nowYear = date("Y");
1225 $nowDay = substr($nowYMD,6,2);
1226 $nowMonth = substr($nowYMD,4,2);
1227 $nowYear = substr($nowYMD,0,4);
1230 $dayDiff = $nowDay - $dobDay;
1231 $monthDiff = $nowMonth - $dobMonth;
1232 $yearDiff = $nowYear - $dobYear;
1234 $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1236 if ( $ageInMonths > 24 ) {
1238 if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1239 else if ($monthDiff < 0) { $age -= 1; }
1242 $age = "$ageInMonths month";
1249 // Returns Age in days
1250 // in months if < 2 years old
1251 // in years if > 2 years old
1252 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1253 // (optional) nowYMD is a date in YYYYMMDD format
1254 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1257 // strip any dashes from the DOB
1258 $dobYMD = preg_replace("/-/", "", $dobYMD);
1259 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1261 // set the 'now' date values
1262 if ($nowYMD == null) {
1263 $nowDay = date("d");
1264 $nowMonth = date("m");
1265 $nowYear = date("Y");
1268 $nowDay = substr($nowYMD,6,2);
1269 $nowMonth = substr($nowYMD,4,2);
1270 $nowYear = substr($nowYMD,0,4);
1274 $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1275 $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1276 $timediff = $nowtime - $dobtime;
1277 $age = $timediff / 86400;
1282 function dateToDB ($date)
1284 $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1289 // ----------------------------------------------------------------------------
1291 * DROPDOWN FOR COUNTRIES
1293 * build a dropdown with all countries from geo_country_reference
1295 * @param int $selected - id for selected record
1296 * @param string $name - the name/id for select form
1297 * @return void - just echo the html encoded string
1299 function dropdown_countries($selected = 0, $name = 'country_code') {
1300 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1302 $string = "<select name='$name' id='$name'>";
1303 while ( $row = sqlFetchArray($r) ) {
1304 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1305 $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1308 $string .= '</select>';
1313 // ----------------------------------------------------------------------------
1315 * DROPDOWN FOR YES/NO
1317 * build a dropdown with two options (yes - 1, no - 0)
1319 * @param int $selected - id for selected record
1320 * @param string $name - the name/id for select form
1321 * @return void - just echo the html encoded string
1323 function dropdown_yesno($selected = 0, $name = 'yesno') {
1324 $string = "<select name='$name' id='$name'>";
1326 $selected = (int)$selected;
1327 if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1328 else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1330 $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1331 $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1332 $string .= '</select>';
1337 // ----------------------------------------------------------------------------
1339 * DROPDOWN FOR MALE/FEMALE options
1341 * build a dropdown with three options (unselected/male/female)
1343 * @param int $selected - id for selected record
1344 * @param string $name - the name/id for select form
1345 * @return void - just echo the html encoded string
1347 function dropdown_sex($selected = 0, $name = 'sex') {
1348 $string = "<select name='$name' id='$name'>";
1350 if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1351 else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1352 else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1354 $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1355 $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1356 $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1357 $string .= '</select>';
1362 // ----------------------------------------------------------------------------
1364 * DROPDOWN FOR MARITAL STATUS
1366 * build a dropdown with marital status
1368 * @param int $selected - id for selected record
1369 * @param string $name - the name/id for select form
1370 * @return void - just echo the html encoded string
1372 function dropdown_marital($selected = 0, $name = 'status') {
1373 $string = "<select name='$name' id='$name'>";
1375 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1377 foreach ( $statii as $st ) {
1378 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1379 $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1382 $string .= '</select>';
1387 // ----------------------------------------------------------------------------
1389 * DROPDOWN FOR PROVIDERS
1391 * build a dropdown with all providers
1393 * @param int $selected - id for selected record
1394 * @param string $name - the name/id for select form
1395 * @return void - just echo the html encoded string
1397 function dropdown_providers($selected = 0, $name = 'status') {
1398 $provideri = getProviderInfo();
1400 $string = "<select name='$name' id='$name'>";
1401 $string .= '<option value="">' .xl('Unassigned'). '</option>';
1402 foreach ( $provideri as $s ) {
1403 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1404 $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1407 $string .= '</select>';
1412 // ----------------------------------------------------------------------------
1414 * DROPDOWN FOR INSURANCE COMPANIES
1416 * build a dropdown with all insurers
1418 * @param int $selected - id for selected record
1419 * @param string $name - the name/id for select form
1420 * @return void - just echo the html encoded string
1422 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1423 $insurancei = getInsuranceProviders();
1425 $string = "<select name='$name' id='$name'>";
1426 $string .= '<option value="0">Onbekend</option>';
1427 foreach ( $insurancei as $iid => $iname ) {
1428 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1429 $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1432 $string .= '</select>';
1438 // ----------------------------------------------------------------------------
1442 * return the name or the country code, function of arguments
1444 * @param int $country_code
1445 * @param string $country_name
1446 * @return string | int - name or code
1448 function country_code($country_code = 0, $country_name = '') {
1450 if ( $country_code ) {
1451 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1453 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1456 $db = $GLOBALS['adodb']['db'];
1457 $result = $db->Execute($sql);
1458 if ($result && !$result->EOF) {
1459 $strint = $result->fields['res'];
1465 function DBToDate ($date)
1467 $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1471 function get_patient_balance($pid) {
1472 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1473 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1474 "pid = ? AND activity = 1", array($pid) );
1475 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1476 "pid = ?", array($pid) );
1477 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1478 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1479 "pid = ?", array($pid) );
1480 return sprintf('%01.2f', $brow['amount'] + $srow['amount']
1481 - $drow['payments'] - $drow['adjustments']);
1483 else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1484 // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1485 $conn = $GLOBALS['adodb']['db'];
1486 $customer_info['id'] = 0;
1487 $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1488 "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1489 "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1490 "im.foreign_table = 'customer'";
1491 $result = $conn->Execute($sql);
1492 if($result && !$result->EOF) {
1493 $customer_info['id'] = $result->fields['foreign_id'];
1495 $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1496 $ws = new WSWrapper($function);
1497 if(is_numeric($ws->value)) {
1498 return sprintf('%01.2f', $ws->value);
1504 // Function to check if patient is deceased.
1506 // $pid - patient id
1507 // $date - date checking if deceased (will default to current date if blank)
1509 // If deceased, then will return the number of
1510 // days that patient has been deceased.
1511 // If not deceased, then will return false.
1512 function is_patient_deceased($pid,$date='') {
1514 // Set date to current if not set
1515 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1517 // Query for deceased status (gets days deceased if patient is deceased)
1518 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1519 "FROM `patient_data` " .
1520 "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date) );
1522 if (empty($results)) {
1523 // Patient is alive, so return false
1527 // Patient is dead, so return the number of days patient has been deceased.
1528 // Don't let it be zero days or else will confuse calls to this function.
1529 if ($results['days_deceased'] === 0) {
1530 $results['days_deceased'] = 1;
1532 return $results['days_deceased'];