3 // Copyright (C) 2011 Ken Chapple
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License
7 // as published by the Free Software Foundation; either version 2
8 // of the License, or (at your option) any later version.
10 // Holds library functions (and hashes) used by the appointment reporting module
14 require_once(dirname(__FILE__
)."/encounter_events.inc.php");
15 require_once(dirname(__FILE__
)."/../interface/main/calendar/modules/PostCalendar/pnincludes/Date/Calc.php");
18 $COMPARE_FUNCTION_HASH = array(
19 'doctor' => 'compareAppointmentsByDoctorName',
20 'patient' => 'compareAppointmentsByPatientName',
21 'pubpid' => 'compareAppointmentsByPatientId',
22 'date' => 'compareAppointmentsByDate',
23 'time' => 'compareAppointmentsByTime',
24 'type' => 'compareAppointmentsByType',
25 'comment' => 'compareAppointmentsByComment',
26 'status' => 'compareAppointmentsByStatus',
27 'completed' => 'compareAppointmentsByCompletedDrugScreen',
28 'trackerstatus' => 'compareAppointmentsByTrackerStatus'
32 'doctor' => array( 'doctor', 'date', 'time' ),
33 'patient' => array( 'patient', 'date', 'time' ),
34 'pubpid' => array( 'pubpid', 'date', 'time' ),
35 'date' => array( 'date', 'time', 'type', 'patient' ),
36 'time' => array( 'time', 'date', 'patient' ),
37 'type' => array( 'type', 'date', 'time', 'patient' ),
38 'comment' => array( 'comment', 'date', 'time', 'patient' ),
39 'status' => array( 'status', 'date', 'time', 'patient' ),
40 'completed' => array( 'completed', 'date', 'time', 'patient' ),
41 'trackerstatus' => array( 'trackerstatus', 'date', 'time', 'patient' ),
44 /*Arrays for the interpretation of recurrence patterns.*/
47 '2' => xl('Every 2nd'),
48 '3' => xl('Every 3rd'),
49 '4' => xl('Every 4th'),
50 '5' => xl('Every 5th'),
51 '6' => xl('Every 6th')
54 $REPEAT_FREQ_TYPE = array(
62 $REPEAT_ON_NUM = array(
70 $REPEAT_ON_DAY = array(
74 '3' => xl('Wednesday'),
75 '4' => xl('Thursday'),
80 function fetchEvents($from_date, $to_date, $where_param = null, $orderby_param = null, $tracker_board = false, $nextX = 0, $bind_param = null, $query_param = null)
83 $sqlBindArray = array();
86 $query = $query_param;
89 $sqlBindArray = $bind_param;
95 "((e.pc_endDate >= ? AND e.pc_recurrtype > '0') OR " .
96 "(e.pc_eventDate >= ?))";
98 array_push($sqlBindArray, $from_date, $from_date);
102 "((e.pc_endDate >= ? AND e.pc_eventDate <= ? AND e.pc_recurrtype > '0') OR " .
103 "(e.pc_eventDate >= ? AND e.pc_eventDate <= ?))";
105 array_push($sqlBindArray, $from_date, $to_date, $from_date, $to_date);
109 $where .= $where_param;
112 $order_by = "e.pc_eventDate, e.pc_startTime";
113 if ($orderby_param) {
114 $order_by = $orderby_param;
117 // Tracker Board specific stuff
118 $tracker_fields = '';
120 if ($tracker_board) {
121 $tracker_fields = "e.pc_room, e.pc_pid, t.id, t.date, t.apptdate, t.appttime, t.eid, t.pid, t.original_user, t.encounter, t.lastseq, t.random_drug_test, t.drug_screen_completed, " .
122 "q.pt_tracker_id, q.start_datetime, q.room, q.status, q.seq, q.user, " .
123 "s.toggle_setting_1, s.toggle_setting_2, s.option_id, ";
124 $tracker_joins = "LEFT OUTER JOIN patient_tracker AS t ON t.pid = e.pc_pid AND t.apptdate = e.pc_eventDate AND t.appttime = e.pc_starttime AND t.eid = e.pc_eid " .
125 "LEFT OUTER JOIN patient_tracker_element AS q ON q.pt_tracker_id = t.id AND q.seq = t.lastseq " .
126 "LEFT OUTER JOIN list_options AS s ON s.list_id = 'apptstat' AND s.option_id = q.status AND s.activity = 1 " ;
130 "e.pc_eventDate, e.pc_endDate, e.pc_startTime, e.pc_endTime, e.pc_duration, e.pc_recurrtype, e.pc_recurrspec, e.pc_recurrfreq, e.pc_catid, e.pc_eid, e.pc_gid, " .
131 "e.pc_title, e.pc_hometext, e.pc_apptstatus, " .
132 "p.fname, p.mname, p.lname, p.pid, p.pubpid, p.phone_home, p.phone_cell, " .
133 "p.hipaa_allowsms, p.phone_home, p.phone_cell, p.hipaa_voice, p.hipaa_allowemail, p.email, " .
134 "u.fname AS ufname, u.mname AS umname, u.lname AS ulname, u.id AS uprovider_id, " .
137 "c.pc_catname, c.pc_catid, e.pc_facility " .
138 "FROM openemr_postcalendar_events AS e " .
140 "LEFT OUTER JOIN facility AS f ON e.pc_facility = f.id " .
141 "LEFT OUTER JOIN patient_data AS p ON p.pid = e.pc_pid " .
142 "LEFT OUTER JOIN users AS u ON u.id = e.pc_aid " .
143 "LEFT OUTER JOIN openemr_postcalendar_categories AS c ON c.pc_catid = e.pc_catid " .
145 "ORDER BY $order_by";
148 $sqlBindArray = array_merge($sqlBindArray, $bind_param);
153 ///////////////////////////////////////////////////////////////////////
154 // The following code is from the calculateEvents function in the //
155 // PostCalendar Module modified and inserted here by epsdky //
156 ///////////////////////////////////////////////////////////////////////
160 $res = sqlStatement($query, $sqlBindArray);
165 $resNotNull = (isset($res) && $res != null);
168 while ($event = sqlFetchArray($res)) {
171 $stopDate = $event['pc_endDate'];
173 $stopDate = ($event['pc_endDate'] <= $to_date) ?
$event['pc_endDate'] : $to_date;
178 switch ($event['pc_recurrtype']) {
186 $event_recurrspec = @unserialize
($event['pc_recurrspec']);
188 $rfreq = $event_recurrspec['event_repeat_freq'];
189 $rtype = $event_recurrspec['event_repeat_freq_type'];
190 $exdate = $event_recurrspec['exdate'];
192 list($ny,$nm,$nd) = explode('-', $event['pc_eventDate']);
193 // $occurance = Date_Calc::dateFormat($nd,$nm,$ny,'%Y-%m-%d');
194 $occurance = $event['pc_eventDate'];
196 while ($occurance < $from_date) {
197 $occurance =& __increment($nd, $nm, $ny, $rfreq, $rtype);
198 list($ny,$nm,$nd) = explode('-', $occurance);
201 while ($occurance <= $stopDate) {
203 if (isset($exdate)) {
204 foreach (explode(",", $exdate) as $exception) {
205 // occurrance format == yyyy-mm-dd
206 // exception format == yyyymmdd
207 if (preg_replace("/-/", "", $occurance) == $exception) {
213 if ($excluded == false) {
214 $event['pc_eventDate'] = $occurance;
215 $event['pc_endDate'] = '0000-00-00';
220 if ($incX == $nextX) {
228 $occurance =& __increment($nd, $nm, $ny, $rfreq, $rtype);
229 list($ny,$nm,$nd) = explode('-', $occurance);
235 $event_recurrspec = @unserialize
($event['pc_recurrspec']);
237 $rfreq = $event_recurrspec['event_repeat_on_freq'];
238 $rnum = $event_recurrspec['event_repeat_on_num'];
239 $rday = $event_recurrspec['event_repeat_on_day'];
240 $exdate = $event_recurrspec['exdate'];
242 list($ny,$nm,$nd) = explode('-', $event['pc_eventDate']);
244 if (isset($event_recurrspec['rt2_pf_flag']) && $event_recurrspec['rt2_pf_flag']) {
248 $occuranceYm = "$ny-$nm"; // YYYY-mm
249 $from_dateYm = substr($from_date, 0, 7); // YYYY-mm
250 $stopDateYm = substr($stopDate, 0, 7); // YYYY-mm
252 // $nd will sometimes be 29, 30 or 31 and if used in the mktime functions below
253 // a problem with overflow will occur so it is set to 1 to avoid this (for rt2
254 // appointments set prior to fix $nd remains unchanged). This can be done since
255 // $nd has no influence past the mktime functions.
256 while ($occuranceYm < $from_dateYm) {
257 $occuranceYmX = date('Y-m-d', mktime(0, 0, 0, $nm+
$rfreq, $nd, $ny));
258 list($ny,$nm,$nd) = explode('-', $occuranceYmX);
259 $occuranceYm = "$ny-$nm";
262 while ($occuranceYm <= $stopDateYm) {
266 $occurance = Date_Calc
::NWeekdayOfMonth($dnum--, $rday, $nm, $ny, $format = "%Y-%m-%d");
267 } while ($occurance === -1);
269 if ($occurance >= $from_date && $occurance <= $stopDate) {
271 if (isset($exdate)) {
272 foreach (explode(",", $exdate) as $exception) {
273 // occurrance format == yyyy-mm-dd
274 // exception format == yyyymmdd
275 if (preg_replace("/-/", "", $occurance) == $exception) {
281 if ($excluded == false) {
282 $event['pc_eventDate'] = $occurance;
283 $event['pc_endDate'] = '0000-00-00';
288 if ($incX == $nextX) {
297 $occuranceYmX = date('Y-m-d', mktime(0, 0, 0, $nm+
$rfreq, $nd, $ny));
298 list($ny,$nm,$nd) = explode('-', $occuranceYmX);
299 $occuranceYm = "$ny-$nm";
306 ////////////////////// End of code inserted by epsdky
309 function fetchAllEvents($from_date, $to_date, $provider_id = null, $facility_id = null)
311 $sqlBindArray = array();
316 $where .= " AND e.pc_aid = ?";
317 array_push($sqlBindArray, $provider_id);
321 $where .= " AND e.pc_facility = ? AND u.facility_id = ?";
322 array_push($sqlBindArray, $facility_id, $facility_id);
325 $appointments = fetchEvents($from_date, $to_date, $where, null, false, 0, $sqlBindArray);
326 return $appointments;
329 //Support for therapy group appointments added by shachar z.
330 function fetchAppointments($from_date, $to_date, $patient_id = null, $provider_id = null, $facility_id = null, $pc_appstatus = null, $with_out_provider = null, $with_out_facility = null, $pc_catid = null, $tracker_board = false, $nextX = 0, $group_id = null, $patient_name = null)
332 $sqlBindArray = array();
337 $where .= " AND e.pc_aid = ?";
338 array_push($sqlBindArray, $provider_id);
342 $where .= " AND e.pc_pid = ?";
343 array_push($sqlBindArray, $patient_id);
344 } elseif ($group_id) {
345 //if $group_id this means we want only the group events
346 $where .= " AND e.pc_gid = ? AND e.pc_pid = ''";
347 array_push($sqlBindArray, $group_id);
349 $where .= " AND e.pc_pid != ''";
353 $where .= " AND e.pc_facility = ?";
354 array_push($sqlBindArray, $facility_id);
357 //Appointment Status Checking
358 if ($pc_appstatus != '') {
359 $where .= " AND e.pc_apptstatus = ?";
360 array_push($sqlBindArray, $pc_appstatus);
363 if ($pc_catid != null) {
364 $where .= " AND e.pc_catid = ?";
365 array_push($sqlBindArray, $pc_catid);
368 if ($patient_name != null) {
369 $where .= " AND (p.fname LIKE CONCAT('%',?,'%') OR p.lname LIKE CONCAT('%',?,'%'))";
370 array_push($sqlBindArray, $patient_name, $patient_name);
373 //Without Provider checking
374 if ($with_out_provider != '') {
375 $where .= " AND e.pc_aid = ''";
378 //Without Facility checking
379 if ($with_out_facility != '') {
380 $where .= " AND e.pc_facility = 0";
383 $appointments = fetchEvents($from_date, $to_date, $where, '', $tracker_board, $nextX, $sqlBindArray);
384 return $appointments;
387 //Support for therapy group appointments added by shachar z.
388 function fetchNextXAppts($from_date, $patient_id, $nextX = 1, $group_id = null)
392 $nextXAppts = array();
393 $appts = fetchAppointments($from_date, null, $patient_id, null, null, null, null, null, null, false, $nextX, $group_id);
395 $appts = sortAppointments($appts);
396 $nextXAppts = array_slice($appts, 0, $nextX);
402 // get the event slot size in seconds
403 function getSlotSize()
405 if (isset($GLOBALS['calendar_interval'])) {
406 return $GLOBALS['calendar_interval'] * 60;
412 function getAvailableSlots($from_date, $to_date, $provider_id = null, $facility_id = null)
414 $appointments = fetchAllEvents($from_date, $to_date, $provider_id, $facility_id);
415 $appointments = sortAppointments($appointments, "date");
416 $from_datetime = strtotime($from_date." 00:00:00");
417 $to_datetime = strtotime($to_date." 23:59:59");
418 $availableSlots = array();
421 for ($i = 0; $i < count($appointments); ++
$i) {
422 if ($appointments[$i]['pc_catid'] == 2) { // 2 == In Office
423 $start_time = $appointments[$i]['pc_startTime'];
424 $date = $appointments[$i]['pc_eventDate'];
425 $provider_id = $appointments[$i]['uprovider_id'];
426 } else if ($appointments[$i]['pc_catid'] == 3) { // 3 == Out Of Office
429 $start_time = $appointments[$i]['pc_endTime'];
430 $date = $appointments[$i]['pc_eventDate'];
431 $provider_id = $appointments[$i]['uprovider_id'];
434 // find next appointment with the same provider
435 $next_appointment_date = 0;
436 $next_appointment_time = 0;
437 for ($j = $i+
1; $j < count($appointments); ++
$j) {
438 if ($appointments[$j]['uprovider_id'] == $provider_id) {
439 $next_appointment_date = $appointments[$j]['pc_eventDate'];
440 $next_appointment_time = $appointments[$j]['pc_startTime'];
445 $same_day = ( strtotime($next_appointment_date) == strtotime($date) ) ?
true : false;
447 if ($next_appointment_time && $same_day) {
448 // check the start time of the next appointment
450 $start_datetime = strtotime($date." ".$start_time);
451 $next_appointment_datetime = strtotime($next_appointment_date." ".$next_appointment_time);
452 $curr_time = $start_datetime;
453 while ($curr_time < $next_appointment_datetime - (getSlotSize() / 2)) {
454 //create a new appointment ever 15 minutes
455 $time = date("H:i:s", $curr_time);
456 $available_slot = createAvailableSlot(
457 $appointments[$i]['pc_eventDate'],
459 $appointments[$i]['ufname'],
460 $appointments[$i]['ulname'],
461 $appointments[$i]['umname']
463 $availableSlots []= $available_slot;
464 $curr_time +
= getSlotSize(); // add a 15-minute slot
469 return $availableSlots;
472 function createAvailableSlot($event_date, $start_time, $provider_fname, $provider_lname, $provider_mname = "", $cat_name = "Available")
475 $newSlot['ulname'] = $provider_lname;
476 $newSlot['ufname'] = $provider_fname;
477 $newSlot['umname'] = $provider_mname;
478 $newSlot['pc_eventDate'] = $event_date;
479 $newSlot['pc_startTime'] = $start_time;
480 $newSlot['pc_endTime'] = $start_time;
481 $newSlot['pc_catname'] = $cat_name;
485 function getCompareFunction($code)
487 global $COMPARE_FUNCTION_HASH;
488 return $COMPARE_FUNCTION_HASH[$code];
491 function getComparisonOrder($code)
494 return $ORDERHASH[$code];
498 function sortAppointments(array $appointments, $orderBy = 'date')
500 global $appointment_sort_order;
501 $appointment_sort_order = $orderBy;
502 usort($appointments, "compareAppointments");
503 return $appointments;
506 // cmp_function for usort
507 // The comparison function must return an integer less than, equal to,
508 // or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
509 function compareAppointments($appointment1, $appointment2)
511 global $appointment_sort_order;
512 $comparisonOrder = getComparisonOrder($appointment_sort_order);
513 foreach ($comparisonOrder as $comparison) {
514 $cmp_function = getCompareFunction($comparison);
515 $result = $cmp_function($appointment1, $appointment2);
524 function compareBasic($e1, $e2)
528 } else if ($e1 > $e2) {
535 function compareAppointmentsByDate($appointment1, $appointment2)
537 $date1 = strtotime($appointment1['pc_eventDate']);
538 $date2 = strtotime($appointment2['pc_eventDate']);
540 return compareBasic($date1, $date2);
543 function compareAppointmentsByTime($appointment1, $appointment2)
545 $time1 = strtotime($appointment1['pc_startTime']);
546 $time2 = strtotime($appointment2['pc_startTime']);
548 return compareBasic($time1, $time2);
551 function compareAppointmentsByDoctorName($appointment1, $appointment2)
553 $name1 = $appointment1['ulname'];
554 $name2 = $appointment2['ulname'];
555 $cmp = compareBasic($name1, $name2);
557 $name1 = $appointment1['ufname'];
558 $name2 = $appointment2['ufname'];
559 return compareBasic($name1, $name2);
565 function compareAppointmentsByPatientName($appointment1, $appointment2)
567 $name1 = $appointment1['lname'];
568 $name2 = $appointment2['lname'];
569 $cmp = compareBasic($name1, $name2);
571 $name1 = $appointment1['fname'];
572 $name2 = $appointment2['fname'];
573 return compareBasic($name1, $name2);
579 function compareAppointmentsByType($appointment1, $appointment2)
581 $type1 = $appointment1['pc_catid'];
582 $type2 = $appointment2['pc_catid'];
583 return compareBasic($type1, $type2);
586 function compareAppointmentsByPatientId($appointment1, $appointment2)
588 $id1 = $appointment1['pubpid'];
589 $id2 = $appointment2['pubpid'];
590 return compareBasic($id1, $id2);
593 function compareAppointmentsByComment($appointment1, $appointment2)
595 $comment1 = $appointment1['pc_hometext'];
596 $comment2 = $appointment2['pc_hometext'];
597 return compareBasic($comment1, $comment2);
600 function compareAppointmentsByStatus($appointment1, $appointment2)
602 $status1 = $appointment1['pc_apptstatus'];
603 $status2 = $appointment2['pc_apptstatus'];
604 return compareBasic($status1, $status2);
607 function compareAppointmentsByTrackerStatus($appointment1, $appointment2)
609 $trackerstatus1 = $appointment1['status'];
610 $trackerstatus2 = $appointment2['status'];
611 return compareBasic($trackerstatus1, $trackerstatus2);
614 function compareAppointmentsByCompletedDrugScreen($appointment1, $appointment2)
616 $completed1 = $appointment1['drug_screen_completed'];
617 $completed2 = $appointment2['drug_screen_completed'];
618 return compareBasic($completed1, $completed2);
621 function fetchAppointmentCategories()
623 $catSQL= " SELECT pc_catid as id, pc_catname as category "
624 . " FROM openemr_postcalendar_categories WHERE pc_recurrtype=0 and pc_cattype=0";
625 if ($GLOBALS['enable_group_therapy']) {
626 $catSQL .= " OR pc_cattype=3";
629 $catSQL .= " ORDER BY category";
630 return sqlStatement($catSQL);
633 function interpretRecurrence($recurr_freq, $recurr_type)
635 global $REPEAT_FREQ, $REPEAT_FREQ_TYPE, $REPEAT_ON_NUM, $REPEAT_ON_DAY;
637 $recurr_freq = unserialize($recurr_freq);
638 if ($recurr_type == 1) {
639 $interpreted = $REPEAT_FREQ[$recurr_freq['event_repeat_freq']];
640 $interpreted .= " " . $REPEAT_FREQ_TYPE[$recurr_freq['event_repeat_freq_type']];
641 } elseif ($recurr_type == 2) {
642 $interpreted = $REPEAT_FREQ[$recurr_freq['event_repeat_on_freq']];
643 $interpreted .= " " . $REPEAT_ON_NUM[$recurr_freq['event_repeat_on_num']];
644 $interpreted .= " " . $REPEAT_ON_DAY[$recurr_freq['event_repeat_on_day']];
645 } elseif ($recurr_type == 3) {
646 $interpreted = $REPEAT_FREQ[1];
648 $day_arr = explode(",", $recurr_freq['event_repeat_freq']);
649 foreach ($day_arr as $day) {
650 $interpreted .= $comma . " " . $REPEAT_ON_DAY[$day - 1];
658 function fetchRecurrences($pid)
660 $query = "SELECT pe.pc_title, pe.pc_endDate, pe.pc_recurrtype, pe.pc_recurrspec, pc.pc_catname FROM openemr_postcalendar_events AS pe "
661 . "JOIN openemr_postcalendar_categories AS pc ON pe.pc_catid=pc.pc_catid "
662 . "WHERE pe.pc_pid = ? AND pe.pc_recurrtype > 0;";
663 $sqlBindArray = array();
664 array_push($sqlBindArray, $pid);
665 $res = sqlStatement($query, $sqlBindArray);
667 while ($res_arr[$row] = sqlFetchArray($res)) {
668 $res_arr[$row]['pc_recurrspec'] = interpretRecurrence($res_arr[$row]['pc_recurrspec'], $res_arr[$row]['pc_recurrtype']);
675 function ends_in_a_week($end_date)
677 $timestamp_in_a_week = strtotime('+7 day');
678 $timestamp_end_date = strtotime($end_date);
679 if ($timestamp_in_a_week > $timestamp_end_date) {
680 return true; //ends in a week
683 return false; // ends in more than a week
686 //Checks if recurrence is current (didn't end yet).
687 function recurrence_is_current($end_date)
689 $end_date_timestamp = strtotime($end_date);
690 $current_timestamp = time();
691 if ($current_timestamp <= $end_date_timestamp) {
692 return true; //recurrence is current