prepping ubuntu packages
[openemr.git] / library / appointments.inc.php
blobb424ffdfd7e67f3c2afc9adb3f0f862a16a47d6b
1 <?php
3 // Copyright (C) 2011 Ken Chapple
4 //
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 ////////////
15 require_once(dirname(__FILE__)."/encounter_events.inc.php");
16 require_once(dirname(__FILE__)."/../interface/main/calendar/modules/PostCalendar/pnincludes/Date/Calc.php");
17 ////////////
20 $COMPARE_FUNCTION_HASH = array(
21 'doctor' => 'compareAppointmentsByDoctorName',
22 'patient' => 'compareAppointmentsByPatientName',
23 'pubpid' => 'compareAppointmentsByPatientId',
24 'date' => 'compareAppointmentsByDate',
25 'time' => 'compareAppointmentsByTime',
26 'type' => 'compareAppointmentsByType',
27 'comment' => 'compareAppointmentsByComment',
28 'status' => 'compareAppointmentsByStatus',
29 'completed' => 'compareAppointmentsByCompletedDrugScreen',
30 'trackerstatus' => 'compareAppointmentsByTrackerStatus'
33 $ORDERHASH = array(
34 'doctor' => array( 'doctor', 'date', 'time' ),
35 'patient' => array( 'patient', 'date', 'time' ),
36 'pubpid' => array( 'pubpid', 'date', 'time' ),
37 'date' => array( 'date', 'time', 'type', 'patient' ),
38 'time' => array( 'time', 'date', 'patient' ),
39 'type' => array( 'type', 'date', 'time', 'patient' ),
40 'comment' => array( 'comment', 'date', 'time', 'patient' ),
41 'status' => array( 'status', 'date', 'time', 'patient' ),
42 'completed' => array( 'completed', 'date', 'time', 'patient' ),
43 'trackerstatus' => array( 'trackerstatus', 'date', 'time', 'patient' ),
46 function fetchEvents( $from_date, $to_date, $where_param = null, $orderby_param = null, $tracker_board = false, $nextX = 0 )
48 //////
49 if($nextX) {
51 $where =
52 "((e.pc_endDate >= '$from_date' AND e.pc_recurrtype > '0') OR " .
53 "(e.pc_eventDate >= '$from_date'))";
55 } else {
56 //////
57 $where =
58 "((e.pc_endDate >= '$from_date' AND e.pc_eventDate <= '$to_date' AND e.pc_recurrtype > '0') OR " .
59 "(e.pc_eventDate >= '$from_date' AND e.pc_eventDate <= '$to_date'))";
63 if ( $where_param ) $where .= $where_param;
65 $order_by = "e.pc_eventDate, e.pc_startTime";
66 if ( $orderby_param ) {
67 $order_by = $orderby_param;
70 // Tracker Board specific stuff
71 $tracker_fields = '';
72 $tracker_joins = '';
73 if ($tracker_board) {
74 $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, " .
75 "q.pt_tracker_id, q.start_datetime, q.room, q.status, q.seq, q.user, " .
76 "s.toggle_setting_1, s.toggle_setting_2, s.option_id, " ;
77 $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 " .
78 "LEFT OUTER JOIN patient_tracker_element AS q ON q.pt_tracker_id = t.id AND q.seq = t.lastseq " .
79 "LEFT OUTER JOIN list_options AS s ON s.list_id = 'apptstat' AND s.option_id = q.status " ;
82 $query = "SELECT " .
83 "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, " .
84 "e.pc_title, e.pc_hometext, e.pc_apptstatus, " .
85 "p.fname, p.mname, p.lname, p.pid, p.pubpid, p.phone_home, p.phone_cell, " .
86 "u.fname AS ufname, u.mname AS umname, u.lname AS ulname, u.id AS uprovider_id, " .
87 "$tracker_fields" .
88 "c.pc_catname, c.pc_catid " .
89 "FROM openemr_postcalendar_events AS e " .
90 "$tracker_joins" .
91 "LEFT OUTER JOIN patient_data AS p ON p.pid = e.pc_pid " .
92 "LEFT OUTER JOIN users AS u ON u.id = e.pc_aid " .
93 "LEFT OUTER JOIN openemr_postcalendar_categories AS c ON c.pc_catid = e.pc_catid " .
94 "WHERE $where " .
95 "ORDER BY $order_by";
98 ///////////////////////////////////////////////////////////////////////
99 // The following code is from the calculateEvents function in the
100 // PostCalendar Module modified and inserted here by epsdky
102 $events2 = array();
103 $res = sqlStatement($query);
104 ////////
105 if($nextX) {
106 global $resNotNull;
107 $resNotNull = (isset($res) && $res != null);
110 while ($event = sqlFetchArray($res)) {
111 ///////
112 if($nextX) $stopDate = $event['pc_endDate'];
113 else $stopDate = ($event['pc_endDate'] <= $to_date) ? $event['pc_endDate'] : $to_date;
114 ///////
115 $incX = 0;
116 switch($event['pc_recurrtype']) {
118 case '0' :
120 $events2[] = $event;
122 break;
123 //////
124 case '1' :
126 $event_recurrspec = @unserialize($event['pc_recurrspec']);
128 $rfreq = $event_recurrspec['event_repeat_freq'];
129 $rtype = $event_recurrspec['event_repeat_freq_type'];
130 $exdate = $event_recurrspec['exdate'];
132 list($ny,$nm,$nd) = explode('-',$event['pc_eventDate']);
133 // $occurance = Date_Calc::dateFormat($nd,$nm,$ny,'%Y-%m-%d');
134 $occurance = $event['pc_eventDate'];
136 while($occurance < $from_date) {
137 $occurance =& __increment($nd,$nm,$ny,$rfreq,$rtype);
138 list($ny,$nm,$nd) = explode('-',$occurance);
141 while($occurance <= $stopDate) {
143 $excluded = false;
144 if (isset($exdate)) {
145 foreach (explode(",", $exdate) as $exception) {
146 // occurrance format == yyyy-mm-dd
147 // exception format == yyyymmdd
148 if (preg_replace("/-/", "", $occurance) == $exception) {
149 $excluded = true;
154 if ($excluded == false) {
155 $event['pc_eventDate'] = $occurance;
156 $event['pc_endDate'] = '0000-00-00';
157 $events2[] = $event;
158 //////
159 if ($nextX) {
160 ++$incX;
161 if($incX == $nextX) break;
163 //////
166 $occurance =& __increment($nd,$nm,$ny,$rfreq,$rtype);
167 list($ny,$nm,$nd) = explode('-',$occurance);
171 break;
173 //////
174 case '2' :
176 $event_recurrspec = @unserialize($event['pc_recurrspec']);
178 $rfreq = $event_recurrspec['event_repeat_on_freq'];
179 $rnum = $event_recurrspec['event_repeat_on_num'];
180 $rday = $event_recurrspec['event_repeat_on_day'];
181 $exdate = $event_recurrspec['exdate'];
183 list($ny,$nm,$nd) = explode('-',$event['pc_eventDate']);
185 $occuranceYm = "$ny-$nm"; // YYYY-mm
186 $from_dateYm = substr($from_date,0,7); // YYYY-mm
187 $stopDateYm = substr($stopDate,0,7); // YYYY-mm
189 // $nd will sometimes be 29, 30 or 31, and if used in mktime below, a problem
190 // with overflow will occur ('01' should be plugged in to avoid this). We need
191 // to mirror the calendar code which has this problem, so $nd has been used.
192 while($occuranceYm < $from_dateYm) {
193 $occuranceYmX = date('Y-m-d',mktime(0,0,0,$nm+$rfreq,$nd,$ny));
194 list($ny,$nm,$nd) = explode('-',$occuranceYmX);
195 $occuranceYm = "$ny-$nm";
198 while($occuranceYm <= $stopDateYm) {
200 // (YYYY-mm)-dd
201 $dnum = $rnum;
202 do {
203 $occurance = Date_Calc::NWeekdayOfMonth($dnum--,$rday,$nm,$ny,$format="%Y-%m-%d");
204 } while($occurance === -1);
206 if($occurance >= $from_date && $occurance <= $stopDate) {
208 $excluded = false;
209 if (isset($exdate)) {
210 foreach (explode(",", $exdate) as $exception) {
211 // occurrance format == yyyy-mm-dd
212 // exception format == yyyymmdd
213 if (preg_replace("/-/", "", $occurance) == $exception) {
214 $excluded = true;
219 if ($excluded == false) {
221 $event['pc_eventDate'] = $occurance;
222 $event['pc_endDate'] = '0000-00-00';
223 $events2[] = $event;
224 //////
225 if($nextX) {
226 ++$incX;
227 if($incX == $nextX) break;
229 //////
235 $occuranceYmX = date('Y-m-d',mktime(0,0,0,$nm+$rfreq,$nd,$ny));
236 list($ny,$nm,$nd) = explode('-',$occuranceYmX);
237 $occuranceYm = "$ny-$nm";
241 break;
246 return $events2;
247 ////////////////////// End of code inserted by epsdky
249 //////////////////////
251 function fetchAllEvents( $from_date, $to_date, $provider_id = null, $facility_id = null )
253 $where = "";
254 if ( $provider_id ) $where .= " AND e.pc_aid = '$provider_id'";
256 $facility_filter = '';
257 if ( $facility_id ) {
258 $event_facility_filter = " AND e.pc_facility = '" . add_escape_custom($facility_id) . "'"; //escape $facility_id
259 $provider_facility_filter = " AND u.facility_id = '" . add_escape_custom($facility_id) . "'"; //escape $facility_id
260 $facility_filter = $event_facility_filter . $provider_facility_filter;
263 $where .= $facility_filter;
264 $appointments = fetchEvents( $from_date, $to_date, $where );
265 return $appointments;
268 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 )
270 $where = "";
271 if ( $provider_id ) $where .= " AND e.pc_aid = '$provider_id'";
272 if ( $patient_id ) {
273 $where .= " AND e.pc_pid = '$patient_id'";
274 } else {
275 $where .= " AND e.pc_pid != ''";
278 $facility_filter = '';
279 if ( $facility_id ) {
280 $event_facility_filter = " AND e.pc_facility = '" . add_escape_custom($facility_id) . "'"; // escape $facility_id
281 $provider_facility_filter = " AND u.facility_id = '" . add_escape_custom($facility_id) . "'"; // escape $facility_id
282 $facility_filter = $event_facility_filter . $provider_facility_filter;
285 $where .= $facility_filter;
287 //Appointment Status Checking
288 $filter_appstatus = '';
289 if($pc_appstatus != ''){
290 $filter_appstatus = " AND e.pc_apptstatus = '".$pc_appstatus."'";
292 $where .= $filter_appstatus;
294 if($pc_catid !=null)
296 $where .= " AND e.pc_catid=".intval($pc_catid); // using intval to escape this parameter
299 //Without Provider checking
300 $filter_woprovider = '';
301 if($with_out_provider != ''){
302 $filter_woprovider = " AND e.pc_aid = ''";
304 $where .= $filter_woprovider;
306 //Without Facility checking
307 $filter_wofacility = '';
308 if($with_out_facility != ''){
309 $filter_wofacility = " AND e.pc_facility = 0";
311 $where .= $filter_wofacility;
313 $appointments = fetchEvents( $from_date, $to_date, $where, '', $tracker_board, $nextX );
314 return $appointments;
317 function fetchNextXAppts($from_date, $patient_id, $nextX = 1) {
319 $appts = array();
320 $nextXAppts = array();
321 $appts = fetchAppointments( $from_date, null, $patient_id, null, null, null, null, null, null, false, $nextX );
322 if($appts) {
323 $appts = sortAppointments($appts);
324 $nextXAppts = array_slice($appts, 0, $nextX);
326 return $nextXAppts;
330 // get the event slot size in seconds
331 function getSlotSize()
333 if ( isset( $GLOBALS['calendar_interval'] ) ) {
334 return $GLOBALS['calendar_interval'] * 60;
336 return 15 * 60;
339 function getAvailableSlots( $from_date, $to_date, $provider_id = null, $facility_id = null )
341 $appointments = fetchAllEvents( $from_date, $to_date, $provider_id, $facility_id );
342 $appointments = sortAppointments( $appointments, "date" );
343 $from_datetime = strtotime( $from_date." 00:00:00" );
344 $to_datetime = strtotime( $to_date." 23:59:59" );
345 $availableSlots = array();
346 $start_time = 0;
347 $date = 0;
348 for ( $i = 0; $i < count( $appointments ); ++$i )
350 if ( $appointments[$i]['pc_catid'] == 2 ) { // 2 == In Office
351 $start_time = $appointments[$i]['pc_startTime'];
352 $date = $appointments[$i]['pc_eventDate'];
353 $provider_id = $appointments[$i]['uprovider_id'];
354 } else if ( $appointments[$i]['pc_catid'] == 3 ) { // 3 == Out Of Office
355 continue;
356 } else {
357 $start_time = $appointments[$i]['pc_endTime'];
358 $date = $appointments[$i]['pc_eventDate'];
359 $provider_id = $appointments[$i]['uprovider_id'];
362 // find next appointment with the same provider
363 $next_appointment_date = 0;
364 $next_appointment_time = 0;
365 for ( $j = $i+1; $j < count( $appointments ); ++$j ) {
366 if ( $appointments[$j]['uprovider_id'] == $provider_id ) {
367 $next_appointment_date = $appointments[$j]['pc_eventDate'];
368 $next_appointment_time = $appointments[$j]['pc_startTime'];
369 break;
373 $same_day = ( strtotime( $next_appointment_date ) == strtotime( $date ) ) ? true : false;
375 if ( $next_appointment_time && $same_day ) {
376 // check the start time of the next appointment
378 $start_datetime = strtotime( $date." ".$start_time );
379 $next_appointment_datetime = strtotime( $next_appointment_date." ".$next_appointment_time );
380 $curr_time = $start_datetime;
381 while ( $curr_time < $next_appointment_datetime - (getSlotSize() / 2) ) {
382 //create a new appointment ever 15 minutes
383 $time = date( "H:i:s", $curr_time );
384 $available_slot = createAvailableSlot(
385 $appointments[$i]['pc_eventDate'],
386 $time,
387 $appointments[$i]['ufname'],
388 $appointments[$i]['ulname'],
389 $appointments[$i]['umname'] );
390 $availableSlots []= $available_slot;
391 $curr_time += getSlotSize(); // add a 15-minute slot
396 return $availableSlots;
399 function createAvailableSlot( $event_date, $start_time, $provider_fname, $provider_lname, $provider_mname = "", $cat_name = "Available" )
401 $newSlot = array();
402 $newSlot['ulname'] = $provider_lname;
403 $newSlot['ufname'] = $provider_fname;
404 $newSlot['umname'] = $provider_mname;
405 $newSlot['pc_eventDate'] = $event_date;
406 $newSlot['pc_startTime'] = $start_time;
407 $newSlot['pc_endTime'] = $start_time;
408 $newSlot['pc_catname'] = $cat_name;
409 return $newSlot;
412 function getCompareFunction( $code ) {
413 global $COMPARE_FUNCTION_HASH;
414 return $COMPARE_FUNCTION_HASH[$code];
417 function getComparisonOrder( $code ) {
418 global $ORDERHASH;
419 return $ORDERHASH[$code];
423 function sortAppointments( array $appointments, $orderBy = 'date' )
425 global $appointment_sort_order;
426 $appointment_sort_order = $orderBy;
427 usort( $appointments, "compareAppointments" );
428 return $appointments;
431 // cmp_function for usort
432 // The comparison function must return an integer less than, equal to,
433 // or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
434 function compareAppointments( $appointment1, $appointment2 )
436 global $appointment_sort_order;
437 $comparisonOrder = getComparisonOrder( $appointment_sort_order );
438 foreach ( $comparisonOrder as $comparison )
440 $cmp_function = getCompareFunction( $comparison );
441 $result = $cmp_function( $appointment1, $appointment2 );
442 if ( 0 != $result ) {
443 return $result;
447 return 0;
450 function compareBasic( $e1, $e2 )
452 if ( $e1 < $e2 ) {
453 return -1;
454 } else if ( $e1 > $e2 ) {
455 return 1;
458 return 0;
461 function compareAppointmentsByDate( $appointment1, $appointment2 )
463 $date1 = strtotime( $appointment1['pc_eventDate'] );
464 $date2 = strtotime( $appointment2['pc_eventDate'] );
466 return compareBasic( $date1, $date2 );
469 function compareAppointmentsByTime( $appointment1, $appointment2 )
471 $time1 = strtotime( $appointment1['pc_startTime'] );
472 $time2 = strtotime( $appointment2['pc_startTime'] );
474 return compareBasic( $time1, $time2 );
477 function compareAppointmentsByDoctorName( $appointment1, $appointment2 )
479 $name1 = $appointment1['ulname'];
480 $name2 = $appointment2['ulname'];
481 $cmp = compareBasic( $name1, $name2 );
482 if ( $cmp == 0 ) {
483 $name1 = $appointment1['ufname'];
484 $name2 = $appointment2['ufname'];
485 return compareBasic( $name1, $name2 );
488 return $cmp;
491 function compareAppointmentsByPatientName( $appointment1, $appointment2 )
493 $name1 = $appointment1['lname'];
494 $name2 = $appointment2['lname'];
495 $cmp = compareBasic( $name1, $name2 );
496 if ( $cmp == 0 ) {
497 $name1 = $appointment1['fname'];
498 $name2 = $appointment2['fname'];
499 return compareBasic( $name1, $name2 );
502 return $cmp;
505 function compareAppointmentsByType( $appointment1, $appointment2 )
507 $type1 = $appointment1['pc_catid'];
508 $type2 = $appointment2['pc_catid'];
509 return compareBasic( $type1, $type2 );
512 function compareAppointmentsByPatientId( $appointment1, $appointment2 )
514 $id1 = $appointment1['pubpid'];
515 $id2 = $appointment2['pubpid'];
516 return compareBasic( $id1, $id2 );
519 function compareAppointmentsByComment( $appointment1, $appointment2 )
521 $comment1 = $appointment1['pc_hometext'];
522 $comment2 = $appointment2['pc_hometext'];
523 return compareBasic( $comment1, $comment2 );
526 function compareAppointmentsByStatus( $appointment1, $appointment2 )
528 $status1 = $appointment1['pc_apptstatus'];
529 $status2 = $appointment2['pc_apptstatus'];
530 return compareBasic( $status1, $status2 );
533 function compareAppointmentsByTrackerStatus( $appointment1, $appointment2 )
535 $trackerstatus1 = $appointment1['status'];
536 $trackerstatus2 = $appointment2['status'];
537 return compareBasic( $trackerstatus1, $trackerstatus2 );
540 function compareAppointmentsByCompletedDrugScreen( $appointment1, $appointment2 )
542 $completed1 = $appointment1['drug_screen_completed'];
543 $completed2 = $appointment2['drug_screen_completed'];
544 return compareBasic( $completed1, $completed2 );
547 function fetchAppointmentCategories()
549 $catSQL= " SELECT pc_catid as id, pc_catname as category "
550 . " FROM openemr_postcalendar_categories WHERE pc_recurrtype=0 and pc_cattype=0 ORDER BY category";
551 return sqlStatement($catSQL);