added ending dates of service
[openemr.git] / library / patient.inc
blob6321523e1d3b1c40c2a9f01967bfa093c275da3c
1 <?php
2 include_once("{$GLOBALS['srcdir']}/sql.inc");
3 require_once(dirname(__FILE__) . "/classes/WSWrapper.class.php");
5 // These are for sports team use:
6 $PLAYER_FITNESSES = array(
7   xl('Full Play'),
8   xl('Full Training'),
9   xl('Restricted Training'),
10   xl('Injured Out'),
11   xl('Rehabilitation'),
12   xl('Illness'),
13   xl('International Duty')
15 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
17 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS") {
18     $sql = "select $given from patient_data where pid='$pid' order by date DESC limit 0,1";
19     return sqlQuery($sql);
22 function getLanguages() {
23     $returnval = array('','english');
24     $sql = "select distinct lower(language) as language from patient_data";
25     $rez = sqlStatement($sql);
26     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
27         if (($row["language"] != "english") && ($row["language"] != "")) {
28             array_push($returnval, $row["language"]);
29         }
30     }
31     return $returnval;
34 function getInsuranceProviders() {
35     $returnval = array();
37     if (true) {
38         $sql = "select name, id from insurance_companies order by name, id";
39         $rez = sqlStatement($sql);
40         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
41             $returnval[$row['id']] = $row['name'];
42         }
43     }
45     // Please leave this here. I have a user who wants to see zip codes and PO
46     // box numbers listed along with the insurance company names, as many companies
47     // have different billing addresses for different plans.  -- Rod Roark
48     //
49     else {
50         $sql = "select insurance_companies.name, insurance_companies.id, " .
51           "addresses.zip, addresses.line1 " .
52           "from insurance_companies, addresses " .
53           "where addresses.foreign_id = insurance_companies.id " .
54           "order by insurance_companies.name, addresses.zip";
56         $rez = sqlStatement($sql);
58         for($iter=0; $row=sqlFetchArray($rez); $iter++) {
59             preg_match("/\d+/", $row['line1'], $matches);
60             $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
61               "," . $matches[0] . ")";
62         }
63     }
65     return $returnval;
68 function getProviders() {
69     $returnval = array("");
70     $sql = "select fname, lname from users where authorized = 1 and " .
71         "active = 1 and username != ''";
72     $rez = sqlStatement($sql);
73     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
74         if (($row["fname"] != "") && ($row["lname"] != "")) {
75             array_push($returnval, $row["fname"] . " " . $row["lname"]);
76         }
77     }
78     return $returnval;
81 // ----------------------------------------------------------------------------
82 /**
83  * GET ADDITIONAL INFORMATIONS 
84  * 
85  * only Dutch use
86  * 
87  * @param $pid - patient id
88  * @return array
89  */
90 function getPatientDataNL($pid) {
91     sqlQuery("SET NAMES 'utf8'");
92     $sql = "SELECT * FROM patient_data_NL WHERE pdn_id = '$pid'";
93     return sqlQuery($sql);
97 /**
98 GET FACILITIES
100 returns all facilities or just the id for the first one
101 (FACILITY FILTERING (lemonsoftware))
103 @param string - if 'first' return first facility ordered by id
104 @return array | int for 'first' case
106 function getFacilities($first = '') {
107     $r = sqlStatement("SELECT * FROM facility ORDER BY id");
108     $ret = array();
109     while ( $row = sqlFetchArray($r) ) {
110        $ret[] = $row;
113         if ( $first == 'first') {
114             return $ret[0]['id'];
115         } else {
116             return $ret;
117         }
121 GET SERVICE FACILITIES
123 returns all service_location facilities or just the id for the first one
124 (FACILITY FILTERING (CHEMED))
126 @param string - if 'first' return first facility ordered by id
127 @return array | int for 'first' case
129 function getServiceFacilities($first = '') {
130     $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
131     $ret = array();
132     while ( $row = sqlFetchArray($r) ) {
133        $ret[] = $row;
136         if ( $first == 'first') {
137             return $ret[0]['id'];
138         } else {
139             return $ret;
140         }
143 //(CHEMED) facility filter
144 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
145     $param1 = "";
146     if ($providers_only) {
147         $param1 = " AND authorized=1 ";
148     }
150     //--------------------------------
151     //(CHEMED) facility filter
152     $param2 = "";
153     if ($facility) {
154         $param2 = " AND facility_id = $facility ";
155     }
156     //--------------------------------
158     $command = "=";
159     if ($providerID == "%") {
160         $command = "like";
161     }
162     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
163         "from users where username != '' and active = 1 and id $command '" .
164         mysql_real_escape_string($providerID) . "' " . $param1 . $param2;
165     $rez = sqlStatement($query);
166     for($iter=0; $row=sqlFetchArray($rez); $iter++)
167         $returnval[$iter]=$row;
169     //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
170     //accessible from $resultval['key']
172     if($iter==1) {
173         $akeys = array_keys($returnval[0]);
174         foreach($akeys as $key) {
176             $returnval[0][$key] = $returnval[0][$key];
177         }
178     }
179     return $returnval;
182 //same as above but does not reduce if only 1 row returned
183 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
184     $param1 = "";
185     if ($providers_only) {
186         $param1 = "AND authorized=1";
187     }
188     $command = "=";
189     if ($providerID == "%") {
190         $command = "like";
191     }
192     $query = "select distinct id, username, lname, fname, authorized, info, facility " .
193         "from users where active = 1 and username != '' and id $command '" .
194         mysql_real_escape_string($providerID) . "' " . $param1;
196     $rez = sqlStatement($query);
197     for($iter=0; $row=sqlFetchArray($rez); $iter++)
198         $returnval[$iter]=$row;
200     return $returnval;
203 function getProviderName($providerID) {
204     $pi = getProviderInfo($providerID);
205     if (strlen($pi[0]["lname"]) > 0) {
206         return $pi[0]['fname'] . " " . $pi[0]['lname'];
207     }
208     return "";
211 function getProviderId($providerName) {
212     $query = "select id from users where username = '". mysql_real_escape_string($providerName)."'";
213     $rez = sqlStatement($query);
214     for($iter=0; $row=sqlFetchArray($rez); $iter++)
215         $returnval[$iter]=$row;
216     return $returnval;
219 function getEthnoRacials() {
220     $returnval = array("");
221     $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
222     $rez = sqlStatement($sql);
223     for($iter=0; $row=sqlFetchArray($rez); $iter++) {
224         if (($row["ethnoracial"] != "")) {
225             array_push($returnval, $row["ethnoracial"]);
226         }
227     }
228     return $returnval;
231 function getHistoryData($pid, $given = "*")
233     $sql = "select $given from history_data where pid='$pid' order by date DESC limit 0,1";
234     return sqlQuery($sql);
237 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
238 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
240   $sql = "select $given from insurance_data as insd " .
241     "left join insurance_companies as ic on ic.id = insd.provider " .
242     "where pid = '$pid' and type = '$type' order by date DESC limit 1";
243   return sqlQuery($sql);
246 function getInsuranceDataByDate($pid, $date, $type,
247   $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
248 { // this must take the date in the following manner: YYYY-MM-DD
249   // this function recalls the insurance value that was most recently enterred from the
250   // given date. it will call up most recent records up to and on the date given,
251   // but not records enterred after the given date
252   $sql = "select $given from insurance_data as insd " .
253     "left join insurance_companies as ic on ic.id = provider " .
254     "where pid = '$pid' and date_format(date,'%Y-%m-%d') <= '$date' and " .
255     "type='$type' order by date DESC limit 1";
256   return sqlQuery($sql);
259 function getEmployerData($pid, $given = "*")
261     $sql = "select $given from employer_data where pid='$pid' order by date DESC limit 0,1";
262     return sqlQuery($sql);
265 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")
267     // Allow the last name to be followed by a comma and some part of a first name.
268     // New behavior for searches:
269     // Allows comma alone followed by some part of a first name
270     // If the first letter of either name is capital, searches for name starting
271     // with given substring (the expected behavior).  If it is lower case, it
272     // it searches for the substring anywhere in the name.  This applies to either
273     // last name or first name or both.  The arbitrary limit of 100 results is set
274     // in the sql query below. --Mark Leeds
275     $lname = trim($lname);
276     $fname = '';
277      if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
278          $lname = trim($matches[1]);
279          $fname = trim($matches[2]);
280     }
281     $search_for_pieces1 = '';
282     $search_for_pieces2 = '';
283     if ($lname{0} != strtoupper($lname{0})) {$search_for_pieces1 = '%';}
284     if ($fname{0} != strtoupper($fname{0})) {$search_for_pieces2 = '%';}
285     $sql="select $given from patient_data where lname like '"
286         .$search_for_pieces1."$lname%' "
287         ."and fname like '"
288         .$search_for_pieces2."$fname%' "
289         ."order by $orderby ";
291     if ($limit != "all") $sql .= " limit $start, $limit";
293     $rez = sqlStatement($sql);
295     for($iter=0; $row=sqlFetchArray($rez); $iter++)
296         $returnval[$iter]=$row;
298     return $returnval;
301 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")
303     $sql = "select $given from patient_data where pubpid like '$pid%' " .
304         "order by $orderby";
306     if ($limit != "all")
307         $sql .= " limit $start, $limit";
308     $rez = sqlStatement($sql);
309     for($iter=0; $row=sqlFetchArray($rez); $iter++)
310         $returnval[$iter]=$row;
312     return $returnval;
315 // return a collection of Patient PIDs
316 // new arg style by JRM March 2008
317 // 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")
318 function getPatientPID($args)
320     $pid = "%";
321     $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
322     $orderby = "lname ASC, fname ASC";
323     $limit="all";
324     $start="0";
326     // alter default values if defined in the passed in args
327     if (isset($args['pid'])) { $pid = $args['pid']; }
328     if (isset($args['given'])) { $given = $args['given']; }
329     if (isset($args['orderby'])) { $orderby = $args['orderby']; }
330     if (isset($args['limit'])) { $limit = $args['limit']; }
331     if (isset($args['start'])) { $start = $args['start']; }
333     $command = "=";
334     if ($pid == -1) $pid = "%";
335     elseif (empty($pid)) $pid = "NULL";
337     if (strstr($pid,"%")) $command = "like";
339     $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
340     if ($limit != "all") $sql .= " limit $start, $limit";
342     $rez = sqlStatement($sql);
343     for($iter=0; $row=sqlFetchArray($rez); $iter++)
344         $returnval[$iter]=$row;
346     return $returnval;
349 function getPatientName($pid) {
350     if (empty($pid)) return "";
351     $patientData = getPatientPID(array("pid"=>$pid));
352     if (empty($patientData[0]['lname'])) return "";
353     $patientName =  $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
354     return $patientName;
357 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
359     $DOB = fixDate($DOB, $DOB);
361     $sql="select $given from patient_data where DOB like '$DOB%' " .
362         "order by $orderby";
364     if ($limit != "all")
365         $sql .= " limit $start, $limit";
367     $rez = sqlStatement($sql);
368     for($iter=0; $row=sqlFetchArray($rez); $iter++)
369         $returnval[$iter]=$row;
371     return $returnval;
374 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
376     $sql="select $given from patient_data where ss like '$ss%' " .
377         "order by $orderby";
379     if ($limit != "all")
380         $sql .= " limit $start, $limit";
382     $rez = sqlStatement($sql);
383     for($iter=0; $row=sqlFetchArray($rez); $iter++)
384         $returnval[$iter]=$row;
386     return $returnval;
389 //(CHEMED) Search by phone number
390 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
392     $phone = ereg_replace( "[[:punct:]]","", $phone );
393     $sql="select $given from patient_data where REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP '$phone' " .
394         "order by $orderby";
396     if ($limit != "all")
397         $sql .= " limit $start, $limit";
399     $rez = sqlStatement($sql);
400     for($iter=0; $row=sqlFetchArray($rez); $iter++)
401         $returnval[$iter]=$row;
403     return $returnval;
406 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
408     $sql="select $given from patient_data order by $orderby";
410     if ($limit != "all")
411         $sql .= " limit $start, $limit";
413     $rez = sqlStatement($sql);
414     for($iter=0; $row=sqlFetchArray($rez); $iter++)
415         $returnval[$iter]=$row;
417     return $returnval;
420 //----------------------input functions
421 function newPatientData(    $db_id="",
422                 $title = "",
423                 $fname = "",
424                 $lname = "",
425                 $mname = "",
426                 $sex = "",
427                 $DOB = "",
428                 $street = "",
429                 // DBC dutch use
430                 $nstreet = "",
431                 $nnr = "",
432                 $nadd = "",
433                 // EOS DBC
434                 $postal_code = "",
435                 $city = "",
436                 $state = "",
437                 $country_code = "",
438                 $ss = "",
439                 $occupation = "",
440                 $phone_home = "",
441                 $phone_biz = "",
442                 $phone_contact = "",
443                 $status = "",
444                 $contact_relationship = "",
445                 $referrer = "",
446                 $referrerID = "",
447                 $email = "",
448                 $language = "",
449                 $ethnoracial = "",
450                 $interpretter = "",
451                 $migrantseasonal = "",
452                 $family_size = "",
453                 $monthly_income = "",
454                 $homeless = "",
455                 $financial_review = "",
456                 $pubpid = "",
457                 $pid = "MAX(pid)+1",
458                 $providerID = "",
459                 $genericname1 = "",
460                 $genericval1 = "",
461                 $genericname2 = "",
462                 $genericval2 = "",
463                 $phone_cell = "",
464                 $hipaa_mail = "",
465                 $hipaa_voice = "",
466                 $squad = 0,
467                 $pharmacy_id = 0,
468                 $drivers_license = "",
469                 $hipaa_notice = "",
470                 $hipaa_message = "",
471                 $regdate = "",
472                 // dutch specific
473                 $prefixlast = "",
474                 $prefixlastpartner = "",
475                 $lastpartner = "",
476                 $initials = "",
477                 $provider_data = array(),
478                 $referer_data = array()
479                 // DBC Dutch System
481             )
483     $DOB = fixDate($DOB);
484     $regdate = fixDate($regdate);
486     $fitness = 0;
487     $referral_source = '';
488     if ($pid) {
489         $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
490         // Check for brain damage:
491         if ($db_id != $rez['id']) {
492             $errmsg = "Internal error: Attempt to change patient_data.id from '" .
493               $rez['id'] . "' to '$db_id' for pid '$pid'";
494             die($errmsg);
495         }
496         $fitness = $rez['fitness'];
497         $referral_source = $rez['referral_source'];
498     }
500     // Get the default price level.
501     $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
502       "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
503     $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
505     $query = ("replace into patient_data set
506         id='$db_id',
507         title='$title',
508         fname='$fname',
509         lname='$lname',
510         mname='$mname',
511         sex='$sex',
512         DOB='$DOB',
513         street='$street',
514         postal_code='$postal_code',
515         city='$city',
516         state='$state',
517         country_code='$country_code',
518         drivers_license='$drivers_license',
519         ss='$ss',
520         occupation='$occupation',
521         phone_home='$phone_home',
522         phone_biz='$phone_biz',
523         phone_contact='$phone_contact',
524         status='$status',
525         contact_relationship='$contact_relationship',
526         referrer='$referrer',
527         referrerID='$referrerID',
528         email='$email',
529         language='$language',
530         ethnoracial='$ethnoracial',
531         interpretter='$interpretter',
532         migrantseasonal='$migrantseasonal',
533         family_size='$family_size',
534         monthly_income='$monthly_income',
535         homeless='$homeless',
536         financial_review='$financial_review',
537         pubpid='$pubpid',
538         pid = $pid,
539         providerID = '$providerID',
540         genericname1 = '$genericname1',
541         genericval1 = '$genericval1',
542         genericname2 = '$genericname2',
543         genericval2 = '$genericval2',
544         phone_cell = '$phone_cell',
545         pharmacy_id = '$pharmacy_id',
546         hipaa_mail = '$hipaa_mail',
547         hipaa_voice = '$hipaa_voice',
548         hipaa_notice = '$hipaa_notice',
549         hipaa_message = '$hipaa_message',
550         squad = '$squad',
551         fitness='$fitness',
552         referral_source='$referral_source',
553         regdate='$regdate',
554         pricelevel='$pricelevel',
555         date=NOW()");
557     $id = sqlInsert($query);
559     // DBC 
560     if ( !$db_id ) {
561       // find the last inserted id for new patient case
562       $db_id = empty($GLOBALS['dutchpc']) ? mysql_insert_id() : dsql_lastid();
563     }
564     // EOS DBC
566     $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
568          // dutch use
569         if ( $GLOBALS['dutchpc'] ) {
570                 $init = strtoupper(preg_replace('/[\s\.\-_0-9]/','',$initials));
571                 
572             $querynl = ("REPLACE INTO patient_data_NL SET
573                     pdn_id = '$db_id',
574                     pdn_pxlast = '$prefixlast',
575                     pdn_pxlastpar = '$prefixlastpartner',
576                     pdn_lastpar = '$lastpartner',
577                     pdn_street = '$nstreet',
578                     pdn_number = '$nnr',
579                     pdn_addition = '$nadd',
580                     pdn_initials = '$init'
581             ");
583             if ( $db_id ) $idnl = sqlInsert($querynl); // only if exists
584         }
585         // EOS dutch use
588        // DBC Dutch System
589         // provider first
590         if ( $GLOBALS['dutchpc'] && $db_id && $provider_data && $referer_data) {
591            $querypr = ("INSERT INTO cl_providers(pro_pid, pro_company, pro_initials, pro_prefix, pro_lname,
592                    pro_street, pro_number, pro_addition, pro_city, pro_zipcode,  pro_phone, pro_fax, pro_email, pro_referer ) 
593                    VALUES ($db_id, '{$provider_data['pro_company']}', '{$provider_data['pro_initials']}',
594                   '{$provider_data['pro_prefix']}', '{$provider_data['pro_lname']}',  
595                   '{$provider_data['pro_street']}', '{$provider_data['pro_number']}', '{$provider_data['pro_addition']}', 
596                   '{$provider_data['pro_city']}',  '{$provider_data['pro_zipcode']}',
597                   '{$provider_data['pro_phone']}', '{$provider_data['pro_fax']}',  '{$provider_data['pro_email']}', 
598                   '{$provider_data['pro_referer']}') 
599                   ON DUPLICATE KEY UPDATE  pro_referer = '{$provider_data['pro_referer']}',
600                   pro_company = '{$provider_data['pro_company']}', pro_initials = '{$provider_data['pro_initials']}',
601                   pro_prefix = '{$provider_data['pro_prefix']}',
602                   pro_lname = '{$provider_data['pro_lname']}', pro_street = '{$provider_data['pro_street']}',
603                   pro_number = '{$provider_data['pro_number']}', pro_addition = '{$provider_data['pro_addition']}',
604                   pro_city = '{$provider_data['pro_city']}', pro_zipcode = '{$provider_data['pro_zipcode']}',
605                   pro_phone = '{$provider_data['pro_phone']}', pro_fax = '{$provider_data['pro_fax']}',
606                   pro_email = '{$provider_data['pro_email']}'
607             ");
608            $idpr = sqlInsert($querypr);
610         // referer if it's the case
611         if ( $referer_data['ref_code'] ) {
612            $queryre = ("INSERT INTO cl_referers(ref_pid, ref_code, ref_company, ref_initials, ref_prefix,
613                    ref_lname, ref_street, ref_number, ref_addition, ref_city, ref_zipcode,  ref_phone, ref_fax,
614                    ref_email) 
615                    VALUES ($db_id, {$referer_data['ref_code']}, '{$referer_data['ref_company']}', 
616                    '{$referer_data['ref_initials']}', '{$referer_data['ref_prefix']}',
617                    '{$referer_data['ref_lname']}', '{$referer_data['ref_street']}', '{$referer_data['ref_number']}', 
618                    '{$referer_data['ref_addition']}', '{$referer_data['ref_city']}', '{$referer_data['ref_zipcode']}',
619                   '{$referer_data['ref_phone']}', '{$referer_data['ref_fax']}',  '{$referer_data['ref_email']}')
620                   ON DUPLICATE KEY UPDATE ref_code = {$referer_data['ref_code']},
621                   ref_company = '{$referer_data['ref_company']}', ref_initials = '{$referer_data['ref_initials']}',
622                   ref_prefix = '{$referer_data['ref_prefix']}',
623                   ref_lname = '{$referer_data['ref_lname']}', ref_street = '{$referer_data['ref_street']}',
624                   ref_number = '{$referer_data['ref_number']}', ref_addition = '{$referer_data['ref_addition']}',
625                   ref_city = '{$referer_data['ref_city']}', ref_zipcode = '{$referer_data['ref_zipcode']}',
626                   ref_phone = '{$referer_data['ref_phone']}', ref_fax = '{$referer_data['ref_fax']}',
627                   ref_email = '{$referer_data['ref_email']}'
628             ");
629            $idre = sqlInsert($queryre);
630         } 
631         } // if globals
632         // EOS DBC
634     sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
635                 $phone_biz,$phone_cell,$email,$pid);
637     return $foo['pid'];
640 // Supported input date formats are:
641 //   mm/dd/yyyy
642 //   mm/dd/yy   (assumes 20yy for yy < 10, else 19yy)
643 //   yyyy/mm/dd
644 //   also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
646 function fixDate($date, $default="0000-00-00") {
647     $fixed_date = $default;
648     $date = trim($date);
649     if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
650         $dmy = preg_split("'[/.-]'", $date);
651         if ($dmy[0] > 99) {
652             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
653         } else {
654             if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
655               if ($dmy[2] < 1000) $dmy[2] += 1900;
656               if ($dmy[2] < 1910) $dmy[2] += 100;
657             }
658             $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
659         }
660     }
662     return $fixed_date;
665 function updatePatientData($pid,$new)
667   /*******************************************************************
668     $real = getPatientData($pid);
669     $new['DOB'] = fixDate($new['DOB']);
670     while(list($key, $value) = each ($new))
671         $real[$key] = $value;
672     $real['date'] = "'+NOW()+'";
673     $real['id'] = "";
674     $sql = "insert into patient_data set ";
675     while(list($key, $value) = each($real))
676         $sql .= $key." = '$value', ";
677     $sql = substr($sql, 0, -2);
678     return sqlInsert($sql);
679   *******************************************************************/
681   // The above was broken, though seems intent to insert a new patient_data
682   // row for each update.  A good idea, but nothing is doing that yet so
683   // the code below does not yet attempt it.
685   $new['DOB'] = fixDate($new['DOB']);
686   $db_id = $new['id'];
688   $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
689   // Check for brain damage:
690   if ($pid != $rez['pid']) {
691     $errmsg = "Internal error: Attempt to change patient data with pid = '" .
692       $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
693     die($errmsg);
694   }
695   $sql = "UPDATE patient_data SET date = NOW()";
696   foreach ($new as $key => $value) {
697     $sql .= ", $key = '$value'";
698   }
699   $sql .= " WHERE id = '$db_id'";
700   $id = sqlInsert($sql);
702   sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
703     $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
704     $rez['phone_cell'],$rez['email'],$rez['pid']);
706   return $id;
709 function newEmployerData(    $pid,
710                 $name = "",
711                 $street = "",
712                 $postal_code = "",
713                 $city = "",
714                 $state = "",
715                 $country = ""
716             )
718     return sqlInsert("insert into employer_data set
719         name='$name',
720         street='$street',
721         postal_code='$postal_code',
722         city='$city',
723         state='$state',
724         country='$country',
725         pid='$pid',
726         date=NOW()
727         ");
730 function updateEmployerData($pid, $new)
732   $old = getEmployerData($pid);
733   $set = '';
734   $modified = false;
735   foreach (array('name','street','city','state','postal_code','country') as $key) {
736     $value = empty($old[$key]) ? '' : addslashes($old[$key]);
737     if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
738       $value = $new[$key];
739       $modified = true;
740     }
741     $set .= "$key = '$value', ";
742   }
743   if ($modified) {
744     $set .= "pid = '$pid', date = NOW()";
745     return sqlInsert("INSERT INTO employer_data SET $set");
746   }
747   return $old['id'];
750 // This updates or adds the given insurance data info, while retaining any
751 // previously added insurance_data rows that should be preserved.
752 // This does not directly support the maintenance of non-current insurance.
754 function newInsuranceData(
755   $pid,
756   $type = "",
757   $provider = "",
758   $policy_number = "",
759   $group_number = "",
760   $plan_name = "",
761   $subscriber_lname = "",
762   $subscriber_mname = "",
763   $subscriber_fname = "",
764   $subscriber_relationship = "",
765   $subscriber_ss = "",
766   $subscriber_DOB = "",
767   $subscriber_street = "",
768   $subscriber_postal_code = "",
769   $subscriber_city = "",
770   $subscriber_state = "",
771   $subscriber_country = "",
772   $subscriber_phone = "",
773   $subscriber_employer = "",
774   $subscriber_employer_street = "",
775   $subscriber_employer_city = "",
776   $subscriber_employer_postal_code = "",
777   $subscriber_employer_state = "",
778   $subscriber_employer_country = "",
779   $copay = "",
780   $subscriber_sex = "",
781   $effective_date = "0000-00-00")
783   if (strlen($type) <= 0) return FALSE;
785   // If a bad date was passed, err on the side of caution.
786   $effective_date = fixDate($effective_date, date('Y-m-d'));
788   $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
789     "pid = '$pid' AND type = '$type' ORDER BY date DESC");
790   $idrow = sqlFetchArray($idres);
792   // Replace the most recent entry in any of the following cases:
793   // * Its effective date is >= this effective date.
794   // * It is the first entry and it has no (insurance) provider.
795   // * There is no encounter that is earlier than the new effective date but
796   //   on or after the old effective date.
797   // Otherwise insert a new entry.
799   $replace = false;
800   if ($idrow) {
801     if (strcmp($idrow['date'], $effective_date) > 0) {
802       $replace = true;
803     }
804     else {
805       if (!$idrow['provider'] && !sqlFetchArray($idres)) {
806         $replace = true;
807       }
808       else {
809         $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
810           "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
811           "date >= '" . $idrow['date'] . " 00:00:00'");
812         if ($ferow['count'] == 0) $replace = true;
813       }
814     }
815   }
817   if ($replace) {
819     // TBD: This is a bit dangerous in that a typo in entering the effective
820     // date can wipe out previous insurance history.  So we want some data
821     // entry validation somewhere.
822     sqlStatement("DELETE FROM insurance_data WHERE " .
823       "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
824       "id != " . $idrow['id']);
826     $data = array();
827     $data['type'] = $type;
828     $data['provider'] = $provider;
829     $data['policy_number'] = $policy_number;
830     $data['group_number'] = $group_number;
831     $data['plan_name'] = $plan_name;
832     $data['subscriber_lname'] = $subscriber_lname;
833     $data['subscriber_mname'] = $subscriber_mname;
834     $data['subscriber_fname'] = $subscriber_fname;
835     $data['subscriber_relationship'] = $subscriber_relationship;
836     $data['subscriber_ss'] = $subscriber_ss;
837     $data['subscriber_DOB'] = $subscriber_DOB;
838     $data['subscriber_street'] = $subscriber_street;
839     $data['subscriber_postal_code'] = $subscriber_postal_code;
840     $data['subscriber_city'] = $subscriber_city;
841     $data['subscriber_state'] = $subscriber_state;
842     $data['subscriber_country'] = $subscriber_country;
843     $data['subscriber_phone'] = $subscriber_phone;
844     $data['subscriber_employer'] = $subscriber_employer;
845     $data['subscriber_employer_city'] = $subscriber_employer_city;
846     $data['subscriber_employer_street'] = $subscriber_employer_street;
847     $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
848     $data['subscriber_employer_state'] = $subscriber_employer_state;
849     $data['subscriber_employer_country'] = $subscriber_employer_country;
850     $data['copay'] = $copay;
851     $data['subscriber_sex'] = $subscriber_sex;
852     $data['pid'] = $pid;
853     $data['date'] = $effective_date;
854     updateInsuranceData($idrow['id'], $data);
855     return $idrow['id'];
856   }
857   else {
858     return sqlInsert("INSERT INTO insurance_data SET
859       type = '$type',
860       provider = '$provider',
861       policy_number = '$policy_number',
862       group_number = '$group_number',
863       plan_name = '$plan_name',
864       subscriber_lname = '$subscriber_lname',
865       subscriber_mname = '$subscriber_mname',
866       subscriber_fname = '$subscriber_fname',
867       subscriber_relationship = '$subscriber_relationship',
868       subscriber_ss = '$subscriber_ss',
869       subscriber_DOB = '$subscriber_DOB',
870       subscriber_street = '$subscriber_street',
871       subscriber_postal_code = '$subscriber_postal_code',
872       subscriber_city = '$subscriber_city',
873       subscriber_state = '$subscriber_state',
874       subscriber_country = '$subscriber_country',
875       subscriber_phone = '$subscriber_phone',
876       subscriber_employer = '$subscriber_employer',
877       subscriber_employer_city = '$subscriber_employer_city',
878       subscriber_employer_street = '$subscriber_employer_street',
879       subscriber_employer_postal_code = '$subscriber_employer_postal_code',
880       subscriber_employer_state = '$subscriber_employer_state',
881       subscriber_employer_country = '$subscriber_employer_country',
882       copay = '$copay',
883       subscriber_sex = '$subscriber_sex',
884       pid = '$pid',
885       date = '$effective_date'
886     ");
887   }
890 // This is used internally only.
891 function updateInsuranceData($id, $new)
893   $fields = sqlListFields("insurance_data");
894   $use = array();
896   while(list($key, $value) = each ($new)) {
897     if (in_array($key, $fields)) {
898       $use[$key] = $value;
899     }
900   }
902   $sql = "UPDATE insurance_data SET ";
903   while(list($key, $value) = each($use))
904     $sql .= $key . " = '$value', ";
905   $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
907   sqlStatement($sql);
910 function newHistoryData($pid, $new=false) {
911   $sql = "insert into history_data set pid = '$pid', date = NOW()";
912   if ($new) {
913     while(list($key, $value) = each($new)) {
914       if (!get_magic_quotes_gpc()) $value = addslashes($value);
915       $sql .= ", $key = '$value'";
916     }
917   }
918   return sqlInsert($sql);
921 function updateHistoryData($pid,$new)
923         $real = getHistoryData($pid);
924         while(list($key, $value) = each ($new))
925                 $real[$key] = $value;
926         $real['date'] = "'+NOW()+'";
927         $real['id'] = "";
929         $sql = "insert into history_data set ";
930         while(list($key, $value) = each($real))
931                 $sql .= $key." = '$value', ";
932         $sql = substr($sql, 0, -2);
935         return sqlInsert($sql);
938 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
939                 $phone_biz,$phone_cell,$email,$pid="")
941     $db = $GLOBALS['adodb']['db'];
942     $customer_info = array();
944     $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
945     $result = $db->Execute($sql);
946     if ($result && !$result->EOF) {
947         $customer_info['foreign_update'] = true;
948         $customer_info['foreign_id'] = $result->fields['foreign_id'];
949         $customer_info['foreign_table'] = $result->fields['foreign_table'];
950     }
952     ///xml rpc code to connect to accounting package and add user to it
953     $customer_info['firstname'] = $fname;
954     $customer_info['lastname'] = $lname;
955     $customer_info['address'] = $street;
956     $customer_info['suburb'] = $city;
957     $customer_info['state'] = $state;
958     $customer_info['postcode'] = $postal_code;
960     //ezybiz wants state as a code rather than abbreviation
961     $customer_info['geo_zone_id'] = "";
962     $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
963     $db = $GLOBALS['adodb']['db'];
964     $result = $db->Execute($sql);
965     if ($result && !$result->EOF) {
966         $customer_info['geo_zone_id'] = $result->fields['zone_id'];
967     }
969     //ezybiz wants country as a code rather than abbreviation
970     $customer_info['geo_country_id'] = "";
971     $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
972     $db = $GLOBALS['adodb']['db'];
973     $result = $db->Execute($sql);
974     if ($result && !$result->EOF) {
975         $customer_info['geo_country_id'] = $result->fields['countries_id'];
976     }
978     $customer_info['phone1'] = $phone_home;
979     $customer_info['phone1comment'] = "Home Phone";
980     $customer_info['phone2'] = $phone_biz;
981     $customer_info['phone2comment'] = "Business Phone";
982   $customer_info['phone3'] = $phone_cell;
983   $customer_info['phone3comment'] = "Cell Phone";
984     $customer_info['email'] = $email;
985     $customer_info['customernumber'] = $pid;
987     $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
988     $ws = new WSWrapper($function);
990     // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
991     if (is_numeric($ws->value)) {
992         $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
993         $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
994     }
997 // Returns Date of Birth given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
998 function getPatientAge($dobYMD)
1000     $tdyYMD=date("Ymd");
1001     $yearDiff = substr($tdyYMD,0,4) - substr($dobYMD,0,4);
1002     $ageInMonths = ((substr($tdyYMD,0,4)*12)+substr($tdyYMD,4,2)) -
1003                    ((substr($dobYMD,0,4)*12)+substr($dobYMD,4,2));
1004     $dayDiff = substr($tdyYMD,6,2) - substr($dobYMD,6,2);
1005     if ( $dayDiff < 0 ) {
1006         $ageInMonths -= 1;
1007     }
1008     if ( $ageInMonths > 24 ) {
1009         $age = intval($ageInMonths/12);
1010     }
1011     else  {
1012         $age = "$ageInMonths month";
1013     }
1014     return $age;
1017 function dateToDB ($date)
1019     $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1020     return $date;
1024 // ----------------------------------------------------------------------------
1026  * DROPDOWN FOR COUNTRIES
1027  * 
1028  * build a dropdown with all countries from geo_country_reference
1029  * 
1030  * @param int $selected - id for selected record
1031  * @param string $name - the name/id for select form
1032  * @return void - just echo the html encoded string
1033  */
1034 function dropdown_countries($selected = 0, $name = 'country_code') {
1035     $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1037     $string = "<select name='$name' id='$name'>";
1038     while ( $row = sqlFetchArray($r) ) {
1039         $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1040         $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1041     }
1043     $string .= '</select>';
1044     echo $string;
1048 // ----------------------------------------------------------------------------
1050  * DROPDOWN FOR YES/NO
1051  * 
1052  * build a dropdown with two options (yes - 1, no - 0)
1053  * 
1054  * @param int $selected - id for selected record
1055  * @param string $name - the name/id for select form
1056  * @return void - just echo the html encoded string 
1057  */
1058 function dropdown_yesno($selected = 0, $name = 'yesno') {
1059     $string = "<select name='$name' id='$name'>";
1061     $selected = (int)$selected;
1062     if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1063     else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1065     $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1066     $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1067     $string .= '</select>';
1069     echo $string;
1072 // ----------------------------------------------------------------------------
1074  * DROPDOWN FOR MALE/FEMALE options
1075  * 
1076  * build a dropdown with three options (unselected/male/female)
1077  * 
1078  * @param int $selected - id for selected record
1079  * @param string $name - the name/id for select form
1080  * @return void - just echo the html encoded string
1081  */
1082 function dropdown_sex($selected = 0, $name = 'sex') {
1083     $string = "<select name='$name' id='$name'>";
1085     if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1086     else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1087     else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1089     $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1090     $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1091     $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1092     $string .= '</select>';
1094     echo $string;
1097 // ----------------------------------------------------------------------------
1099  * DROPDOWN FOR MARITAL STATUS
1100  * 
1101  * build a dropdown with marital status
1102  * 
1103  * @param int $selected - id for selected record
1104  * @param string $name - the name/id for select form
1105  * @return void - just echo the html encoded string
1106  */
1107 function dropdown_marital($selected = 0, $name = 'status') {
1108     $string = "<select name='$name' id='$name'>";
1110     $statii = array('married','single','divorced','widowed','separated','domestic partner');
1112     foreach ( $statii as $st ) {
1113         $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1114         $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1115     }
1117     $string .= '</select>';
1119     echo $string;
1122 // ----------------------------------------------------------------------------
1124  * DROPDOWN FOR PROVIDERS
1125  * 
1126  * build a dropdown with all providers
1127  * 
1128  * @param int $selected - id for selected record
1129  * @param string $name - the name/id for select form
1130  * @return void - just echo the html encoded string
1131  */
1132 function dropdown_providers($selected = 0, $name = 'status') {
1133     $provideri = getProviderInfo();
1135     $string = "<select name='$name' id='$name'>";
1136     $string .= '<option value="">' .xl('Unassigned'). '</option>';
1137     foreach ( $provideri as $s ) {
1138         $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1139         $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1140     }
1142     $string .= '</select>';
1144     echo $string;
1147 // ----------------------------------------------------------------------------
1149  * DROPDOWN FOR INSURANCE COMPANIES
1150  * 
1151  * build a dropdown with all insurers
1152  * 
1153  * @param int $selected - id for selected record
1154  * @param string $name - the name/id for select form
1155  * @return void - just echo the html encoded string
1156  */
1157 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1158     $insurancei = getInsuranceProviders();
1160     $string = "<select name='$name' id='$name'>";
1161     $string .= '<option value="0">Onbekend</option>';
1162     foreach ( $insurancei as $iid => $iname ) {
1163         $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1164         $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1165     }
1167     $string .= '</select>';
1169     echo $string;
1173 // ----------------------------------------------------------------------------
1175  * COUNTRY CODE
1176  * 
1177  * return the name or the country code, function of arguments
1178  * 
1179  * @param int $country_code
1180  * @param string $country_name
1181  * @return string | int - name or code
1182  */
1183 function country_code($country_code = 0, $country_name = '') {
1184     $strint = '';
1185     if ( $country_code ) {
1186         $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1187     } else {
1188         $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1189     }
1191     $db = $GLOBALS['adodb']['db'];
1192     $result = $db->Execute($sql);
1193     if ($result && !$result->EOF) {
1194         $strint = $result->fields['res'];
1195     }
1197     return $strint;
1200 // ----------------------------------------------------------------------------
1202  * GET INSURANCE DATA
1203  * (Dutch usage)
1204  * 
1205  * return the insurer(s) and some patient
1206  * 
1207  * @param int $pid - patient id
1208  * @param int $current 1-current 0-all insurers
1209  * @return array
1210  */
1211 function get_insurers_nl($pid = 0, $current = 1) {
1212     if ( !$pid ) return FALSE;
1214     $join = 'insurance_companies ic ON ic.id = pi.pin_provider';
1215     $r = dsql_select('*', 'patient_insurers_NL pi', array('pin_pid' => $pid), 'pin_date DESC', $join);
1217     while ( $row = mysql_fetch_array($r) ) {
1218         $rez[] = $row;
1219     } // while
1221     return ( $current ? $rez[0] : $rez );
1225 // ----------------------------------------------------------------------------
1227  * SET INSURANCE DATA
1228  * (Dutch usage)
1229  * 
1230  * set the insurer for a patient
1231  * 
1232  * @param int $pid - patient id
1233  * @param int $insid - insurer id
1234  * @return void
1235  */
1236 function set_insurer_nl($pid = 0, $insid = 0, $date = '', $policy = '') {
1237     if ( !$pid || !$insid || ($date == '0000-00-00') ) return FALSE;
1239     $fields = array('pin_pid', 'pin_provider', 'pin_date', 'pin_policy');
1240     $values = array($pid, $insid, $date, $policy);
1241     dsql_insert('patient_insurers_NL', $fields, $values);
1244 // ----------------------------------------------------------------------------
1246  * FIND THE INSURERS STATUS FOR A PATIENT
1247  * (Dutch usage)
1248  * 
1249  * return the answer for the question: is this the first insurer or not?
1250  * 
1251  * @param int $pid - patient id
1252  * @return int - the number of insurer records ( 0 - no insurer; >0 some insurers)
1253  */
1254 function total_insurers($pid = 0) {
1255     if ( !$pid ) return FALSE;
1257     $r = dsql_select('COUNT(*) AS c', 'patient_insurers_NL', array('pin_pid' => $pid));
1258     $row = mysql_fetch_array($r);
1260     return $row['c'];
1264 function DBToDate ($date)
1266     $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1267     return $date;