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 $facilityService = new \services\FacilityService();
13 // These are for sports team use:
14 $PLAYER_FITNESSES = array(
17 xl('Restricted Training'),
21 xl('International Duty')
23 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
25 // Hard-coding this array because its values and meanings are fixed by the 837p
26 // standard and we don't want people messing with them.
27 $policy_types = array(
29 '12' => xl('Working Aged Beneficiary or Spouse with Employer Group Health Plan'),
30 '13' => xl('End-Stage Renal Disease Beneficiary in MCP with Employer`s Group Plan'),
31 '14' => xl('No-fault Insurance including Auto is Primary'),
32 '15' => xl('Worker`s Compensation'),
33 '16' => xl('Public Health Service (PHS) or Other Federal Agency'),
34 '41' => xl('Black Lung'),
35 '42' => xl('Veteran`s Administration'),
36 '43' => xl('Disabled Beneficiary Under Age 65 with Large Group Health Plan (LGHP)'),
37 '47' => xl('Other Liability Insurance is Primary'),
41 * Get a patient's demographic data.
43 * @param int $pid The PID of the patient
44 * @param string $given an optional subsection of the patient's demographic
46 * @return array The requested subsection of a patient's demographic data.
47 * If no subsection was given, returns everything, with the
48 * date of birth as the last field.
50 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS")
52 $sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
53 return sqlQuery($sql, array($pid) );
56 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)
72 $sql = "select name from insurance_companies where id=?";
73 $row = sqlQuery($sql,array($ins_id));
78 function getInsuranceProviders()
83 $sql = "select name, id from insurance_companies where inactive != 1 order by name, id";
84 $rez = sqlStatement($sql);
85 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
86 $returnval[$row['id']] = $row['name'];
90 // Please leave this here. I have a user who wants to see zip codes and PO
91 // box numbers listed along with the insurance company names, as many companies
92 // have different billing addresses for different plans. -- Rod Roark
95 $sql = "select insurance_companies.name, insurance_companies.id, " .
96 "addresses.zip, addresses.line1 " .
97 "from insurance_companies, addresses " .
98 "where addresses.foreign_id = insurance_companies.id " .
99 "order by insurance_companies.name, addresses.zip";
101 $rez = sqlStatement($sql);
103 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
104 preg_match("/\d+/", $row['line1'], $matches);
105 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
106 "," . $matches[0] . ")";
113 function getInsuranceProvidersExtra()
115 $returnval = array();
116 // add a global and if for where to allow inactive inscompanies
118 $sql = "SELECT insurance_companies.name, insurance_companies.id, addresses.line1, addresses.line2, addresses.city,
119 addresses.state, addresses.zip
120 FROM insurance_companies, addresses
121 WHERE addresses.foreign_id = insurance_companies.id
122 AND insurance_companies.inactive != 1
123 ORDER BY insurance_companies.name, addresses.zip";
125 $rez = sqlStatement($sql);
127 for ($iter = 0; $row = sqlFetchArray($rez); $iter++) {
128 switch ($GLOBALS['insurance_information']) {
129 case $GLOBALS['insurance_information'] = '0':
130 $returnval[$row['id']] = $row['name'];
132 case $GLOBALS['insurance_information'] = '1':
133 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ")";
135 case $GLOBALS['insurance_information'] = '2':
136 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['zip'] . ")";
138 case $GLOBALS['insurance_information'] = '3':
139 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] . ")";
141 case $GLOBALS['insurance_information'] = '4':
142 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['state'] .
143 ", " . $row['zip'] . ")";
145 case $GLOBALS['insurance_information'] = '5':
146 $returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ", " . $row['line2'] . ", " . $row['city'] .
147 ", " . $row['state'] . ", " . $row['zip'] . ")";
149 case $GLOBALS['insurance_information'] = '6':
150 preg_match("/\d+/", $row['line1'], $matches);
151 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
152 "," . $matches[0] . ")";
160 function getProviders()
162 $returnval = array("");
163 $sql = "select fname, lname, suffix from users where authorized = 1 and " .
164 "active = 1 and username != ''";
165 $rez = sqlStatement($sql);
166 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
167 if (($row["fname"] != "") && ($row["lname"] != "")) {
168 if ($row["suffix"] != "") $row["lname"] .= ", ".$row["suffix"];
169 array_push($returnval, $row["fname"] . " " . $row["lname"]);
175 // ----------------------------------------------------------------------------
176 // Get one facility row. If the ID is not specified, then get either the
177 // "main" (billing) facility, or the default facility of the currently
178 // logged-in user. This was created to support genFacilityTitle() but
179 // may find additional uses.
181 function getFacility($facid=0)
183 global $facilityService;
188 $facility = $facilityService->getById($facid);
190 else if ($facid == 0) {
191 $facility = $facilityService->getPrimaryBillingLocation();
194 $facility = $facilityService->getFacilityForUser($_SESSION['authUserID']);
200 // Generate a report title including report name and facility name, address
203 function genFacilityTitle($repname='', $facid=0)
206 $s .= "<table class='ftitletable'>\n";
208 $s .= " <td class='ftitlecell1'>$repname</td>\n";
209 $s .= " <td class='ftitlecell2'>\n";
210 $r = getFacility($facid);
212 $s .= "<b>" . htmlspecialchars( $r['name'], ENT_NOQUOTES) . "</b>\n";
213 if ($r['street']) $s .= "<br />" . htmlspecialchars( $r['street'], ENT_NOQUOTES) . "\n";
214 if ($r['city'] || $r['state'] || $r['postal_code']) {
216 if ($r['city']) $s .= htmlspecialchars( $r['city'], ENT_NOQUOTES);
218 if ($r['city']) $s .= ", \n";
219 $s .= htmlspecialchars( $r['state'], ENT_NOQUOTES);
221 if ($r['postal_code']) $s .= " " . htmlspecialchars( $r['postal_code'], ENT_NOQUOTES);
224 if ($r['country_code']) $s .= "<br />" . htmlspecialchars( $r['country_code'], ENT_NOQUOTES) . "\n";
225 if (preg_match('/[1-9]/', $r['phone'])) $s .= "<br />" . htmlspecialchars( $r['phone'], ENT_NOQUOTES) . "\n";
236 returns all facilities or just the id for the first one
237 (FACILITY FILTERING (lemonsoftware))
239 @param string - if 'first' return first facility ordered by id
240 @return array | int for 'first' case
242 function getFacilities($first = '')
244 global $facilityService;
246 $fres = $facilityService->getAll();
248 if ($first == 'first') {
249 return $fres[0]['id'];
256 GET SERVICE FACILITIES
258 returns all service_location facilities or just the id for the first one
259 (FACILITY FILTERING (CHEMED))
261 @param string - if 'first' return first facility ordered by id
262 @return array | int for 'first' case
264 function getServiceFacilities($first = '')
266 global $facilityService;
268 $fres = $facilityService->getAllServiceLocations();
270 if ($first == 'first') {
271 return $fres[0]['id'];
277 //(CHEMED) facility filter
278 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' )
281 if ($providers_only === 'any') {
282 $param1 = " AND authorized = 1 AND active = 1 ";
284 else if ($providers_only) {
285 $param1 = " AND authorized = 1 AND calendar = 1 ";
288 //--------------------------------
289 //(CHEMED) facility filter
292 if ($GLOBALS['restrict_user_facility']) {
293 $param2 = " AND (facility_id = $facility
297 where tablename = 'users'
303 $param2 = " AND facility_id = $facility ";
306 //--------------------------------
309 if ($providerID == "%") {
312 $query = "select distinct id, username, lname, fname, authorized, info, facility, suffix " .
313 "from users where username != '' and active = 1 and id $command '" .
314 add_escape_custom($providerID) . "' " . $param1 . $param2;
315 // sort by last name -- JRM June 2008
316 $query .= " ORDER BY lname, fname ";
317 $rez = sqlStatement($query);
318 for($iter=0; $row=sqlFetchArray($rez); $iter++)
319 $returnval[$iter]=$row;
321 //if only one result returned take the key/value pairs in array [0] and merge them down into
322 // the base array so that $resultval[0]['key'] is also accessible from $resultval['key']
325 $akeys = array_keys($returnval[0]);
326 foreach($akeys as $key) {
327 $returnval[0][$key] = $returnval[0][$key];
333 //same as above but does not reduce if only 1 row returned
334 function getCalendarProviderInfo($providerID = "%", $providers_only = true)
337 if ($providers_only) {
338 $param1 = "AND authorized=1";
341 if ($providerID == "%") {
344 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
345 "from users where active = 1 and username != '' and id $command '" .
346 add_escape_custom($providerID) . "' " . $param1;
348 $rez = sqlStatement($query);
349 for($iter=0; $row=sqlFetchArray($rez); $iter++)
350 $returnval[$iter]=$row;
355 function getProviderName($providerID)
357 $pi = getProviderInfo($providerID, 'any');
358 if (strlen($pi[0]["lname"]) > 0) {
359 if (strlen($pi[0]["suffix"]) > 0) $pi[0]["lname"] .= ", ".$pi[0]["suffix"];
360 return $pi[0]['fname'] . " " . $pi[0]['lname'];
365 function getProviderId($providerName)
367 $query = "select id from users where username = ?";
368 $rez = sqlStatement($query, array($providerName) );
369 for($iter=0; $row=sqlFetchArray($rez); $iter++)
370 $returnval[$iter]=$row;
374 function getEthnoRacials()
376 $returnval = array("");
377 $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
378 $rez = sqlStatement($sql);
379 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
380 if (($row["ethnoracial"] != "")) {
381 array_push($returnval, $row["ethnoracial"]);
387 function getHistoryData($pid, $given = "*", $dateStart='',$dateEnd='')
390 if ($dateStart && $dateEnd) {
391 $res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd) );
393 else if ($dateStart && !$dateEnd) {
394 $res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart) );
396 else if (!$dateStart && $dateEnd) {
397 $res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd) );
400 $res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid) );
403 if($given == 'tobacco'){
404 $res = sqlQuery("select $given from history_data where pid = ? and tobacco is not null and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd));
410 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
411 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
413 $sql = "select $given from insurance_data as insd " .
414 "left join insurance_companies as ic on ic.id = insd.provider " .
415 "where pid = ? and type = ? order by date DESC limit 1";
416 return sqlQuery($sql, array($pid, $type) );
419 function getInsuranceDataByDate(
423 $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name"
425 // this must take the date in the following manner: YYYY-MM-DD
426 // this function recalls the insurance value that was most recently enterred from the
427 // given date. it will call up most recent records up to and on the date given,
428 // but not records enterred after the given date
429 $sql = "select $given from insurance_data as insd " .
430 "left join insurance_companies as ic on ic.id = provider " .
431 "where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
432 "type=? order by date DESC limit 1";
433 return sqlQuery($sql, array($pid,$date,$type) );
436 function getEmployerData($pid, $given = "*")
438 $sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
439 return sqlQuery($sql, array($pid) );
442 function _set_patient_inc_count($limit, $count, $where, $whereBindArray=array())
444 // When the limit is exceeded, find out what the unlimited count would be.
445 $GLOBALS['PATIENT_INC_COUNT'] = $count;
446 // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
447 if ($limit != "all") {
448 $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
449 $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
454 * Allow the last name to be followed by a comma and some part of a first name(can
455 * also place middle name after the first name with a space separating them)
456 * Allows comma alone followed by some part of a first name(can also place middle name
457 * after the first name with a space separating them).
458 * Allows comma alone preceded by some part of a last name.
459 * If no comma or space, then will search both last name and first name.
460 * If the first letter of either name is capital, searches for name starting
461 * with given substring (the expected behavior). If it is lower case, it
462 * searches for the substring anywhere in the name. This applies to either
463 * last name, first name, and middle name.
464 * Also allows first name followed by middle and/or last name when separated by spaces.
465 * @param string $term
466 * @param string $given
467 * @param string $orderby
468 * @param string $limit
469 * @param string $start
472 function getPatientLnames($term = "%", $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")
474 $names = getPatientNameSplit($term);
476 foreach ($names as $key => $val) {
478 if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
479 $names[$key] = '%' . $val . '%';
481 $names[$key] = $val . '%';
486 // Debugging section below
487 //if(array_key_exists('first',$names)) {
488 // error_log("first name search term :".$names['first']);
490 //if(array_key_exists('middle',$names)) {
491 // error_log("middle name search term :".$names['middle']);
493 //if(array_key_exists('last',$names)) {
494 // error_log("last name search term :".$names['last']);
496 // Debugging section above
498 $sqlBindArray = array();
499 if(array_key_exists('last',$names) && $names['last'] == '') {
500 // Do not search last name
501 $where = "fname LIKE ? ";
502 array_push($sqlBindArray, $names['first']);
503 if ($names['middle'] != '') {
504 $where .= "AND mname LIKE ? ";
505 array_push($sqlBindArray, $names['middle']);
507 } elseif(array_key_exists('first',$names) && $names['first'] == '') {
508 // Do not search first name or middle name
509 $where = "lname LIKE ? ";
510 array_push($sqlBindArray, $names['last']);
511 } elseif($names['first'] == '' && $names['last'] != '') {
512 // Search both first name and last name with same term
513 $names['first'] = $names['last'];
514 $where = "lname LIKE ? OR fname LIKE ? ";
515 array_push($sqlBindArray, $names['last'], $names['first']);
516 } elseif ($names['middle'] != '') {
517 $where = "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";
518 array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
520 $where = "lname LIKE ? AND fname LIKE ? ";
521 array_push($sqlBindArray, $names['last'], $names['first']);
524 if (!empty($GLOBALS['pt_restrict_field'])) {
525 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
526 $where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
527 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
528 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
529 array_push($sqlBindArray, $_SESSION{"authUser"});
533 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
534 if ($limit != "all") $sql .= " LIMIT $start, $limit";
536 $rez = sqlStatement($sql, $sqlBindArray);
539 for($iter=0; $row=sqlFetchArray($rez); $iter++)
540 $returnval[$iter] = $row;
542 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
546 * Accept a string used by a search function expected to find a patient name,
547 * then split up the string if a comma or space exists. Return an array having
548 * from 1 to 3 elements, named first, middle, and last.
549 * See above getPatientLnames() function for details on how the splitting occurs.
550 * @param string $term
553 function getPatientNameSplit($term)
556 if (strpos($term, ',') !== false) {
557 $names = explode(',', $term);
558 $n['last'] = $names[0];
559 if (strpos(trim($names[1]), ' ') !== false) {
560 list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
562 $n['first'] = $names[1];
564 } elseif (strpos($term, ' ') !== false) {
565 $names = explode(' ', $term);
566 if (count($names) == 1) {
567 $n['last'] = $names[0];
568 } elseif (count($names) == 3) {
569 $n['first'] = $names[0];
570 $n['middle'] = $names[1];
571 $n['last'] = $names[2];
573 // This will handle first and last name or first followed by
574 // multiple names only using just the last of the names in the list.
575 $n['first'] = $names[0];
576 $n['last'] = end($names);
580 if(empty($n['last'])) $n['last'] = '%';
582 // Trim whitespace off the names before returning
583 foreach($n as $key => $val) {
584 $n[$key] = trim($val);
586 return $n; // associative array containing names
589 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")
592 $sqlBindArray = array();
593 $where = "pubpid LIKE ? ";
594 array_push($sqlBindArray, $pid."%");
595 if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
596 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
597 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
598 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
599 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
600 array_push($sqlBindArray, $_SESSION{"authUser"});
604 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
605 if ($limit != "all") $sql .= " limit $start, $limit";
606 $rez = sqlStatement($sql, $sqlBindArray);
607 for($iter=0; $row=sqlFetchArray($rez); $iter++)
608 $returnval[$iter]=$row;
610 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
614 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")
616 $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%") );
618 $sqlBindArray = array();
620 for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
624 $where .= " ".add_escape_custom($row["field_id"])." like ? ";
625 array_push($sqlBindArray, "%".$searchTerm."%");
628 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
629 if ($limit != "all") $sql .= " limit $start, $limit";
630 $rez = sqlStatement($sql, $sqlBindArray);
631 for($iter=0; $row=sqlFetchArray($rez); $iter++)
632 $returnval[$iter]=$row;
633 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
637 function getByPatientDemographicsFilter(
640 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS",
641 $orderby = "lname ASC, fname ASC",
644 $search_service_code=''
647 $layoutCols = explode( '~', $searchFields );
648 $sqlBindArray = array();
651 foreach ($layoutCols as $val) {
652 if (empty($val)) continue;
657 $where .= " ".add_escape_custom($val)." = ? ";
658 array_push($sqlBindArray, $searchTerm);
661 $where .= " ".add_escape_custom($val)." like ? ";
662 array_push($sqlBindArray, $searchTerm."%");
667 // If no search terms, ensure valid syntax.
668 if ($i == 0) $where = "1 = 1";
670 // If a non-empty service code was given, then restrict to patients who
671 // have been provided that service. Since the code is used in a LIKE
672 // clause, % and _ wildcards are supported.
673 if ($search_service_code) {
674 $where = "( $where ) AND " .
675 "( SELECT COUNT(*) FROM billing AS b WHERE " .
676 "b.pid = patient_data.pid AND " .
677 "b.activity = 1 AND " .
678 "b.code_type != 'COPAY' AND " .
681 array_push($sqlBindArray, $search_service_code);
684 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
685 if ($limit != "all") $sql .= " limit $start, $limit";
686 $rez = sqlStatement($sql, $sqlBindArray);
687 for($iter=0; $row=sqlFetchArray($rez); $iter++)
688 $returnval[$iter]=$row;
689 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
693 // return a collection of Patient PIDs
694 // new arg style by JRM March 2008
695 // 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")
696 function getPatientPID($args)
699 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
700 $orderby = "lname ASC, fname ASC";
704 // alter default values if defined in the passed in args
705 if (isset($args['pid'])) { $pid = $args['pid']; }
706 if (isset($args['given'])) { $given = $args['given']; }
707 if (isset($args['orderby'])) { $orderby = $args['orderby']; }
708 if (isset($args['limit'])) { $limit = $args['limit']; }
709 if (isset($args['start'])) { $start = $args['start']; }
712 if ($pid == -1) $pid = "%";
713 elseif (empty($pid)) $pid = "NULL";
715 if (strstr($pid,"%")) $command = "like";
717 $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
718 if ($limit != "all") $sql .= " limit $start, $limit";
720 $rez = sqlStatement($sql);
721 for($iter=0; $row=sqlFetchArray($rez); $iter++)
722 $returnval[$iter]=$row;
727 /* return a patient's name in the format LAST, FIRST */
728 function getPatientName($pid)
730 if (empty($pid)) return "";
731 $patientData = getPatientPID(array("pid"=>$pid));
732 if (empty($patientData[0]['lname'])) return "";
733 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
737 /* find patient data by DOB */
738 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
740 $DOB = fixDate($DOB, $DOB);
741 $sqlBindArray = array();
742 $where = "DOB like ? ";
743 array_push($sqlBindArray, $DOB."%");
744 if (!empty($GLOBALS['pt_restrict_field'])) {
745 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
746 $where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
747 " = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
748 add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
749 array_push($sqlBindArray, $_SESSION{"authUser"});
753 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
755 if ($limit != "all") $sql .= " LIMIT $start, $limit";
757 $rez = sqlStatement($sql, $sqlBindArray);
758 for($iter=0; $row=sqlFetchArray($rez); $iter++)
759 $returnval[$iter]=$row;
761 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
765 /* find patient data by SSN */
766 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
768 $sqlBindArray = array();
769 $where = "ss LIKE ?";
770 array_push($sqlBindArray, $ss."%");
771 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
772 if ($limit != "all") $sql .= " LIMIT $start, $limit";
774 $rez = sqlStatement($sql, $sqlBindArray);
775 for($iter=0; $row=sqlFetchArray($rez); $iter++)
776 $returnval[$iter]=$row;
778 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
782 //(CHEMED) Search by phone number
783 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
785 $phone = preg_replace( "/[[:punct:]]/","", $phone );
786 $sqlBindArray = array();
787 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
788 array_push($sqlBindArray, $phone);
789 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
790 if ($limit != "all") $sql .= " LIMIT $start, $limit";
792 $rez = sqlStatement($sql, $sqlBindArray);
793 for($iter=0; $row=sqlFetchArray($rez); $iter++)
794 $returnval[$iter]=$row;
796 _set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
800 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
802 $sql="select $given from patient_data order by $orderby";
805 $sql .= " limit $start, $limit";
807 $rez = sqlStatement($sql);
808 for($iter=0; $row=sqlFetchArray($rez); $iter++)
809 $returnval[$iter]=$row;
814 //----------------------input functions
815 function newPatientData(
834 $contact_relationship = "",
841 $migrantseasonal = "",
843 $monthly_income = "",
845 $financial_review = "",
859 $drivers_license = "",
865 $DOB = fixDate($DOB);
866 $regdate = fixDate($regdate);
869 $referral_source = '';
871 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
872 // Check for brain damage:
873 if ($db_id != $rez['id']) {
874 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
875 $rez['id'] . "' to '$db_id' for pid '$pid'";
878 $fitness = $rez['fitness'];
879 $referral_source = $rez['referral_source'];
882 // Get the default price level.
883 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
884 "list_id = 'pricelevel' AND activity = 1 ORDER BY is_default DESC, seq ASC LIMIT 1");
885 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
887 $query = ("replace into patient_data set
896 postal_code='$postal_code',
899 country_code='$country_code',
900 drivers_license='$drivers_license',
902 occupation='$occupation',
903 phone_home='$phone_home',
904 phone_biz='$phone_biz',
905 phone_contact='$phone_contact',
907 contact_relationship='$contact_relationship',
908 referrer='$referrer',
909 referrerID='$referrerID',
911 language='$language',
912 ethnoracial='$ethnoracial',
913 interpretter='$interpretter',
914 migrantseasonal='$migrantseasonal',
915 family_size='$family_size',
916 monthly_income='$monthly_income',
917 homeless='$homeless',
918 financial_review='$financial_review',
921 providerID = '$providerID',
922 genericname1 = '$genericname1',
923 genericval1 = '$genericval1',
924 genericname2 = '$genericname2',
925 genericval2 = '$genericval2',
926 billing_note= '$billing_note',
927 phone_cell = '$phone_cell',
928 pharmacy_id = '$pharmacy_id',
929 hipaa_mail = '$hipaa_mail',
930 hipaa_voice = '$hipaa_voice',
931 hipaa_notice = '$hipaa_notice',
932 hipaa_message = '$hipaa_message',
935 referral_source='$referral_source',
937 pricelevel='$pricelevel',
940 $id = sqlInsert($query);
943 // find the last inserted id for new patient case
944 $db_id = getSqlLastID();
947 $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
952 // Supported input date formats are:
954 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
956 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
958 function fixDate($date, $default="0000-00-00")
960 $fixed_date = $default;
962 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
963 $dmy = preg_split("'[/.-]'", $date);
965 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
967 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
968 if ($dmy[2] < 1000) $dmy[2] += 1900;
969 if ($dmy[2] < 1910) $dmy[2] += 100;
971 // phone_country_code indicates format of ambiguous input dates.
972 if ($GLOBALS['phone_country_code'] == 1)
973 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
975 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[1], $dmy[0]);
982 function pdValueOrNull($key, $value)
984 if (($key == 'DOB' || $key == 'regdate' || $key == 'contrastart' ||
985 substr($key, 0, 8) == 'userdate' || $key == 'deceased_date') &&
986 (empty($value) || $value == '0000-00-00'))
991 return "'" . add_escape_custom($value) . "'";
995 // Create or update patient data from an array.
997 function updatePatientData($pid, $new, $create=false)
999 /*******************************************************************
1000 $real = getPatientData($pid);
1001 $new['DOB'] = fixDate($new['DOB']);
1002 while(list($key, $value) = each ($new))
1003 $real[$key] = $value;
1004 $real['date'] = "'+NOW()+'";
1006 $sql = "insert into patient_data set ";
1007 while(list($key, $value) = each($real))
1008 $sql .= $key." = '$value', ";
1009 $sql = substr($sql, 0, -2);
1010 return sqlInsert($sql);
1011 *******************************************************************/
1013 // The above was broken, though seems intent to insert a new patient_data
1014 // row for each update. A good idea, but nothing is doing that yet so
1015 // the code below does not yet attempt it.
1017 $new['DOB'] = fixDate($new['DOB']);
1020 $sql = "INSERT INTO patient_data SET pid = '" . add_escape_custom($pid) . "', date = NOW()";
1021 foreach ($new as $key => $value) {
1022 if ($key == 'id') continue;
1023 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1025 $db_id = sqlInsert($sql);
1028 $db_id = $new['id'];
1029 $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '" . add_escape_custom($db_id) . "'");
1030 // Check for brain damage:
1031 if ($pid != $rez['pid']) {
1032 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
1033 text($rez['pid']) . "' when current pid is '" . text($pid) . "' for id '" . text($db_id) . "'";
1036 $sql = "UPDATE patient_data SET date = NOW()";
1037 foreach ($new as $key => $value) {
1038 $sql .= ", `$key` = " . pdValueOrNull($key, $value);
1040 $sql .= " WHERE id = '" . add_escape_custom($db_id) . "'";
1047 function newEmployerData(
1057 return sqlInsert("insert into employer_data set
1060 postal_code='$postal_code',
1069 // Create or update employer data from an array.
1071 function updateEmployerData($pid, $new, $create=false)
1073 $colnames = array('name','street','city','state','postal_code','country');
1076 $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1077 foreach ($colnames as $key) {
1078 $value = isset($new[$key]) ? $new[$key] : '';
1079 $set .= ", `$key` = '" . add_escape_custom($value) . "'";
1081 return sqlInsert("INSERT INTO employer_data SET $set");
1085 $old = getEmployerData($pid);
1087 foreach ($colnames as $key) {
1088 $value = empty($old[$key]) ? '' : $old[$key];
1089 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
1090 $value = $new[$key];
1093 $set .= "`$key` = '" . add_escape_custom($value) . "', ";
1096 $set .= "pid = '" . add_escape_custom($pid) . "', date = NOW()";
1097 return sqlInsert("INSERT INTO employer_data SET $set");
1103 // This updates or adds the given insurance data info, while retaining any
1104 // previously added insurance_data rows that should be preserved.
1105 // This does not directly support the maintenance of non-current insurance.
1107 function newInsuranceData(
1111 $policy_number = "",
1114 $subscriber_lname = "",
1115 $subscriber_mname = "",
1116 $subscriber_fname = "",
1117 $subscriber_relationship = "",
1118 $subscriber_ss = "",
1119 $subscriber_DOB = "",
1120 $subscriber_street = "",
1121 $subscriber_postal_code = "",
1122 $subscriber_city = "",
1123 $subscriber_state = "",
1124 $subscriber_country = "",
1125 $subscriber_phone = "",
1126 $subscriber_employer = "",
1127 $subscriber_employer_street = "",
1128 $subscriber_employer_city = "",
1129 $subscriber_employer_postal_code = "",
1130 $subscriber_employer_state = "",
1131 $subscriber_employer_country = "",
1133 $subscriber_sex = "",
1134 $effective_date = "0000-00-00",
1135 $accept_assignment = "TRUE",
1139 if (strlen($type) <= 0) return false;
1141 // If a bad date was passed, err on the side of caution.
1142 $effective_date = fixDate($effective_date, date('Y-m-d'));
1144 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
1145 "pid = ? AND type = ? ORDER BY date DESC", array($pid,$type));
1146 $idrow = sqlFetchArray($idres);
1148 // Replace the most recent entry in any of the following cases:
1149 // * Its effective date is >= this effective date.
1150 // * It is the first entry and it has no (insurance) provider.
1151 // * There is no encounter that is earlier than the new effective date but
1152 // on or after the old effective date.
1153 // Otherwise insert a new entry.
1157 if (strcmp($idrow['date'], $effective_date) > 0) {
1161 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
1165 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
1166 "WHERE pid = ? AND date < ? AND " .
1167 "date >= ?", array($pid, $effective_date." 00:00:00", $idrow['date']." 00:00:00"));
1168 if ($ferow['count'] == 0) $replace = true;
1175 // TBD: This is a bit dangerous in that a typo in entering the effective
1176 // date can wipe out previous insurance history. So we want some data
1177 // entry validation somewhere.
1178 sqlStatement("DELETE FROM insurance_data WHERE " .
1179 "pid = ? AND type = ? AND date >= ? AND " .
1180 "id != ?", array($pid, $type, $effective_date, $idrow['id']));
1183 $data['type'] = $type;
1184 $data['provider'] = $provider;
1185 $data['policy_number'] = $policy_number;
1186 $data['group_number'] = $group_number;
1187 $data['plan_name'] = $plan_name;
1188 $data['subscriber_lname'] = $subscriber_lname;
1189 $data['subscriber_mname'] = $subscriber_mname;
1190 $data['subscriber_fname'] = $subscriber_fname;
1191 $data['subscriber_relationship'] = $subscriber_relationship;
1192 $data['subscriber_ss'] = $subscriber_ss;
1193 $data['subscriber_DOB'] = $subscriber_DOB;
1194 $data['subscriber_street'] = $subscriber_street;
1195 $data['subscriber_postal_code'] = $subscriber_postal_code;
1196 $data['subscriber_city'] = $subscriber_city;
1197 $data['subscriber_state'] = $subscriber_state;
1198 $data['subscriber_country'] = $subscriber_country;
1199 $data['subscriber_phone'] = $subscriber_phone;
1200 $data['subscriber_employer'] = $subscriber_employer;
1201 $data['subscriber_employer_city'] = $subscriber_employer_city;
1202 $data['subscriber_employer_street'] = $subscriber_employer_street;
1203 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1204 $data['subscriber_employer_state'] = $subscriber_employer_state;
1205 $data['subscriber_employer_country'] = $subscriber_employer_country;
1206 $data['copay'] = $copay;
1207 $data['subscriber_sex'] = $subscriber_sex;
1208 $data['pid'] = $pid;
1209 $data['date'] = $effective_date;
1210 $data['accept_assignment'] = $accept_assignment;
1211 $data['policy_type'] = $policy_type;
1212 updateInsuranceData($idrow['id'], $data);
1213 return $idrow['id'];
1216 return sqlInsert("INSERT INTO insurance_data SET
1217 type = '" . add_escape_custom($type) . "',
1218 provider = '" . add_escape_custom($provider) . "',
1219 policy_number = '" . add_escape_custom($policy_number) . "',
1220 group_number = '" . add_escape_custom($group_number) . "',
1221 plan_name = '" . add_escape_custom($plan_name) . "',
1222 subscriber_lname = '" . add_escape_custom($subscriber_lname) . "',
1223 subscriber_mname = '" . add_escape_custom($subscriber_mname) . "',
1224 subscriber_fname = '" . add_escape_custom($subscriber_fname) . "',
1225 subscriber_relationship = '" . add_escape_custom($subscriber_relationship) . "',
1226 subscriber_ss = '" . add_escape_custom($subscriber_ss) . "',
1227 subscriber_DOB = '" . add_escape_custom($subscriber_DOB) . "',
1228 subscriber_street = '" . add_escape_custom($subscriber_street) . "',
1229 subscriber_postal_code = '" . add_escape_custom($subscriber_postal_code) . "',
1230 subscriber_city = '" . add_escape_custom($subscriber_city) . "',
1231 subscriber_state = '" . add_escape_custom($subscriber_state) . "',
1232 subscriber_country = '" . add_escape_custom($subscriber_country) . "',
1233 subscriber_phone = '" . add_escape_custom($subscriber_phone) . "',
1234 subscriber_employer = '" . add_escape_custom($subscriber_employer) . "',
1235 subscriber_employer_city = '" . add_escape_custom($subscriber_employer_city) . "',
1236 subscriber_employer_street = '" . add_escape_custom($subscriber_employer_street) . "',
1237 subscriber_employer_postal_code = '" . add_escape_custom($subscriber_employer_postal_code) . "',
1238 subscriber_employer_state = '" . add_escape_custom($subscriber_employer_state) . "',
1239 subscriber_employer_country = '" . add_escape_custom($subscriber_employer_country) . "',
1240 copay = '" . add_escape_custom($copay) . "',
1241 subscriber_sex = '" . add_escape_custom($subscriber_sex) . "',
1242 pid = '" . add_escape_custom($pid) . "',
1243 date = '" . add_escape_custom($effective_date) . "',
1244 accept_assignment = '" . add_escape_custom($accept_assignment) . "',
1245 policy_type = '" . add_escape_custom($policy_type) . "'
1250 // This is used internally only.
1251 function updateInsuranceData($id, $new)
1253 $fields = sqlListFields("insurance_data");
1256 while(list($key, $value) = each ($new)) {
1257 if (in_array($key, $fields)) {
1258 $use[$key] = $value;
1262 $sql = "UPDATE insurance_data SET ";
1263 while(list($key, $value) = each($use))
1264 $sql .= "`$key` = '" . add_escape_custom($value) . "', ";
1265 $sql = substr($sql, 0, -2) . " WHERE id = '" . add_escape_custom($id) . "'";
1270 function newHistoryData($pid, $new=false)
1272 $arraySqlBind = array();
1273 $sql = "insert into history_data set pid = ?, date = NOW()";
1274 array_push($arraySqlBind,$pid);
1276 while(list($key, $value) = each($new)) {
1277 array_push($arraySqlBind,$value);
1278 $sql .= ", `$key` = ?";
1281 return sqlInsert($sql, $arraySqlBind );
1284 function updateHistoryData($pid,$new)
1286 $real = getHistoryData($pid);
1287 while(list($key, $value) = each ($new))
1288 $real[$key] = $value;
1290 // need to unset date, so can reset it below
1291 unset($real['date']);
1293 $arraySqlBind = array();
1294 $sql = "insert into history_data set `date` = NOW(), ";
1295 while(list($key, $value) = each($real)) {
1296 array_push($arraySqlBind,$value);
1297 $sql .= "`$key` = ?, ";
1299 $sql = substr($sql, 0, -2);
1301 return sqlInsert($sql, $arraySqlBind );
1305 // in months if < 2 years old
1306 // in years if > 2 years old
1307 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1308 // (optional) nowYMD is a date in YYYYMMDD format
1309 function getPatientAge($dobYMD, $nowYMD=null)
1311 // strip any dashes from the DOB
1312 $dobYMD = preg_replace("/-/", "", $dobYMD);
1313 $dobDay = substr($dobYMD,6,2);
1314 $dobMonth = substr($dobYMD,4,2);
1315 $dobYear = substr($dobYMD,0,4);
1317 // set the 'now' date values
1318 if ($nowYMD == null) {
1319 $nowDay = date("d");
1320 $nowMonth = date("m");
1321 $nowYear = date("Y");
1324 $nowDay = substr($nowYMD,6,2);
1325 $nowMonth = substr($nowYMD,4,2);
1326 $nowYear = substr($nowYMD,0,4);
1329 $dayDiff = $nowDay - $dobDay;
1330 $monthDiff = $nowMonth - $dobMonth;
1331 $yearDiff = $nowYear - $dobYear;
1333 $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1335 // We want the age in FULL months, so if the current date is less than the numerical day of birth, subtract a month
1336 if($dayDiff<0) { $ageInMonths-=1; }
1338 if ( $ageInMonths > 24 ) {
1340 if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1341 else if ($monthDiff < 0) { $age -= 1; }
1344 $age = "$ageInMonths " . xl('month');
1351 * Wrapper to make sure the clinical rules dates formats corresponds to the
1352 * format expected by getPatientAgeYMD
1354 * @param string $dob date of birth
1355 * @param string $target date to calculate age on
1356 * @return array containing
1357 * age - decimal age in years
1358 * age_in_months - decimal age in months
1359 * ageinYMD - formatted string #y #m #d */
1360 function parseAgeInfo($dob,$target)
1362 // Prepare dob (expected in order Y M D, remove whatever delimiters might be there
1363 $dateDOB = preg_replace("/[-\s\/]/", "", $dob);
1365 // Prepare target (Y-M-D H:M:S)
1366 $dateTarget = preg_replace("/[-\s\/]/","",$target);
1368 return getPatientAgeYMD($dateDOB,$dateTarget);
1376 * @return array containing
1377 * age - decimal age in years
1378 * age_in_months - decimal age in months
1379 * ageinYMD - formatted string #y #m #d
1381 function getPatientAgeYMD($dob, $date=null)
1384 if ($date == null) {
1385 $daynow = date("d");
1386 $monthnow = date("m");
1387 $yearnow = date("Y");
1388 $datenow=$yearnow.$monthnow.$daynow;
1391 $datenow=preg_replace("/-/", "", $date);
1392 $yearnow=substr($datenow,0,4);
1393 $monthnow=substr($datenow,4,2);
1394 $daynow=substr($datenow,6,2);
1395 $datenow=$yearnow.$monthnow.$daynow;
1398 $dob=preg_replace("/-/", "", $dob);
1399 $dobyear=substr($dob,0,4);
1400 $dobmonth=substr($dob,4,2);
1401 $dobday=substr($dob,6,2);
1402 $dob=$dobyear.$dobmonth.$dobday;
1404 //to compensate for 30, 31, 28, 29 days/month
1405 $mo=$monthnow; //to avoid confusion with later calculation
1407 if ($mo==05 or $mo==07 or $mo==10 or $mo==12) { //determined by monthnow-1
1408 $nd=30; //nd = number of days in a month, if monthnow is 5, 7, 9, 12 then
1409 } // look at April, June, September, November for calculation. These months only have 30 days.
1410 elseif ($mo==03) { // for march, look to the month of February for calculation, check for leap year
1411 $check_leap_Y=$yearnow/4; // To check if this is a leap year.
1412 if (is_int($check_leap_Y)) {$nd=29;} //If it true then this is the leap year
1413 else {$nd=28;} //otherwise, it is not a leap year.
1415 else {$nd=31;} // other months have 31 days
1417 $bdthisyear=$yearnow.$dobmonth.$dobday; //Date current year's birthday falls on
1418 if ($datenow < $bdthisyear) // if patient hasn't had birthday yet this year
1420 $age_year = $yearnow - $dobyear - 1;
1421 if ($daynow < $dobday) {
1422 $months_since_birthday=12 - $dobmonth + $monthnow - 1;
1423 $days_since_dobday=$nd - $dobday + $daynow; //did not take into account for month with 31 days
1426 $months_since_birthday=12 - $dobmonth + $monthnow;
1427 $days_since_dobday=$daynow - $dobday;
1430 else // if patient has had birthday this calandar year
1432 $age_year = $yearnow - $dobyear;
1433 if ($daynow < $dobday) {
1434 $months_since_birthday=$monthnow - $dobmonth -1;
1435 $days_since_dobday=$nd - $dobday + $daynow;
1438 $months_since_birthday=$monthnow - $dobmonth;
1439 $days_since_dobday=$daynow - $dobday;
1443 $day_as_month_decimal = $days_since_dobday / 30;
1444 $months_since_birthday_float = $months_since_birthday + $day_as_month_decimal;
1445 $month_as_year_decimal = $months_since_birthday_float / 12;
1446 $age_float = $age_year + $month_as_year_decimal;
1448 $age_in_months = $age_year * 12 + $months_since_birthday_float;
1449 $age_in_months = round($age_in_months,2); //round the months to xx.xx 2 floating points
1450 $age = round($age_float,2);
1452 // round the years to 2 floating points
1453 $ageinYMD = $age_year."y ".$months_since_birthday."m ".$days_since_dobday."d";
1454 return compact('age','age_in_months','ageinYMD');
1457 // Returns Age in days
1458 // in months if < 2 years old
1459 // in years if > 2 years old
1460 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1461 // (optional) nowYMD is a date in YYYYMMDD format
1462 function getPatientAgeInDays($dobYMD, $nowYMD=null)
1466 // strip any dashes from the DOB
1467 $dobYMD = preg_replace("/-/", "", $dobYMD);
1468 $dobDay = substr($dobYMD,6,2);
1469 $dobMonth = substr($dobYMD,4,2);
1470 $dobYear = substr($dobYMD,0,4);
1472 // set the 'now' date values
1473 if ($nowYMD == null) {
1474 $nowDay = date("d");
1475 $nowMonth = date("m");
1476 $nowYear = date("Y");
1479 $nowDay = substr($nowYMD,6,2);
1480 $nowMonth = substr($nowYMD,4,2);
1481 $nowYear = substr($nowYMD,0,4);
1485 $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1486 $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1487 $timediff = $nowtime - $dobtime;
1488 $age = $timediff / 86400; // 24 hours * 3600 seconds/hour = 86400 seconds
1493 * Returns a string to be used to display a patient's age
1495 * @param type $dobYMD
1496 * @param type $asOfYMD
1497 * @return string suitable for displaying patient's age based on preferences
1499 function getPatientAgeDisplay($dobYMD, $asOfYMD=null)
1501 if($GLOBALS['age_display_format']=='1')
1503 $ageYMD=getPatientAgeYMD($dobYMD,$asOfYMD);
1504 if(isset($GLOBALS['age_display_limit']) && $ageYMD['age']<=$GLOBALS['age_display_limit'])
1506 return $ageYMD['ageinYMD'];
1510 return getPatientAge($dobYMD, $asOfYMD);
1515 return getPatientAge($dobYMD, $asOfYMD);
1519 function dateToDB($date)
1521 $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1526 // ----------------------------------------------------------------------------
1528 * DROPDOWN FOR COUNTRIES
1530 * build a dropdown with all countries from geo_country_reference
1532 * @param int $selected - id for selected record
1533 * @param string $name - the name/id for select form
1534 * @return void - just echo the html encoded string
1536 function dropdown_countries($selected = 0, $name = 'country_code')
1538 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1540 $string = "<select name='$name' id='$name'>";
1541 while ( $row = sqlFetchArray($r) ) {
1542 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1543 $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1546 $string .= '</select>';
1551 // ----------------------------------------------------------------------------
1553 * DROPDOWN FOR YES/NO
1555 * build a dropdown with two options (yes - 1, no - 0)
1557 * @param int $selected - id for selected record
1558 * @param string $name - the name/id for select form
1559 * @return void - just echo the html encoded string
1561 function dropdown_yesno($selected = 0, $name = 'yesno')
1563 $string = "<select name='$name' id='$name'>";
1565 $selected = (int)$selected;
1566 if ( $selected == 0) { $sel1 = 'selected="selected"';
1568 else { $sel2 = 'selected="selected"';
1571 $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1572 $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1573 $string .= '</select>';
1578 // ----------------------------------------------------------------------------
1580 * DROPDOWN FOR MALE/FEMALE options
1582 * build a dropdown with three options (unselected/male/female)
1584 * @param int $selected - id for selected record
1585 * @param string $name - the name/id for select form
1586 * @return void - just echo the html encoded string
1588 function dropdown_sex($selected = 0, $name = 'sex')
1590 $string = "<select name='$name' id='$name'>";
1592 if ( $selected == 1) { $sel1 = 'selected="selected"';
1595 else if ($selected == 2) { $sel2 = 'selected="selected"';
1598 else { $sel0 = 'selected="selected"';
1602 $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1603 $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1604 $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1605 $string .= '</select>';
1610 // ----------------------------------------------------------------------------
1612 * DROPDOWN FOR MARITAL STATUS
1614 * build a dropdown with marital status
1616 * @param int $selected - id for selected record
1617 * @param string $name - the name/id for select form
1618 * @return void - just echo the html encoded string
1620 function dropdown_marital($selected = 0, $name = 'status')
1622 $string = "<select name='$name' id='$name'>";
1624 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1626 foreach ( $statii as $st ) {
1627 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1628 $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1631 $string .= '</select>';
1636 // ----------------------------------------------------------------------------
1638 * DROPDOWN FOR PROVIDERS
1640 * build a dropdown with all providers
1642 * @param int $selected - id for selected record
1643 * @param string $name - the name/id for select form
1644 * @return void - just echo the html encoded string
1646 function dropdown_providers($selected = 0, $name = 'status')
1648 $provideri = getProviderInfo();
1650 $string = "<select name='$name' id='$name'>";
1651 $string .= '<option value="">' .xl('Unassigned'). '</option>';
1652 foreach ( $provideri as $s ) {
1653 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1654 $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1657 $string .= '</select>';
1662 // ----------------------------------------------------------------------------
1664 * DROPDOWN FOR INSURANCE COMPANIES
1666 * build a dropdown with all insurers
1668 * @param int $selected - id for selected record
1669 * @param string $name - the name/id for select form
1670 * @return void - just echo the html encoded string
1672 function dropdown_insurance($selected = 0, $name = 'iprovider')
1674 $insurancei = getInsuranceProviders();
1676 $string = "<select name='$name' id='$name'>";
1677 $string .= '<option value="0">Onbekend</option>';
1678 foreach ( $insurancei as $iid => $iname ) {
1679 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1680 $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1683 $string .= '</select>';
1689 // ----------------------------------------------------------------------------
1693 * return the name or the country code, function of arguments
1695 * @param int $country_code
1696 * @param string $country_name
1697 * @return string | int - name or code
1699 function country_code($country_code = 0, $country_name = '')
1702 if ( $country_code ) {
1703 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1705 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1708 $db = $GLOBALS['adodb']['db'];
1709 $result = $db->Execute($sql);
1710 if ($result && !$result->EOF) {
1711 $strint = $result->fields['res'];
1717 function DBToDate($date)
1719 $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1724 * Get up to 3 insurances (primary, secondary, tertiary) that are effective
1725 * for the given patient on the given date.
1727 * @param int The PID of the patient.
1728 * @param string Date in yyyy-mm-dd format.
1729 * @return array Array of 0-3 insurance_data rows.
1731 function getEffectiveInsurances($patient_id, $encdate)
1734 foreach (array('primary','secondary','tertiary') as $instype) {
1735 $tmp = sqlQuery("SELECT * FROM insurance_data " .
1736 "WHERE pid = ? AND type = ? " .
1737 "AND date <= ? ORDER BY date DESC LIMIT 1",
1738 array($patient_id, $instype, $encdate));
1739 if (empty($tmp['provider'])) break;
1746 * Get the patient's balance due. Normally this excludes amounts that are out
1747 * to insurance. If you want to include what insurance owes, set the second
1748 * parameter to true.
1750 * @param int The PID of the patient.
1751 * @param boolean Indicates if amounts owed by insurance are to be included.
1752 * @return number The balance.
1754 function get_patient_balance($pid, $with_insurance=false)
1757 $feres = sqlStatement("SELECT date, encounter, last_level_billed, " .
1758 "last_level_closed, stmt_count " .
1759 "FROM form_encounter WHERE pid = ?", array($pid));
1760 while ($ferow = sqlFetchArray($feres)) {
1761 $encounter = $ferow['encounter'];
1762 $dos = substr($ferow['date'], 0, 10);
1763 $insarr = getEffectiveInsurances($pid, $dos);
1764 $inscount = count($insarr);
1765 if (!$with_insurance && $ferow['last_level_closed'] < $inscount && $ferow['stmt_count'] == 0) {
1766 // It's out to insurance so only the co-pay might be due.
1767 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1768 "pid = ? AND encounter = ? AND " .
1769 "code_type = 'copay' AND activity = 1",
1770 array($pid, $encounter));
1771 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments " .
1772 "FROM ar_activity WHERE " .
1773 "pid = ? AND encounter = ? AND payer_type = 0",
1774 array($pid, $encounter));
1775 $ptbal = $insarr[0]['copay'] + $brow['amount'] - $drow['payments'];
1776 if ($ptbal > 0) $balance += $ptbal;
1779 // Including insurance or not out to insurance, everything is due.
1780 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1781 "pid = ? AND encounter = ? AND " .
1782 "activity = 1", array($pid, $encounter));
1783 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1784 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1785 "pid = ? AND encounter = ?", array($pid, $encounter));
1786 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1787 "pid = ? AND encounter = ?", array($pid, $encounter));
1788 $balance += $brow['amount'] + $srow['amount']
1789 - $drow['payments'] - $drow['adjustments'];
1792 return sprintf('%01.2f', $balance);
1795 // Function to check if patient is deceased.
1797 // $pid - patient id
1798 // $date - date checking if deceased (will default to current date if blank)
1800 // If deceased, then will return the number of
1801 // days that patient has been deceased.
1802 // If not deceased, then will return false.
1803 function is_patient_deceased($pid,$date='')
1806 // Set date to current if not set
1807 $date = (!empty($date)) ? $date : date('Y-m-d H:i:s');
1809 // Query for deceased status (gets days deceased if patient is deceased)
1810 $results = sqlQuery("SELECT DATEDIFF(?,`deceased_date`) as `days_deceased` " .
1811 "FROM `patient_data` " .
1812 "WHERE `pid` = ? AND `deceased_date` IS NOT NULL AND `deceased_date` != '0000-00-00 00:00:00' AND `deceased_date` <= ?", array($date,$pid,$date) );
1814 if (empty($results)) {
1815 // Patient is alive, so return false
1819 // Patient is dead, so return the number of days patient has been deceased.
1820 // Don't let it be zero days or else will confuse calls to this function.
1821 if ($results['days_deceased'] === 0) {
1822 $results['days_deceased'] = 1;
1824 return $results['days_deceased'];