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 // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1237 if($dayDiff<0) { $ageInMonths-=1; }
1239 if ( $ageInMonths > 24 ) {
1241 if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1242 else if ($monthDiff < 0) { $age -= 1; }
1245 $age = "$ageInMonths month";
1252 * Wrapper to make sure the clinical rules dates formats corresponds to the
1253 * format expected by getPatientAgeYMD
1255 * @param string $dob date of birth
1256 * @param string $target date to calculate age on
1257 * @return array containing
1258 * age - decimal age in years
1259 * age_in_months - decimal age in months
1260 * ageinYMD - formatted string #y #m #d */
1261 function parseAgeInfo($dob,$target)
1263 // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1264 $dateDOB = preg_replace("/[-\s\/]/", "", $dob);;
1265 // Prepare target (Y-M-D H:M:S)
1266 $dateTarget = preg_replace("/[-\s\/]/","",$target);
1268 return getPatientAgeYMD($dateDOB,$dateTarget);
1276 * @return array containing
1277 * age - decimal age in years
1278 * age_in_months - decimal age in months
1279 * ageinYMD - formatted string #y #m #d
1281 function getPatientAgeYMD($dob, $date=null) {
1283 if ($date == null) {
1284 $daynow = date("d");
1285 $monthnow = date("m");
1286 $yearnow = date("Y");
1287 $datenow=$yearnow.$monthnow.$daynow;
1290 $datenow=preg_replace("/-/", "", $date);
1291 $yearnow=substr($datenow,0,4);
1292 $monthnow=substr($datenow,4,2);
1293 $daynow=substr($datenow,6,2);
1294 $datenow=$yearnow.$monthnow.$daynow;
1297 $dob=preg_replace("/-/", "", $dob);
1298 $dobyear=substr($dob,0,4);
1299 $dobmonth=substr($dob,4,2);
1300 $dobday=substr($dob,6,2);
1301 $dob=$dobyear.$dobmonth.$dobday;
1303 //to compensate for 30, 31, 28, 29 days/month
1304 $mo=$monthnow; //to avoid confusion with later calculation
1306 if ($mo==05 or $mo==07 or $mo==10 or $mo==12) { //determined by monthnow-1
1307 $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then
1308 } // look at April, June, September, November for calculation. These months only have 30 days.
1309 elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1310 $check_leap_Y=$yearnow/4; // To check if this is a leap year.
1311 if (is_int($check_leap_Y)) {$nd=29;} //If it true then this is the leap year
1312 else {$nd=28;} //otherwise, it is not a leap year.
1314 else {$nd=31;} // other months have 31 days
1316 $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1317 if ($datenow < $bdthisyear) // if patient hasn't had birthday yet this year
1319 $age_year = $yearnow - $dobyear - 1;
1320 if ($daynow < $dobday) {
1321 $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1322 $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1325 $months_since_birthday=12 - $dobmonth + $monthnow;
1326 $days_since_dobday=$daynow - $dobday;
1329 else // if patient has had birthday this calandar year
1331 $age_year = $yearnow - $dobyear;
1332 if ($daynow < $dobday) {
1333 $months_since_birthday=$monthnow - $dobmonth -1;
1334 $days_since_dobday=$nd - $dobday + $daynow;
1337 $months_since_birthday=$monthnow - $dobmonth;
1338 $days_since_dobday=$daynow - $dobday;
1342 $day_as_month_decimal = $days_since_dobday / 30;
1343 $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1344 $month_as_year_decimal = $months_since_birthday_float / 12;
1345 $age_float = $age_year + $month_as_year_decimal;
1347 $age_in_months = $age_year * 12 + $months_since_birthday_float;
1348 $age_in_months = round($age_in_months,2); //round the months to xx.xx 2 floating points
1349 $age = round($age_float,2);
1351 // round the years to 2 floating points
1352 $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1353 return compact('age','age_in_months','ageinYMD');
1356 // Returns Age in days
1357 // in months if < 2 years old
1358 // in years if > 2 years old
1359 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1360 // (optional) nowYMD is a date in YYYYMMDD format
1361 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1364 // strip any dashes from the DOB
1365 $dobYMD = preg_replace("/-/", "", $dobYMD);
1366 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1368 // set the 'now' date values
1369 if ($nowYMD == null) {
1370 $nowDay = date("d");
1371 $nowMonth = date("m");
1372 $nowYear = date("Y");
1375 $nowDay = substr($nowYMD,6,2);
1376 $nowMonth = substr($nowYMD,4,2);
1377 $nowYear = substr($nowYMD,0,4);
1381 $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1382 $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1383 $timediff = $nowtime - $dobtime;
1384 $age = $timediff / 86400; // 24 hours * 3600 seconds/hour = 86400 seconds
1389 * Returns a string to be used to display a patient's age
1391 * @param type $dobYMD
1392 * @param type $asOfYMD
1393 * @return string suitable for displaying patient's age based on preferences
1395 function getPatientAgeDisplay($dobYMD, $asOfYMD=null)
1397 if($GLOBALS['age_display_format']=='1')
1399 $ageYMD=getPatientAgeYMD($dobYMD,$asOfYMD);
1400 if(isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit'])
1402 return $ageYMD['ageinYMD'];
1406 return getPatientAge($dobYMD, $asOfYMD);
1411 return getPatientAge($dobYMD, $asOfYMD);
1415 function dateToDB ($date)
1417 $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1422 // ----------------------------------------------------------------------------
1424 * DROPDOWN FOR COUNTRIES
1426 * build a dropdown with all countries from geo_country_reference
1428 * @param int $selected - id for selected record
1429 * @param string $name - the name/id for select form
1430 * @return void - just echo the html encoded string
1432 function dropdown_countries($selected = 0, $name = 'country_code') {
1433 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1435 $string = "<select name='$name' id='$name'>";
1436 while ( $row = sqlFetchArray($r) ) {
1437 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1438 $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1441 $string .= '</select>';
1446 // ----------------------------------------------------------------------------
1448 * DROPDOWN FOR YES/NO
1450 * build a dropdown with two options (yes - 1, no - 0)
1452 * @param int $selected - id for selected record
1453 * @param string $name - the name/id for select form
1454 * @return void - just echo the html encoded string
1456 function dropdown_yesno($selected = 0, $name = 'yesno') {
1457 $string = "<select name='$name' id='$name'>";
1459 $selected = (int)$selected;
1460 if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1461 else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1463 $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1464 $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1465 $string .= '</select>';
1470 // ----------------------------------------------------------------------------
1472 * DROPDOWN FOR MALE/FEMALE options
1474 * build a dropdown with three options (unselected/male/female)
1476 * @param int $selected - id for selected record
1477 * @param string $name - the name/id for select form
1478 * @return void - just echo the html encoded string
1480 function dropdown_sex($selected = 0, $name = 'sex') {
1481 $string = "<select name='$name' id='$name'>";
1483 if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1484 else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1485 else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1487 $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1488 $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1489 $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1490 $string .= '</select>';
1495 // ----------------------------------------------------------------------------
1497 * DROPDOWN FOR MARITAL STATUS
1499 * build a dropdown with marital status
1501 * @param int $selected - id for selected record
1502 * @param string $name - the name/id for select form
1503 * @return void - just echo the html encoded string
1505 function dropdown_marital($selected = 0, $name = 'status') {
1506 $string = "<select name='$name' id='$name'>";
1508 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1510 foreach ( $statii as $st ) {
1511 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1512 $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1515 $string .= '</select>';
1520 // ----------------------------------------------------------------------------
1522 * DROPDOWN FOR PROVIDERS
1524 * build a dropdown with all providers
1526 * @param int $selected - id for selected record
1527 * @param string $name - the name/id for select form
1528 * @return void - just echo the html encoded string
1530 function dropdown_providers($selected = 0, $name = 'status') {
1531 $provideri = getProviderInfo();
1533 $string = "<select name='$name' id='$name'>";
1534 $string .= '<option value="">' .xl('Unassigned'). '</option>';
1535 foreach ( $provideri as $s ) {
1536 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1537 $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1540 $string .= '</select>';
1545 // ----------------------------------------------------------------------------
1547 * DROPDOWN FOR INSURANCE COMPANIES
1549 * build a dropdown with all insurers
1551 * @param int $selected - id for selected record
1552 * @param string $name - the name/id for select form
1553 * @return void - just echo the html encoded string
1555 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1556 $insurancei = getInsuranceProviders();
1558 $string = "<select name='$name' id='$name'>";
1559 $string .= '<option value="0">Onbekend</option>';
1560 foreach ( $insurancei as $iid => $iname ) {
1561 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1562 $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1565 $string .= '</select>';
1571 // ----------------------------------------------------------------------------
1575 * return the name or the country code, function of arguments
1577 * @param int $country_code
1578 * @param string $country_name
1579 * @return string | int - name or code
1581 function country_code($country_code = 0, $country_name = '') {
1583 if ( $country_code ) {
1584 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1586 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1589 $db = $GLOBALS['adodb']['db'];
1590 $result = $db->Execute($sql);
1591 if ($result && !$result->EOF) {
1592 $strint = $result->fields['res'];
1598 function DBToDate ($date)
1600 $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1605 * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1606 * for the given patient on the given date.
1608 * @param int The PID of the patient.
1609 * @param string Date in yyyy-mm-dd format.
1610 * @return array Array of 0-3 insurance_data rows.
1612 function getEffectiveInsurances($patient_id, $encdate) {
1614 foreach (array('primary','secondary','tertiary') as $instype) {
1615 $tmp = sqlQuery("SELECT * FROM insurance_data " .
1616 "WHERE pid = ? AND type = ? " .
1617 "AND date <= ? ORDER BY date DESC LIMIT 1",
1618 array($patient_id, $instype, $encdate));
1619 if (empty($tmp['provider'])) break;
1626 * Get the patient's balance due. Normally this excludes amounts that are out
1627 * to insurance. If you want to include what insurance owes, set the second
1628 * parameter to true.
1630 * @param int The PID of the patient.
1631 * @param boolean Indicates if amounts owed by insurance are to be included.
1632 * @return number The balance.
1634 function get_patient_balance($pid, $with_insurance=false) {
1635 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1637 $feres = sqlStatement("SELECT date, encounter, last_level_billed, " .
1638 "last_level_closed, stmt_count " .
1639 "FROM form_encounter WHERE pid = ?", array($pid));
1640 while ($ferow = sqlFetchArray($feres)) {
1641 $encounter = $ferow['encounter'];
1642 $dos = substr($ferow['date'], 0, 10);
1643 $insarr = getEffectiveInsurances($pid, $dos);
1644 $inscount = count($insarr);
1645 if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1646 // It's out to insurance so only the co-pay might be due.
1647 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1648 "pid = ? AND encounter = ? AND " .
1649 "code_type = 'copay' AND activity = 1",
1650 array($pid, $encounter));
1651 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments " .
1652 "FROM ar_activity WHERE " .
1653 "pid = ? AND encounter = ? AND payer_type = 0",
1654 array($pid, $encounter));
1655 $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1656 if ($ptbal > 0) $balance += $ptbal;
1659 // Including insurance or not out to insurance, everything is due.
1660 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1661 "pid = ? AND encounter = ? AND " .
1662 "activity = 1", array($pid, $encounter));
1663 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1664 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1665 "pid = ? AND encounter = ?", array($pid, $encounter));
1666 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1667 "pid = ? AND encounter = ?", array($pid, $encounter));
1668 $balance += $brow['amount'] + $srow['amount']
1669 - $drow['payments'] - $drow['adjustments'];
1672 return sprintf('%01.2f', $balance);
1674 else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1675 // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1676 $conn = $GLOBALS['adodb']['db'];
1677 $customer_info['id'] = 0;
1678 $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1679 "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1680 "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1681 "im.foreign_table = 'customer'";
1682 $result = $conn->Execute($sql);
1683 if($result && !$result->EOF) {
1684 $customer_info['id'] = $result->fields['foreign_id'];
1686 $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1687 $ws = new WSWrapper($function);
1688 if(is_numeric($ws->value)) {
1689 return sprintf('%01.2f', $ws->value);
1695 // Function to check if patient is deceased.
1697 // $pid - patient id
1698 // $date - date checking if deceased (will default to current date if blank)
1700 // If deceased, then will return the number of
1701 // days that patient has been deceased.
1702 // If not deceased, then will return false.
1703 function is_patient_deceased($pid,$date='') {
1705 // Set date to current if not set
1706 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1708 // Query for deceased status (gets days deceased if patient is deceased)
1709 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1710 "FROM `patient_data` " .
1711 "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date) );
1713 if (empty($results)) {
1714 // Patient is alive, so return false
1718 // Patient is dead, so return the number of days patient has been deceased.
1719 // Don't let it be zero days or else will confuse calls to this function.
1720 if ($results['days_deceased'] === 0) {
1721 $results['days_deceased'] = 1;
1723 return $results['days_deceased'];