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(
9 xl('Restricted Training'),
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"]);
34 function getInsuranceProviders() {
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'];
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
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] . ")";
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"]);
81 // ----------------------------------------------------------------------------
83 * GET ADDITIONAL INFORMATIONS
87 * @param $pid - patient id
90 function getPatientDataNL($pid) {
91 mysql_query("SET NAMES 'utf8'");
92 $sql = "SELECT * FROM patient_data_NL WHERE pdn_id = '$pid'";
93 return sqlQuery($sql);
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");
109 while ( $row = sqlFetchArray($r) ) {
113 if ( $first == 'first') {
114 return $ret[0]['id'];
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");
132 while ( $row = sqlFetchArray($r) ) {
136 if ( $first == 'first') {
137 return $ret[0]['id'];
143 //(CHEMED) facility filter
144 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
146 if ($providers_only) {
147 $param1 = " AND authorized=1 ";
150 //--------------------------------
151 //(CHEMED) facility filter
154 $param2 = " AND facility_id = $facility ";
156 //--------------------------------
159 if ($providerID == "%") {
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']
173 $akeys = array_keys($returnval[0]);
174 foreach($akeys as $key) {
176 $returnval[0][$key] = $returnval[0][$key];
182 //same as above but does not reduce if only 1 row returned
183 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
185 if ($providers_only) {
186 $param1 = "AND authorized=1";
189 if ($providerID == "%") {
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;
203 function getProviderName($providerID) {
204 $pi = getProviderInfo($providerID);
205 if (strlen($pi[0]["lname"]) > 0) {
206 return $pi[0]['fname'] . " " . $pi[0]['lname'];
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;
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"]);
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);
277 if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
278 $lname = trim($matches[1]);
279 $fname = trim($matches[2]);
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%' "
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;
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%' " .
307 $sql .= " limit $start, $limit";
308 $rez = sqlStatement($sql);
309 for($iter=0; $row=sqlFetchArray($rez); $iter++)
310 $returnval[$iter]=$row;
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)
321 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
322 $orderby = "lname ASC, fname ASC";
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']; }
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;
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'];
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%' " .
365 $sql .= " limit $start, $limit";
367 $rez = sqlStatement($sql);
368 for($iter=0; $row=sqlFetchArray($rez); $iter++)
369 $returnval[$iter]=$row;
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%' " .
380 $sql .= " limit $start, $limit";
382 $rez = sqlStatement($sql);
383 for($iter=0; $row=sqlFetchArray($rez); $iter++)
384 $returnval[$iter]=$row;
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' " .
397 $sql .= " limit $start, $limit";
399 $rez = sqlStatement($sql);
400 for($iter=0; $row=sqlFetchArray($rez); $iter++)
401 $returnval[$iter]=$row;
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";
411 $sql .= " limit $start, $limit";
413 $rez = sqlStatement($sql);
414 for($iter=0; $row=sqlFetchArray($rez); $iter++)
415 $returnval[$iter]=$row;
420 //----------------------input functions
421 function newPatientData( $db_id="",
444 $contact_relationship = "",
451 $migrantseasonal = "",
453 $monthly_income = "",
455 $financial_review = "",
468 $drivers_license = "",
474 $prefixlastpartner = "",
483 $DOB = fixDate($DOB);
484 $regdate = fixDate($regdate);
487 $referral_source = '';
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'";
496 $fitness = $rez['fitness'];
497 $referral_source = $rez['referral_source'];
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
514 postal_code='$postal_code',
517 country_code='$country_code',
518 drivers_license='$drivers_license',
520 occupation='$occupation',
521 phone_home='$phone_home',
522 phone_biz='$phone_biz',
523 phone_contact='$phone_contact',
525 contact_relationship='$contact_relationship',
526 referrer='$referrer',
527 referrerID='$referrerID',
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',
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',
552 referral_source='$referral_source',
554 pricelevel='$pricelevel',
557 $id = sqlInsert($query);
561 // find the last inserted id for new patient case
562 $db_id = mysql_insert_id();
566 $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
569 if ( $GLOBALS['dutchpc'] ) {
570 $querynl = ("REPLACE INTO patient_data_NL SET
572 pdn_pxlast = '$prefixlast',
573 pdn_pxlastpar = '$prefixlastpartner',
574 pdn_lastpar = '$lastpartner',
575 pdn_street = '$nstreet',
577 pdn_addition = '$nadd',
578 pdn_initials = '$initials'
581 if ( $db_id ) $idnl = sqlInsert($querynl); // only if exists
588 if ( $GLOBALS['dutchpc'] && ( $db_id ) ) {
589 $querypr = ("INSERT INTO cl_providers(pro_pid, pro_company, pro_initials, pro_prefix, pro_lname,
590 pro_street, pro_number, pro_addition, pro_city, pro_zipcode, pro_phone, pro_fax, pro_email, pro_referer )
591 VALUES ($db_id, '{$provider_data['pro_company']}', '{$provider_data['pro_initials']}',
592 '{$provider_data['pro_prefix']}', '{$provider_data['pro_lname']}',
593 '{$provider_data['pro_street']}', '{$provider_data['pro_number']}', '{$provider_data['pro_addition']}',
594 '{$provider_data['pro_city']}', '{$provider_data['pro_zipcode']}',
595 '{$provider_data['pro_phone']}', '{$provider_data['pro_fax']}', '{$provider_data['pro_email']}',
596 '{$provider_data['pro_referer']}')
597 ON DUPLICATE KEY UPDATE pro_referer = '{$provider_data['pro_referer']}',
598 pro_company = '{$provider_data['pro_company']}', pro_initials = '{$provider_data['pro_initials']}',
599 pro_prefix = '{$provider_data['pro_prefix']}',
600 pro_lname = '{$provider_data['pro_lname']}', pro_street = '{$provider_data['pro_street']}',
601 pro_number = '{$provider_data['pro_number']}', pro_addition = '{$provider_data['pro_addition']}',
602 pro_city = '{$provider_data['pro_city']}', pro_zipcode = '{$provider_data['pro_zipcode']}',
603 pro_phone = '{$provider_data['pro_phone']}', pro_fax = '{$provider_data['pro_fax']}',
604 pro_email = '{$provider_data['pro_email']}'
606 $idpr = sqlInsert($querypr);
608 // referer if it's the case
609 if ( $referer_data['ref_code'] ) {
610 $queryre = ("INSERT INTO cl_referers(ref_pid, ref_code, ref_company, ref_initials, ref_prefix,
611 ref_lname, ref_street, ref_number, ref_addition, ref_city, ref_zipcode, ref_phone, ref_fax,
613 VALUES ($db_id, {$referer_data['ref_code']}, '{$referer_data['ref_company']}',
614 '{$referer_data['ref_initials']}', '{$referer_data['ref_prefix']}',
615 '{$referer_data['ref_lname']}', '{$referer_data['ref_street']}', '{$referer_data['ref_number']}',
616 '{$referer_data['ref_addition']}', '{$referer_data['ref_city']}', '{$referer_data['ref_zipcode']}',
617 '{$referer_data['ref_phone']}', '{$referer_data['ref_fax']}', '{$referer_data['ref_email']}')
618 ON DUPLICATE KEY UPDATE ref_code = {$referer_data['ref_code']},
619 ref_company = '{$referer_data['ref_company']}', ref_initials = '{$referer_data['ref_initials']}',
620 ref_prefix = '{$referer_data['ref_prefix']}',
621 ref_lname = '{$referer_data['ref_lname']}', ref_street = '{$referer_data['ref_street']}',
622 ref_number = '{$referer_data['ref_number']}', ref_addition = '{$referer_data['ref_addition']}',
623 ref_city = '{$referer_data['ref_city']}', ref_zipcode = '{$referer_data['ref_zipcode']}',
624 ref_phone = '{$referer_data['ref_phone']}', ref_fax = '{$referer_data['ref_fax']}',
625 ref_email = '{$referer_data['ref_email']}'
627 $idre = sqlInsert($queryre);
632 sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
633 $phone_biz,$phone_cell,$email,$pid);
638 // Supported input date formats are:
640 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
642 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
644 function fixDate($date, $default="0000-00-00") {
645 $fixed_date = $default;
647 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
648 $dmy = preg_split("'[/.-]'", $date);
650 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
652 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
653 if ($dmy[2] < 1000) $dmy[2] += 1900;
654 if ($dmy[2] < 1910) $dmy[2] += 100;
656 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
663 function updatePatientData($pid,$new)
665 /*******************************************************************
666 $real = getPatientData($pid);
667 $new['DOB'] = fixDate($new['DOB']);
668 while(list($key, $value) = each ($new))
669 $real[$key] = $value;
670 $real['date'] = "'+NOW()+'";
672 $sql = "insert into patient_data set ";
673 while(list($key, $value) = each($real))
674 $sql .= $key." = '$value', ";
675 $sql = substr($sql, 0, -2);
676 return sqlInsert($sql);
677 *******************************************************************/
679 // The above was broken, though seems intent to insert a new patient_data
680 // row for each update. A good idea, but nothing is doing that yet so
681 // the code below does not yet attempt it.
683 $new['DOB'] = fixDate($new['DOB']);
686 $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
687 // Check for brain damage:
688 if ($pid != $rez['pid']) {
689 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
690 $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
693 $sql = "UPDATE patient_data SET date = NOW()";
694 foreach ($new as $key => $value) {
695 $sql .= ", $key = '$value'";
697 $sql .= " WHERE id = '$db_id'";
698 $id = sqlInsert($sql);
700 sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
701 $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
702 $rez['phone_cell'],$rez['email'],$rez['pid']);
707 function newEmployerData( $pid,
716 return sqlInsert("insert into employer_data set
719 postal_code='$postal_code',
728 function updateEmployerData($pid, $new)
730 $old = getEmployerData($pid);
733 foreach (array('name','street','city','state','postal_code','country') as $key) {
734 $value = empty($old[$key]) ? '' : addslashes($old[$key]);
735 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
739 $set .= "$key = '$value', ";
742 $set .= "pid = '$pid', date = NOW()";
743 return sqlInsert("INSERT INTO employer_data SET $set");
748 // This updates or adds the given insurance data info, while retaining any
749 // previously added insurance_data rows that should be preserved.
750 // This does not directly support the maintenance of non-current insurance.
752 function newInsuranceData(
759 $subscriber_lname = "",
760 $subscriber_mname = "",
761 $subscriber_fname = "",
762 $subscriber_relationship = "",
764 $subscriber_DOB = "",
765 $subscriber_street = "",
766 $subscriber_postal_code = "",
767 $subscriber_city = "",
768 $subscriber_state = "",
769 $subscriber_country = "",
770 $subscriber_phone = "",
771 $subscriber_employer = "",
772 $subscriber_employer_street = "",
773 $subscriber_employer_city = "",
774 $subscriber_employer_postal_code = "",
775 $subscriber_employer_state = "",
776 $subscriber_employer_country = "",
778 $subscriber_sex = "",
779 $effective_date = "0000-00-00")
781 if (strlen($type) <= 0) return FALSE;
783 // If a bad date was passed, err on the side of caution.
784 $effective_date = fixDate($effective_date, date('Y-m-d'));
786 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
787 "pid = '$pid' AND type = '$type' ORDER BY date DESC");
788 $idrow = sqlFetchArray($idres);
790 // Replace the most recent entry in any of the following cases:
791 // * Its effective date is >= this effective date.
792 // * It is the first entry and it has no (insurance) provider.
793 // * There is no encounter that is earlier than the new effective date but
794 // on or after the old effective date.
795 // Otherwise insert a new entry.
799 if (strcmp($idrow['date'], $effective_date) > 0) {
803 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
807 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
808 "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
809 "date >= '" . $idrow['date'] . " 00:00:00'");
810 if ($ferow['count'] == 0) $replace = true;
817 // TBD: This is a bit dangerous in that a typo in entering the effective
818 // date can wipe out previous insurance history. So we want some data
819 // entry validation somewhere.
820 sqlStatement("DELETE FROM insurance_data WHERE " .
821 "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
822 "id != " . $idrow['id']);
825 $data['type'] = $type;
826 $data['provider'] = $provider;
827 $data['policy_number'] = $policy_number;
828 $data['group_number'] = $group_number;
829 $data['plan_name'] = $plan_name;
830 $data['subscriber_lname'] = $subscriber_lname;
831 $data['subscriber_mname'] = $subscriber_mname;
832 $data['subscriber_fname'] = $subscriber_fname;
833 $data['subscriber_relationship'] = $subscriber_relationship;
834 $data['subscriber_ss'] = $subscriber_ss;
835 $data['subscriber_DOB'] = $subscriber_DOB;
836 $data['subscriber_street'] = $subscriber_street;
837 $data['subscriber_postal_code'] = $subscriber_postal_code;
838 $data['subscriber_city'] = $subscriber_city;
839 $data['subscriber_state'] = $subscriber_state;
840 $data['subscriber_country'] = $subscriber_country;
841 $data['subscriber_phone'] = $subscriber_phone;
842 $data['subscriber_employer'] = $subscriber_employer;
843 $data['subscriber_employer_city'] = $subscriber_employer_city;
844 $data['subscriber_employer_street'] = $subscriber_employer_street;
845 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
846 $data['subscriber_employer_state'] = $subscriber_employer_state;
847 $data['subscriber_employer_country'] = $subscriber_employer_country;
848 $data['copay'] = $copay;
849 $data['subscriber_sex'] = $subscriber_sex;
851 $data['date'] = $effective_date;
852 updateInsuranceData($idrow['id'], $data);
856 return sqlInsert("INSERT INTO insurance_data SET
858 provider = '$provider',
859 policy_number = '$policy_number',
860 group_number = '$group_number',
861 plan_name = '$plan_name',
862 subscriber_lname = '$subscriber_lname',
863 subscriber_mname = '$subscriber_mname',
864 subscriber_fname = '$subscriber_fname',
865 subscriber_relationship = '$subscriber_relationship',
866 subscriber_ss = '$subscriber_ss',
867 subscriber_DOB = '$subscriber_DOB',
868 subscriber_street = '$subscriber_street',
869 subscriber_postal_code = '$subscriber_postal_code',
870 subscriber_city = '$subscriber_city',
871 subscriber_state = '$subscriber_state',
872 subscriber_country = '$subscriber_country',
873 subscriber_phone = '$subscriber_phone',
874 subscriber_employer = '$subscriber_employer',
875 subscriber_employer_city = '$subscriber_employer_city',
876 subscriber_employer_street = '$subscriber_employer_street',
877 subscriber_employer_postal_code = '$subscriber_employer_postal_code',
878 subscriber_employer_state = '$subscriber_employer_state',
879 subscriber_employer_country = '$subscriber_employer_country',
881 subscriber_sex = '$subscriber_sex',
883 date = '$effective_date'
888 // This is used internally only.
889 function updateInsuranceData($id, $new)
891 $fields = sqlListFields("insurance_data");
894 while(list($key, $value) = each ($new)) {
895 if (in_array($key, $fields)) {
900 $sql = "UPDATE insurance_data SET ";
901 while(list($key, $value) = each($use))
902 $sql .= $key . " = '$value', ";
903 $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
908 function newHistoryData($pid, $new=false) {
909 $sql = "insert into history_data set pid = '$pid', date = NOW()";
911 while(list($key, $value) = each($new)) {
912 if (!get_magic_quotes_gpc()) $value = addslashes($value);
913 $sql .= ", $key = '$value'";
916 return sqlInsert($sql);
919 function updateHistoryData($pid,$new)
921 $real = getHistoryData($pid);
922 while(list($key, $value) = each ($new))
923 $real[$key] = $value;
924 $real['date'] = "'+NOW()+'";
927 $sql = "insert into history_data set ";
928 while(list($key, $value) = each($real))
929 $sql .= $key." = '$value', ";
930 $sql = substr($sql, 0, -2);
933 return sqlInsert($sql);
936 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
937 $phone_biz,$phone_cell,$email,$pid="")
939 $db = $GLOBALS['adodb']['db'];
940 $customer_info = array();
942 $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
943 $result = $db->Execute($sql);
944 if ($result && !$result->EOF) {
945 $customer_info['foreign_update'] = true;
946 $customer_info['foreign_id'] = $result->fields['foreign_id'];
947 $customer_info['foreign_table'] = $result->fields['foreign_table'];
950 ///xml rpc code to connect to accounting package and add user to it
951 $customer_info['firstname'] = $fname;
952 $customer_info['lastname'] = $lname;
953 $customer_info['address'] = $street;
954 $customer_info['suburb'] = $city;
955 $customer_info['state'] = $state;
956 $customer_info['postcode'] = $postal_code;
958 //ezybiz wants state as a code rather than abbreviation
959 $customer_info['geo_zone_id'] = "";
960 $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
961 $db = $GLOBALS['adodb']['db'];
962 $result = $db->Execute($sql);
963 if ($result && !$result->EOF) {
964 $customer_info['geo_zone_id'] = $result->fields['zone_id'];
967 //ezybiz wants country as a code rather than abbreviation
968 $customer_info['geo_country_id'] = "";
969 $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
970 $db = $GLOBALS['adodb']['db'];
971 $result = $db->Execute($sql);
972 if ($result && !$result->EOF) {
973 $customer_info['geo_country_id'] = $result->fields['countries_id'];
976 $customer_info['phone1'] = $phone_home;
977 $customer_info['phone1comment'] = "Home Phone";
978 $customer_info['phone2'] = $phone_biz;
979 $customer_info['phone2comment'] = "Business Phone";
980 $customer_info['phone3'] = $phone_cell;
981 $customer_info['phone3comment'] = "Cell Phone";
982 $customer_info['email'] = $email;
983 $customer_info['customernumber'] = $pid;
985 $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
986 $ws = new WSWrapper($function);
988 // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
989 if (is_numeric($ws->value)) {
990 $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
991 $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
995 // Returns Date of Birth given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
996 function getPatientAge($dobYMD)
999 $yearDiff = substr($tdyYMD,0,4) - substr($dobYMD,0,4);
1000 $ageInMonths = ((substr($tdyYMD,0,4)*12)+substr($tdyYMD,4,2)) -
1001 ((substr($dobYMD,0,4)*12)+substr($dobYMD,4,2));
1002 $dayDiff = substr($tdyYMD,6,2) - substr($dobYMD,6,2);
1003 if ( $dayDiff < 0 ) {
1006 if ( $ageInMonths > 24 ) {
1007 $age = intval($ageInMonths/12);
1010 $age = "$ageInMonths month";
1015 function dateToDB ($date)
1017 $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1022 // ----------------------------------------------------------------------------
1024 * DROPDOWN FOR COUNTRIES
1026 * build a dropdown with all countries from geo_country_reference
1028 * @param int $selected - id for selected record
1029 * @param string $name - the name/id for select form
1030 * @return void - just echo the html encoded string
1032 function dropdown_countries($selected = 0, $name = 'country_code') {
1033 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1035 $string = "<select name='$name' id='$name'>";
1036 while ( $row = sqlFetchArray($r) ) {
1037 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1038 $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1041 $string .= '</select>';
1046 // ----------------------------------------------------------------------------
1048 * DROPDOWN FOR YES/NO
1050 * build a dropdown with two options (yes - 1, no - 0)
1052 * @param int $selected - id for selected record
1053 * @param string $name - the name/id for select form
1054 * @return void - just echo the html encoded string
1056 function dropdown_yesno($selected = 0, $name = 'yesno') {
1057 $string = "<select name='$name' id='$name'>";
1059 $selected = (int)$selected;
1060 if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1061 else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1063 $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1064 $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1065 $string .= '</select>';
1070 // ----------------------------------------------------------------------------
1072 * DROPDOWN FOR MALE/FEMALE options
1074 * build a dropdown with three options (unselected/male/female)
1076 * @param int $selected - id for selected record
1077 * @param string $name - the name/id for select form
1078 * @return void - just echo the html encoded string
1080 function dropdown_sex($selected = 0, $name = 'sex') {
1081 $string = "<select name='$name' id='$name'>";
1083 if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1084 else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1085 else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1087 $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1088 $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1089 $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1090 $string .= '</select>';
1095 // ----------------------------------------------------------------------------
1097 * DROPDOWN FOR MARITAL STATUS
1099 * build a dropdown with marital status
1101 * @param int $selected - id for selected record
1102 * @param string $name - the name/id for select form
1103 * @return void - just echo the html encoded string
1105 function dropdown_marital($selected = 0, $name = 'status') {
1106 $string = "<select name='$name' id='$name'>";
1108 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1110 foreach ( $statii as $st ) {
1111 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1112 $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1115 $string .= '</select>';
1120 // ----------------------------------------------------------------------------
1122 * DROPDOWN FOR PROVIDERS
1124 * build a dropdown with all providers
1126 * @param int $selected - id for selected record
1127 * @param string $name - the name/id for select form
1128 * @return void - just echo the html encoded string
1130 function dropdown_providers($selected = 0, $name = 'status') {
1131 $provideri = getProviderInfo();
1133 $string = "<select name='$name' id='$name'>";
1134 $string .= '<option value="">' .xl('Unassigned'). '</option>';
1135 foreach ( $provideri as $s ) {
1136 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1137 $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1140 $string .= '</select>';
1145 // ----------------------------------------------------------------------------
1147 * DROPDOWN FOR INSURANCE COMPANIES
1149 * build a dropdown with all insurers
1151 * @param int $selected - id for selected record
1152 * @param string $name - the name/id for select form
1153 * @return void - just echo the html encoded string
1155 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1156 $insurancei = getInsuranceProviders();
1158 $string = "<select name='$name' id='$name'>";
1159 $string .= '<option value="0">Onbekend</option>';
1160 foreach ( $insurancei as $iid => $iname ) {
1161 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1162 $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1165 $string .= '</select>';
1171 // ----------------------------------------------------------------------------
1175 * return the name or the country code, function of arguments
1177 * @param int $country_code
1178 * @param string $country_name
1179 * @return string | int - name or code
1181 function country_code($country_code = 0, $country_name = '') {
1183 if ( $country_code ) {
1184 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1186 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1189 $db = $GLOBALS['adodb']['db'];
1190 $result = $db->Execute($sql);
1191 if ($result && !$result->EOF) {
1192 $strint = $result->fields['res'];
1198 // ----------------------------------------------------------------------------
1200 * GET INSURANCE DATA
1203 * return the insurer(s) and some patient
1205 * @param int $pid - patient id
1206 * @param int $current 1-current 0-all insurers
1209 function get_insurers_nl($pid = 0, $current = 1) {
1210 if ( !$pid ) return FALSE;
1212 $q = sprintf("SELECT * FROM patient_insurers_NL pi JOIN insurance_companies ic ON ic.id = pi.pin_provider
1213 WHERE pin_pid = %d ORDER BY pin_date DESC", $pid);
1214 $r = mysql_query($q) or die(mysql_error());
1216 while ( $row = mysql_fetch_array($r) ) {
1220 return ( $current ? $rez[0] : $rez );
1223 // ----------------------------------------------------------------------------
1225 * SET INSURANCE DATA
1228 * set the insurer for a patient
1230 * @param int $pid - patient id
1231 * @param int $insid - insurer id
1234 function set_insurer_nl($pid = 0, $insid = 0, $date = '', $policy = '') {
1235 if ( !$pid || !$insid || ($date == '0000-00-00') ) return FALSE;
1237 $q = sprintf("INSERT INTO patient_insurers_NL(pin_pid, pin_provider, pin_date, pin_policy)
1238 VALUES(%d, %d, '%s', '%s')", $pid, $insid, $date, $policy);
1239 $r = mysql_query($q) or die(mysql_error());
1242 // ----------------------------------------------------------------------------
1244 * FIND THE INSURERS STATUS FOR A PATIENT
1247 * return the answer for the question: is this the first insurer or not?
1249 * @param int $pid - patient id
1250 * @return int - the number of insurer records ( 0 - no insurer; >0 some insurers)
1252 function total_insurers($pid = 0) {
1253 if ( !$pid ) return FALSE;
1255 $q = sprintf("SELECT COUNT(*) AS c FROM patient_insurers_NL WHERE pin_pid = %d ", $pid);
1256 $r = mysql_query($q) or die(mysql_error());
1257 $row = mysql_fetch_array($r);
1263 function DBToDate ($date)
1265 $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);