forked from LibreHealthIO/lh-ehr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpatient.inc
1904 lines (1701 loc) · 67.4 KB
/
patient.inc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* patient.inc
*
* This program patient.inc includes functions for manipulating patient information.
*
* @copyright Copyright (C) 2016 Terry Hill <[email protected]>
* No previous copyright information. This is an original OpenEMR program.
*
*
* LICENSE: This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://opensource.org/licenses/gpl-license.php.
*
* LICENSE: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* See the Mozilla Public License for more details.
* If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* @package LibreHealth EHR
* @author
* @link http://librehealth.io
*
* Please help the overall project by sending changes you make to the author and to the LibreEHR community.
*
*/
require_once("{$GLOBALS['srcdir']}/sql.inc");
require_once("{$GLOBALS['srcdir']}/formdata.inc.php");
// Hard-coding this array because its values and meanings are fixed by the 837p
// standard and we don't want people messing with them.
$policy_types = array(
'' => xl('N/A'),
'12' => xl('Working Aged Beneficiary or Spouse with Employer Group Health Plan'),
'13' => xl('End-Stage Renal Disease Beneficiary in MCP with Employer`s Group Plan'),
'14' => xl('No-fault Insurance including Auto is Primary'),
'15' => xl('Worker`s Compensation'),
'16' => xl('Public Health Service (PHS) or Other Federal Agency'),
'41' => xl('Black Lung'),
'42' => xl('Veteran`s Administration'),
'43' => xl('Disabled Beneficiary Under Age 65 with Large Group Health Plan (LGHP)'),
'47' => xl('Other Liability Insurance is Primary'),
);
/**
* Get a patient's demographic data.
*
* @param int $pid The PID of the patient
* @param string $given an optional subsection of the patient's demographic
* data to retrieve.
* @return array The requested subsection of a patient's demographic data.
* If no subsection was given, returns everything, with the
* date of birth as the last field.
*/
function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS") {
$sql = "select $given from patient_data where pid=? order by date DESC limit 0,1";
return sqlQuery($sql, array($pid) );
}
function getLanguages() {
$returnval = array('','english');
$sql = "select distinct lower(language) as language from patient_data";
$rez = sqlStatement($sql);
for($iter=0; $row=sqlFetchArray($rez); $iter++) {
if (($row["language"] != "english") && ($row["language"] != "")) {
array_push($returnval, $row["language"]);
}
}
return $returnval;
}
function getInsuranceProvider($ins_id) {
$sql = "select name from insurance_companies where id=?";
$row = sqlQuery($sql,array($ins_id));
return $row['name'];
}
function getInsuranceProviders() {
$returnval = array();
if (true) {
$sql = "select name, id from insurance_companies order by name, id";
$rez = sqlStatement($sql);
for($iter=0; $row=sqlFetchArray($rez); $iter++) {
$returnval[$row['id']] = $row['name'];
}
}
// Please leave this here. I have a user who wants to see zip codes and PO
// box numbers listed along with the insurance company names, as many companies
// have different billing addresses for different plans. -- Rod Roark
//
else {
$sql = "select insurance_companies.name, insurance_companies.id, " .
"addresses.zip, addresses.line1 " .
"from insurance_companies, addresses " .
"where addresses.foreign_id = insurance_companies.id " .
"order by insurance_companies.name, addresses.zip";
$rez = sqlStatement($sql);
for($iter=0; $row=sqlFetchArray($rez); $iter++) {
preg_match("/\d+/", $row['line1'], $matches);
$returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
"," . $matches[0] . ")";
}
}
return $returnval;
}
function getInsuranceProvidersExtra() {
$returnval = array();
// added a global control to allow additional address information for insurance companies
$sql = "select insurance_companies.name, insurance_companies.id, " .
"addresses.zip, addresses.line1, addresses.state " .
"from insurance_companies, addresses " .
"where addresses.foreign_id = insurance_companies.id " .
"order by insurance_companies.name, addresses.zip";
$rez = sqlStatement($sql);
for($iter=0; $row=sqlFetchArray($rez); $iter++) {
switch ($GLOBALS['insurance_information']) {
case $GLOBALS['insurance_information'] = '0':
$returnval[$row['id']] = $row['name'];
break;
case $GLOBALS['insurance_information'] = '1':
$returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . ")";
break;
case $GLOBALS['insurance_information'] = '2':
$returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['zip'] . ")";
break;
case $GLOBALS['insurance_information'] = '3':
$returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['state'] . ")";
break;
case $GLOBALS['insurance_information'] = '4':
$returnval[$row['id']] = $row['name'] . " (" . $row['line1'] . "," . $row['state'] .
"," . $row['zip'] . ")";
break;
case $GLOBALS['insurance_information'] = '5':
preg_match("/\d+/", $row['line1'], $matches);
$returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
"," . $matches[0] . ")";
break;
}
}
return $returnval;
}
function getProviders() {
$returnval = array("");
$sql = "select fname, lname, suffix from users where authorized = 1 and " .
"active = 1 and username != ''";
$rez = sqlStatement($sql);
for($iter=0; $row=sqlFetchArray($rez); $iter++) {
if (($row["fname"] != "") && ($row["lname"] != "")) {
array_push($returnval, $row["fname"] . " " . $row["lname"]);
}
}
return $returnval;
}
// ----------------------------------------------------------------------------
// Get one facility row. If the ID is not specified, then get either the
// "main" (billing) facility, or the default facility of the currently
// logged-in user. This was created to support genFacilityTitle() but
// may find additional uses.
//
function getFacility($facid=0) {
//create a sql binding array
$sqlBindArray = array();
if ($facid > 0) {
$query = "SELECT * FROM facility WHERE id = ?";
array_push($sqlBindArray,$facid);
}
else if ($facid == 0) {
$query = "SELECT * FROM facility ORDER BY " .
"billing_location DESC, service_location, id LIMIT 1";
}
else {
$query = "SELECT facility.* FROM users, facility WHERE " .
"users.id = ? AND " .
"facility.id = users.facility_id";
array_push($sqlBindArray,$_SESSION['authUserID']);
}
return sqlQuery($query,$sqlBindArray);
}
// Generate a report title including report name and facility name, address
// and phone.
//
function genFacilityTitle($repname='', $facid=0) {
$s = '';
$s .= "<table class='ftitletable'>\n";
$s .= " <tr>\n";
$s .= " <td class='ftitlecell1'>$repname</td>\n";
$s .= " <td class='ftitlecell2'>\n";
$r = getFacility($facid);
if (!empty($r)) {
$s .= "<b>" . htmlspecialchars( $r['name'], ENT_NOQUOTES) . "</b>\n";
if ($r['street']) $s .= "<br />" . htmlspecialchars( $r['street'], ENT_NOQUOTES) . "\n";
if ($r['city'] || $r['state'] || $r['postal_code']) {
$s .= "<br />";
if ($r['city']) $s .= htmlspecialchars( $r['city'], ENT_NOQUOTES);
if ($r['state']) {
if ($r['city']) $s .= ", \n";
$s .= htmlspecialchars( $r['state'], ENT_NOQUOTES);
}
if ($r['postal_code']) $s .= " " . htmlspecialchars( $r['postal_code'], ENT_NOQUOTES);
$s .= "\n";
}
if ($r['country_code']) $s .= "<br />" . htmlspecialchars( $r['country_code'], ENT_NOQUOTES) . "\n";
if (preg_match('/[1-9]/', $r['phone'])) $s .= "<br />" . htmlspecialchars( $r['phone'], ENT_NOQUOTES) . "\n";
}
$s .= " </td>\n";
$s .= " </tr>\n";
$s .= "</table>\n";
return $s;
}
/**
GET FACILITIES
returns all facilities or just the id for the first one
(FACILITY FILTERING (lemonsoftware))
@param string - if 'first' return first facility ordered by id
@return array | int for 'first' case
*/
function getFacilities($first = '') {
$r = sqlStatement("SELECT * FROM facility ORDER BY id");
$ret = array();
while ( $row = sqlFetchArray($r) ) {
$ret[] = $row;
}
if ( $first == 'first') {
return $ret[0]['id'];
} else {
return $ret;
}
}
/**
GET SERVICE FACILITIES
returns all service_location facilities or just the id for the first one
(FACILITY FILTERING (CHEMED))
@param string - if 'first' return first facility ordered by id
@return array | int for 'first' case
*/
function getServiceFacilities($first = '') {
$r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
$ret = array();
while ( $row = sqlFetchArray($r) ) {
$ret[] = $row;
}
if ( $first == 'first') {
return $ret[0]['id'];
} else {
return $ret;
}
}
//(CHEMED) facility filter
function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
$param1 = "";
if ($providers_only === 'any') {
$param1 = " AND authorized = 1 AND active = 1 ";
}
else if ($providers_only) {
$param1 = " AND authorized = 1 AND calendar = 1 ";
}
//--------------------------------
//(CHEMED) facility filter
$param2 = "";
if ($facility) {
if ($GLOBALS['restrict_user_facility']) {
$param2 = " AND (facility_id = $facility
OR $facility IN
(select facility_id
from users_facility
where tablename = 'users'
and table_id = id)
)
";
}
else {
$param2 = " AND facility_id = $facility ";
}
}
//--------------------------------
$command = "=";
if ($providerID == "%") {
$command = "like";
}
$query = "select distinct id, username, lname, fname, authorized, info, facility, suffix " .
"from users where username != '' and active = 1 and id $command '" .
add_escape_custom($providerID) . "' " . $param1 . $param2;
// sort by last name -- JRM June 2008
$query .= " ORDER BY lname, fname ";
$rez = sqlStatement($query);
for($iter=0; $row=sqlFetchArray($rez); $iter++)
$returnval[$iter]=$row;
//if only one result returned take the key/value pairs in array [0] and merge them down into
// the base array so that $resultval[0]['key'] is also accessible from $resultval['key']
if($iter==1) {
$akeys = array_keys($returnval[0]);
foreach($akeys as $key) {
$returnval[0][$key] = $returnval[0][$key];
}
}
return $returnval;
}
//same as above but does not reduce if only 1 row returned
function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
$param1 = "";
if ($providers_only) {
$param1 = "AND authorized=1";
}
$command = "=";
if ($providerID == "%") {
$command = "like";
}
$query = "select distinct id, username, lname, fname, authorized, info, facility " .
"from users where active = 1 and username != '' and id $command '" .
add_escape_custom($providerID) . "' " . $param1;
$rez = sqlStatement($query);
for($iter=0; $row=sqlFetchArray($rez); $iter++)
$returnval[$iter]=$row;
return $returnval;
}
function getProviderName($providerID) {
$pi = getProviderInfo($providerID, 'any');
if (strlen($pi[0]["lname"]) > 0) {
if (strlen($pi[0]["suffix"]) > 0) $pi[0]["lname"] .= ", ".$pi[0]["suffix"];
return $pi[0]['fname'] . " " . $pi[0]['lname'];
}
return "";
}
function getProviderId($providerName) {
$query = "select id from users where username = ?";
$rez = sqlStatement($query, array($providerName) );
for($iter=0; $row=sqlFetchArray($rez); $iter++)
$returnval[$iter]=$row;
return $returnval;
}
function getEthnoRacials() {
$returnval = array("");
$sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
$rez = sqlStatement($sql);
for($iter=0; $row=sqlFetchArray($rez); $iter++) {
if (($row["ethnoracial"] != "")) {
array_push($returnval, $row["ethnoracial"]);
}
}
return $returnval;
}
function getHistoryData($pid, $given = "*", $dateStart='',$dateEnd='')
{
if ($dateStart && $dateEnd) {
$res = sqlQuery("select $given from history_data where pid = ? and date >= ? and date <= ? order by date DESC limit 0,1", array($pid,$dateStart,$dateEnd) );
}
else if ($dateStart && !$dateEnd) {
$res = sqlQuery("select $given from history_data where pid = ? and date >= ? order by date DESC limit 0,1", array($pid,$dateStart) );
}
else if (!$dateStart && $dateEnd) {
$res = sqlQuery("select $given from history_data where pid = ? and date <= ? order by date DESC limit 0,1", array($pid,$dateEnd) );
}
else {
$res = sqlQuery("select $given from history_data where pid=? order by date DESC limit 0,1", array($pid) );
}
if($given == 'tobacco'){
$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));
}
return $res;
}
// function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
{
$sql = "select $given from insurance_data as insd " .
"left join insurance_companies as ic on ic.id = insd.provider " .
"where pid = ? and type = ? order by date DESC limit 1";
return sqlQuery($sql, array($pid, $type) );
}
function getInsuranceDataInfo(){
$insurances = array();
$sql = "select insd.id insurance_id,insd.*,ic.* from insurance_data as insd left join insurance_companies as ic on ic.id = insd.provider where pid = ? order by type ASC,inactive DESC, date DESC";
$insurance = sqlStatement($sql,array($_SESSION['pid']));
while($ins = sqlFetchArray($insurance)){
$insurances[] = $ins;
}
return $insurances;
}
function getActiveInsuranceData(){
$sql = "select insd.id insurance_id,insd.*,ic.* from insurance_data as insd left join insurance_companies as ic on ic.id = insd.provider where pid = ? and inactive=0 order by type ASC, date DESC";
$insurance_types = array("primary","secondary","tertiary");
$current_insurance_types = array();
$total_available_insurances = array();
$insurance = sqlStatement($sql,array($_SESSION['pid']));
while($ins = sqlFetchArray($insurance)){
$insurances[] = $ins;
$current_insurance_types[] = $ins['type'];
}
$unavailable = array_diff($insurance_types,$current_insurance_types);
for($i=0,$j=0;$i<3;$i++){
if(isset($unavailable[$i])){
$total_available_insurances[] = array();
}
else{
$total_available_insurances[] = $insurances[$j];
$j++;
}
}
return $total_available_insurances;
}
function getInactiveInsuranceData(){
$sql = "select insd.id insurance_id,insd.*,ic.* from insurance_data as insd left join insurance_companies as ic on ic.id = insd.provider where pid = ? and inactive=1 order by type ASC, date DESC";
$insurance = sqlStatement($sql,array($_SESSION['pid']));
while($ins = sqlFetchArray($insurance)){
$insurances[] = $ins;
}
return $insurances;
}
function getInsuranceDataByDate($pid, $date, $type,
$given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
{ // this must take the date in the following manner: YYYY-MM-DD
// this function recalls the insurance value that was most recently enterred from the
// given date. it will call up most recent records up to and on the date given,
// but not records enterred after the given date
$sql = "select $given from insurance_data as insd " .
"left join insurance_companies as ic on ic.id = provider " .
"where pid = ? and date_format(date,'%Y-%m-%d') <= ? and " .
"type=? order by date DESC limit 1";
return sqlQuery($sql, array($pid,$date,$type) );
}
function getEmployerData($pid, $given = "*")
{
$sql = "select $given from employer_data where pid=? order by date DESC limit 0,1";
return sqlQuery($sql, array($pid) );
}
function _set_patient_inc_count($limit, $count, $where, $whereBindArray=array()) {
// When the limit is exceeded, find out what the unlimited count would be.
$GLOBALS['PATIENT_INC_COUNT'] = $count;
// if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
if ($limit != "all") {
$tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where", $whereBindArray);
$GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
}
}
/**
* Allow the last name to be followed by a comma and some part of a first name(can
* also place middle name after the first name with a space separating them)
* Allows comma alone followed by some part of a first name(can also place middle name
* after the first name with a space separating them).
* Allows comma alone preceded by some part of a last name.
* If no comma or space, then will search both last name and first name.
* If the first letter of either name is capital, searches for name starting
* with given substring (the expected behavior). If it is lower case, it
* searches for the substring anywhere in the name. This applies to either
* last name, first name, and middle name.
* Also allows first name followed by middle and/or last name when separated by spaces.
* @param string $term
* @param string $given
* @param string $orderby
* @param string $limit
* @param string $start
* @return array
*/
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")
{
$names = getPatientNameSplit($term);
foreach ($names as $key => $val) {
if (!empty($val)) {
if ((strlen($val) > 1) && ($names[$key][0] != strtoupper($names[$key][0]))) {
$names[$key] = '%' . $val . '%';
} else {
$names[$key] = $val . '%';
}
}
}
// Debugging section below
//if(array_key_exists('first',$names)) {
// error_log("first name search term :".$names['first']);
//}
//if(array_key_exists('middle',$names)) {
// error_log("middle name search term :".$names['middle']);
//}
//if(array_key_exists('last',$names)) {
// error_log("last name search term :".$names['last']);
//}
// Debugging section above
$where = " ( ";
$sqlBindArray = array();
if(array_key_exists('last',$names) && $names['last'] == '') {
// Do not search last name
$where .= "fname LIKE ? ";
array_push($sqlBindArray, $names['first']);
if ($names['middle'] != '') {
$where .= "AND mname LIKE ? ";
array_push($sqlBindArray, $names['middle']);
}
} elseif(array_key_exists('first',$names) && $names['first'] == '') {
// Do not search first name or middle name
$where .= "lname LIKE ? ";
array_push($sqlBindArray, $names['last']);
} elseif($names['first'] == '' && $names['last'] != '') {
// Search both first name and last name with same term
$names['first'] = $names['last'];
$where .= "lname LIKE ? OR fname LIKE ? ";
array_push($sqlBindArray, $names['last'], $names['first']);
} elseif ($names['middle'] != '') {
$where .= "lname LIKE ? AND fname LIKE ? AND mname LIKE ? ";
array_push($sqlBindArray, $names['last'], $names['first'], $names['middle']);
} else {
$where .= "lname LIKE ? AND fname LIKE ? ";
array_push($sqlBindArray, $names['last'], $names['first']);
}
$where .= " ) ";
if (!empty($GLOBALS['pt_restrict_field'])) {
if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
$where .= " AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
" = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
array_push($sqlBindArray, $_SESSION{"authUser"});
}
}
$patient_filter = do_action( 'filter_patient_select', $_SESSION['authUser'] );
if ( $patient_filter ) {
$where .= " AND ".$patient_filter;
}
$sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
if ($limit != "all") $sql .= " LIMIT $start, $limit";
$rez = sqlStatement($sql, $sqlBindArray);
$returnval=array();
for($iter=0; $row=sqlFetchArray($rez); $iter++)
$returnval[$iter] = $row;
_set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
return $returnval;
}
/**
* Accept a string used by a search function expected to find a patient name,
* then split up the string if a comma or space exists. Return an array having
* from 1 to 3 elements, named first, middle, and last.
* See above getPatientLnames() function for details on how the splitting occurs.
* @param string $term
* @return array
*/
function getPatientNameSplit($term) {
$term = trim($term);
if (strpos($term, ',') !== false) {
$names = explode(',', $term);
$n['last'] = $names[0];
if (strpos(trim($names[1]), ' ') !== false) {
list($n['first'], $n['middle']) = explode(' ', trim($names[1]));
} else {
$n['first'] = $names[1];
}
} elseif (strpos($term, ' ') !== false) {
$names = explode(' ', $term);
if (count($names) == 1) {
$n['last'] = $names[0];
} elseif (count($names) == 3) {
$n['first'] = $names[0];
$n['middle'] = $names[1];
$n['last'] = $names[2];
} else {
// This will handle first and last name or first followed by
// multiple names only using just the last of the names in the list.
$n['first'] = $names[0];
$n['last'] = end($names);
}
} else {
$n['last'] = $term;
}
// Trim whitespace off the names before returning
foreach($n as $key => $val) {
$n[$key] = trim($val);
}
return $n; // associative array containing names
}
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")
{
$sqlBindArray = array();
$where = "pid LIKE ? ";
$patient_filter = do_action( 'filter_patient_select', $_SESSION['authUser'] );
if ( $patient_filter ) {
$where .= " AND ".$patient_filter;
}
array_push($sqlBindArray, $pid."%");
if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
$where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
" = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
array_push($sqlBindArray, $_SESSION{"authUser"});
}
}
$sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
if ($limit != "all") $sql .= " limit $start, $limit";
$rez = sqlStatement($sql, $sqlBindArray);
for($iter=0; $row=sqlFetchArray($rez); $iter++)
$returnval[$iter]=$row;
_set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
return $returnval;
}
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")
{
$layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like (? ) AND uor !=0", array("%".Employer."%") );
$sqlBindArray = array();
$where = " ( ";
for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
if ( $iter > 0 ) {
$where .= " or ";
}
$where .= " ".add_escape_custom($row["field_id"])." like ? ";
array_push($sqlBindArray, "%".$searchTerm."%");
}
$where .= " ) ";
$patient_filter = do_action( 'filter_patient_select', $_SESSION['authUser'] );
if ( $patient_filter ) {
$where .= " AND ".$patient_filter;
}
$sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
if ($limit != "all") $sql .= " limit $start, $limit";
$rez = sqlStatement($sql, $sqlBindArray);
for($iter=0; $row=sqlFetchArray($rez); $iter++)
$returnval[$iter]=$row;
_set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
return $returnval;
}
function getByPatientDemographicsFilter($searchFields, $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", $search_service_code='')
{
$layoutCols = explode( '~', $searchFields );
$sqlBindArray = array();
$where = "";
$i = 0;
foreach ($layoutCols as $val) {
if (empty($val)) continue;
if ( $i > 0 ) {
$where .= " or ";
}
if ($val == 'pid') {
$where .= " ".add_escape_custom($val)." = ? ";
array_push($sqlBindArray, $searchTerm);
}
else {
$where .= " ".add_escape_custom($val)." like ? ";
array_push($sqlBindArray, $searchTerm."%");
}
$i++;
}
$patient_filter = do_action( 'filter_patient_select', $_SESSION['authUser'] );
if ( $patient_filter ) {
$where .= " AND ".$patient_filter;
}
// If no search terms, ensure valid syntax.
if ($i == 0) $where = "1 = 1";
// If a non-empty service code was given, then restrict to patients who
// have been provided that service. Since the code is used in a LIKE
// clause, % and _ wildcards are supported.
if ($search_service_code) {
$where = "( $where ) AND " .
"( SELECT COUNT(*) FROM billing AS b WHERE " .
"b.pid = patient_data.pid AND " .
"b.activity = 1 AND " .
"b.code_type != 'COPAY' AND " .
"b.code LIKE ? " .
") > 0";
array_push($sqlBindArray, $search_service_code);
}
$sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
if ($limit != "all") $sql .= " limit $start, $limit";
$rez = sqlStatement($sql, $sqlBindArray);
for($iter=0; $row=sqlFetchArray($rez); $iter++)
$returnval[$iter]=$row;
_set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
return $returnval;
}
// return a collection of Patient PIDs
// new arg style by JRM March 2008
// 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")
function getPatientPID($args)
{
$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";
// alter default values if defined in the passed in args
if (isset($args['pid'])) { $pid = $args['pid']; }
if (isset($args['given'])) { $given = $args['given']; }
if (isset($args['orderby'])) { $orderby = $args['orderby']; }
if (isset($args['limit'])) { $limit = $args['limit']; }
if (isset($args['start'])) { $start = $args['start']; }
$command = "=";
if ($pid == -1) $pid = "%";
elseif (empty($pid)) $pid = "NULL";
if (strstr($pid,"%")) $command = "like";
$filter = "";
$patient_filter = do_action( 'filter_patient_select', $_SESSION['authUser'] );
if ( $patient_filter ) {
$filter = " AND ".$patient_filter;
}
$sql="select $given from patient_data where pid $command '$pid' $filter order by $orderby";
if ($limit != "all") $sql .= " limit $start, $limit";
$rez = sqlStatement($sql);
for($iter=0; $row=sqlFetchArray($rez); $iter++)
$returnval[$iter]=$row;
return $returnval;
}
/* return a patient's name in the format LAST, FIRST */
function getPatientName($pid) {
if (empty($pid)) return "";
$patientData = getPatientPID(array("pid"=>$pid));
if (empty($patientData[0]['lname'])) return "";
$patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
return $patientName;
}
/* find patient data by DOB */
function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
{
$DOB = fixDate($DOB, $DOB);
$sqlBindArray = array();
$where = "DOB like ? ";
array_push($sqlBindArray, $DOB."%");
if (!empty($GLOBALS['pt_restrict_field'])) {
if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
$where .= "AND ( patient_data." . add_escape_custom($GLOBALS['pt_restrict_field']) .
" = ( SELECT facility_id FROM users WHERE username = ?) OR patient_data." .
add_escape_custom($GLOBALS['pt_restrict_field']) . " = '' ) ";
array_push($sqlBindArray, $_SESSION{"authUser"});
}
}
$patient_filter = do_action( 'filter_patient_select', $_SESSION['authUser'] );
if ( $patient_filter ) {
$where .= " AND ".$patient_filter;
}
$sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
if ($limit != "all") $sql .= " LIMIT $start, $limit";
$rez = sqlStatement($sql, $sqlBindArray);
for($iter=0; $row=sqlFetchArray($rez); $iter++)
$returnval[$iter]=$row;
_set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
return $returnval;
}
/* find patient data by SSN */
function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
{
$sqlBindArray = array();
$where = "ss LIKE ?";
$patient_filter = do_action( 'filter_patient_select', $_SESSION['authUser'] );
if ( $patient_filter ) {
$where .= " AND ".$patient_filter;
}
array_push($sqlBindArray, $ss."%");
$sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
if ($limit != "all") $sql .= " LIMIT $start, $limit";
$rez = sqlStatement($sql, $sqlBindArray);
for($iter=0; $row=sqlFetchArray($rez); $iter++)
$returnval[$iter]=$row;
_set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
return $returnval;
}
//(CHEMED) Search by phone number
function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
{
$phone = preg_replace( "/[[:punct:]]/","", $phone );
$sqlBindArray = array();
$where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP ?";
$patient_filter = do_action( 'filter_patient_select', $_SESSION['authUser'] );
if ( $patient_filter ) {
$where .= " AND ".$patient_filter;
}
array_push($sqlBindArray, $phone);
$sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
if ($limit != "all") $sql .= " LIMIT $start, $limit";
$rez = sqlStatement($sql, $sqlBindArray);
for($iter=0; $row=sqlFetchArray($rez); $iter++)
$returnval[$iter]=$row;
_set_patient_inc_count($limit, count($returnval), $where, $sqlBindArray);
return $returnval;
}
function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
{
$sql="select $given from patient_data order by $orderby";
if ($limit != "all")
$sql .= " limit $start, $limit";
$rez = sqlStatement($sql);
for($iter=0; $row=sqlFetchArray($rez); $iter++)
$returnval[$iter]=$row;
return $returnval;
}
//----------------------input functions
function newPatientData( $db_id="",
$title = "",
$fname = "",
$lname = "",
$mname = "",
$sex = "",
$DOB = "",
$street = "",
$postal_code = "",
$city = "",
$state = "",
$country_code = "",
$ss = "",
$occupation = "",
$phone_home = "",
$phone_biz = "",
$phone_contact = "",
$status = "",
$contact_relationship = "",
$referrer = "",
$referrerID = "",
$email = "",
$language = "",
$ethnoracial = "",
$interpretter = "",
$migrantseasonal = "",
$family_size = "",
$monthly_income = "",
$homeless = "",
$financial_review = "",
$pubpid = "",
$pid = "MAX(pid)+1",
$providerID = "",
$genericname1 = "",
$genericval1 = "",
$genericname2 = "",
$genericval2 = "",
$billing_note="",
$phone_cell = "",
$hipaa_mail = "",
$hipaa_voice = "",
$squad = 0,
$pharmacy_id = 0,
$drivers_license = "",
$hipaa_notice = "",
$hipaa_message = "",
$regdate = ""
)
{
$DOB = fixDate($DOB);
$regdate = fixDate($regdate);
$fitness = 0;
$referral_source = '';
if ($pid) {
$rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
// Check for brain damage:
if ($db_id != $rez['id']) {
$errmsg = "Internal error: Attempt to change patient_data.id from '" .
$rez['id'] . "' to '$db_id' for pid '$pid'";
die($errmsg);
}
$fitness = $rez['fitness'];
$referral_source = $rez['referral_source'];
}
// Get the default price level.
$lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
"list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
$pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
$query = ("replace into patient_data set
id='$db_id',
title='$title',
fname='$fname',
lname='$lname',
mname='$mname',
sex='$sex',
DOB='$DOB',
street='$street',
postal_code='$postal_code',
city='$city',
state='$state',
country_code='$country_code',
drivers_license='$drivers_license',
ss='$ss',
occupation='$occupation',
phone_home='$phone_home',
phone_biz='$phone_biz',
phone_contact='$phone_contact',
status='$status',
contact_relationship='$contact_relationship',
referrer='$referrer',
referrerID='$referrerID',
email='$email',
language='$language',
ethnoracial='$ethnoracial',
interpretter='$interpretter',
migrantseasonal='$migrantseasonal',
family_size='$family_size',
monthly_income='$monthly_income',
homeless='$homeless',
financial_review='$financial_review',
pubpid='$pubpid',
pid = $pid,
providerID = '$providerID',
genericname1 = '$genericname1',
genericval1 = '$genericval1',
genericname2 = '$genericname2',
genericval2 = '$genericval2',
billing_note= '$billing_note',
phone_cell = '$phone_cell',
pharmacy_id = '$pharmacy_id',
hipaa_mail = '$hipaa_mail',
hipaa_voice = '$hipaa_voice',
hipaa_notice = '$hipaa_notice',
hipaa_message = '$hipaa_message',
squad = '$squad',