MDL-11517 reserved word MOD used in table alias in questions backup code
[moodle-pu.git] / calendar / lib.php
bloba0f03139359e33341afe678a7a563e5ce41704cf
1 <?php // $Id$
3 /////////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Calendar extension //
8 // //
9 // Copyright (C) 2003-2004 Greek School Network www.sch.gr //
10 // //
11 // Designed by: //
12 // Avgoustos Tsinakos (tsinakos@teikav.edu.gr) //
13 // Jon Papaioannou (pj@moodle.org) //
14 // //
15 // Programming and development: //
16 // Jon Papaioannou (pj@moodle.org) //
17 // //
18 // For bugs, suggestions, etc contact: //
19 // Jon Papaioannou (pj@moodle.org) //
20 // //
21 // The current module was developed at the University of Macedonia //
22 // (www.uom.gr) under the funding of the Greek School Network (www.sch.gr) //
23 // The aim of this project is to provide additional and improved //
24 // functionality to the Asynchronous Distance Education service that the //
25 // Greek School Network deploys. //
26 // //
27 // This program is free software; you can redistribute it and/or modify //
28 // it under the terms of the GNU General Public License as published by //
29 // the Free Software Foundation; either version 2 of the License, or //
30 // (at your option) any later version. //
31 // //
32 // This program is distributed in the hope that it will be useful, //
33 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
34 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
35 // GNU General Public License for more details: //
36 // //
37 // http://www.gnu.org/copyleft/gpl.html //
38 // //
39 /////////////////////////////////////////////////////////////////////////////
41 // These are read by the administration component to provide default values
42 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
43 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
44 define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
45 // This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
46 // Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
47 define('CALENDAR_DEFAULT_WEEKEND', 65);
49 // Fetch the correct values from admin settings/lang pack
50 // If no such settings found, use the above defaults
51 $firstday = isset($CFG->calendar_startwday) ? $CFG->calendar_startwday : get_string('firstdayofweek');
52 if(!is_numeric($firstday)) {
53 define ('CALENDAR_STARTING_WEEKDAY', CALENDAR_DEFAULT_STARTING_WEEKDAY);
55 else {
56 define ('CALENDAR_STARTING_WEEKDAY', intval($firstday) % 7);
58 define ('CALENDAR_UPCOMING_DAYS', isset($CFG->calendar_lookahead) ? intval($CFG->calendar_lookahead) : CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD);
59 define ('CALENDAR_UPCOMING_MAXEVENTS', isset($CFG->calendar_maxevents) ? intval($CFG->calendar_maxevents) : CALENDAR_DEFAULT_UPCOMING_MAXEVENTS);
60 define ('CALENDAR_WEEKEND', isset($CFG->calendar_weekend) ? intval($CFG->calendar_weekend) : CALENDAR_DEFAULT_WEEKEND);
61 define ('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
62 define ('CALENDAR_TF_24', '%H:%M');
63 define ('CALENDAR_TF_12', '%I:%M %p');
65 define ('CALENDAR_MAXCOURSES', 3);
67 $CALENDARDAYS = array('sunday','monday','tuesday','wednesday','thursday','friday','saturday');
71 function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_year = false) {
72 global $CFG, $USER;
74 $display = &New stdClass;
75 $display->minwday = get_user_preferences('calendar_startwday', CALENDAR_STARTING_WEEKDAY);
76 $display->maxwday = $display->minwday + 6;
78 $content = '';
80 if(!empty($cal_month) && !empty($cal_year)) {
81 $thisdate = usergetdate(time()); // Date and time the user sees at his location
82 if($cal_month == $thisdate['mon'] && $cal_year == $thisdate['year']) {
83 // Navigated to this month
84 $date = $thisdate;
85 $display->thismonth = true;
87 else {
88 // Navigated to other month, let's do a nice trick and save us a lot of work...
89 if(!checkdate($cal_month, 1, $cal_year)) {
90 $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']);
91 $display->thismonth = true;
93 else {
94 $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year);
95 $display->thismonth = false;
99 else {
100 $date = usergetdate(time()); // Date and time the user sees at his location
101 $display->thismonth = true;
104 // Fill in the variables we 're going to use, nice and tidy
105 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display
106 $display->maxdays = calendar_days_in_month($m, $y);
108 if (get_user_timezone_offset() < 99) {
109 // We 'll keep these values as GMT here, and offset them when the time comes to query the db
110 $display->tstart = gmmktime(0, 0, 0, $m, 1, $y); // This is GMT
111 $display->tend = gmmktime(23, 59, 59, $m, $display->maxdays, $y); // GMT
112 } else {
113 // no timezone info specified
114 $display->tstart = mktime(0, 0, 0, $m, 1, $y);
115 $display->tend = mktime(23, 59, 59, $m, $display->maxdays, $y);
118 $startwday = dayofweek(1, $m, $y);
120 // Align the starting weekday to fall in our display range
121 // This is simple, not foolproof.
122 if($startwday < $display->minwday) {
123 $startwday += 7;
126 // TODO: THIS IS TEMPORARY CODE!
127 // [pj] I was just reading through this and realized that I when writing this code I was probably
128 // asking for trouble, as all these time manipulations seem to be unnecessary and a simple
129 // make_timestamp would accomplish the same thing. So here goes a test:
130 //$test_start = make_timestamp($y, $m, 1);
131 //$test_end = make_timestamp($y, $m, $display->maxdays, 23, 59, 59);
132 //if($test_start != usertime($display->tstart) - dst_offset_on($display->tstart)) {
133 //notify('Failed assertion in calendar/lib.php line 126; display->tstart = '.$display->tstart.', dst_offset = '.dst_offset_on($display->tstart).', usertime = '.usertime($display->tstart).', make_t = '.$test_start);
135 //if($test_end != usertime($display->tend) - dst_offset_on($display->tend)) {
136 //notify('Failed assertion in calendar/lib.php line 130; display->tend = '.$display->tend.', dst_offset = '.dst_offset_on($display->tend).', usertime = '.usertime($display->tend).', make_t = '.$test_end);
140 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
141 $whereclause = calendar_sql_where(
142 usertime($display->tstart) - dst_offset_on($display->tstart),
143 usertime($display->tend) - dst_offset_on($display->tend),
144 $users, $groups, $courses);
146 if($whereclause === false) {
147 $events = array();
149 else {
150 $events = get_records_select('event', $whereclause, 'timestart');
153 // Set event course class for course events
154 if (!empty($events)) {
155 foreach ($events as $eventid => $event) {
156 if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
157 $event->class = 'event_course'.array_search($event->courseid, $courses) % CALENDAR_MAXCOURSES;
159 if (!empty($event->modulename)) {
160 $cm = get_coursemodule_from_instance($event->modulename, $event->instance);
161 if (!groups_course_module_visible($cm)) {
162 unset($events[$eventid]);
168 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
169 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
170 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
171 // arguments to this function.
173 $morehref = '';
174 if(!empty($courses)) {
175 $courses = array_diff($courses, array(SITEID));
176 if(count($courses) == 1) {
177 $morehref = '&amp;course='.reset($courses);
181 // We want to have easy access by day, since the display is on a per-day basis.
182 // Arguments passed by reference.
183 //calendar_events_by_day($events, $display->tstart, $eventsbyday, $durationbyday, $typesbyday);
184 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
186 //Accessibility: added summary and <abbr> elements.
187 ///global $CALENDARDAYS; appears to be broken.
188 $days_title = array('sunday','monday','tuesday','wednesday','thursday','friday','saturday');
190 $summary = get_string('calendarheading', 'calendar', userdate(make_timestamp($y, $m), get_string('strftimemonthyear')));
191 $summary = get_string('tabledata', 'access', $summary);
192 $content .= '<table class="minicalendar" summary="'.$summary.'">'; // Begin table
193 $content .= '<tr class="weekdays">'; // Header row: day names
195 // Print out the names of the weekdays
196 $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
197 for($i = $display->minwday; $i <= $display->maxwday; ++$i) {
198 // This uses the % operator to get the correct weekday no matter what shift we have
199 // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
200 $content .= '<th scope="col"><abbr title="'. get_string($days_title[$i % 7], 'calendar') .'">'.
201 get_string($days[$i % 7], 'calendar') ."</abbr></th>\n";
204 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
206 // For the table display. $week is the row; $dayweek is the column.
207 $dayweek = $startwday;
209 // Paddding (the first week may have blank days in the beginning)
210 for($i = $display->minwday; $i < $startwday; ++$i) {
211 $content .= '<td class="dayblank">&nbsp;</td>'."\n";
214 // Now display all the calendar
215 for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
216 if($dayweek > $display->maxwday) {
217 // We need to change week (table row)
218 $content .= '</tr><tr>';
219 $dayweek = $display->minwday;
222 // Reset vars
223 $cell = '';
224 if(CALENDAR_WEEKEND & (1 << ($dayweek % 7))) {
225 // Weekend. This is true no matter what the exact range is.
226 $class = 'weekend day';
228 else {
229 // Normal working day.
230 $class = 'day';
233 // Special visual fx if an event is defined
234 if(isset($eventsbyday[$day])) {
235 $dayhref = calendar_get_link_href(CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $day, $m, $y);
237 // OverLib popup
238 $popupcontent = '';
239 foreach($eventsbyday[$day] as $eventid) {
240 if (!isset($events[$eventid])) {
241 continue;
243 $event = $events[$eventid];
244 if(!empty($event->modulename)) {
245 $popupicon = $CFG->modpixpath.'/'.$event->modulename.'/icon.gif';
246 $popupalt = $event->modulename;
248 } else if ($event->courseid == SITEID) { // Site event
249 $popupicon = $CFG->pixpath.'/c/site.gif';
250 $popupalt = '';
251 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
252 $popupicon = $CFG->pixpath.'/c/course.gif';
253 $popupalt = '';
254 } else if ($event->groupid) { // Group event
255 $popupicon = $CFG->pixpath.'/c/group.gif';
256 $popupalt = '';
257 } else if ($event->userid) { // User event
258 $popupicon = $CFG->pixpath.'/c/user.gif';
259 $popupalt = '';
261 $popupcontent .= '<div><img class="icon" src="'.$popupicon.'" alt="'.$popupalt.'" /><a href="'.$dayhref.'#event_'.$event->id.'">'.format_string($event->name, true).'</a></div>';
264 //Accessibility: functionality moved to calendar_get_popup.
265 if($display->thismonth && $day == $d) {
266 $popup = calendar_get_popup(true, $events[$eventid]->timestart, $popupcontent);
267 } else {
268 $popup = calendar_get_popup(false, $events[$eventid]->timestart, $popupcontent);
271 // Class and cell content
272 if(isset($typesbyday[$day]['startglobal'])) {
273 $class .= ' event_global';
275 else if(isset($typesbyday[$day]['startcourse'])) {
276 $class .= ' event_course';
278 else if(isset($typesbyday[$day]['startgroup'])) {
279 $class .= ' event_group';
281 else if(isset($typesbyday[$day]['startuser'])) {
282 $class .= ' event_user';
284 $cell = '<a href="'.$dayhref.'" '.$popup.'>'.$day.'</a>';
286 else {
287 $cell = $day;
290 if(isset($typesbyday[$day]['durationglobal'])) {
291 $class .= ' duration_global';
293 else if(isset($typesbyday[$day]['durationcourse'])) {
294 $class .= ' duration_course';
296 else if(isset($typesbyday[$day]['durationgroup'])) {
297 $class .= ' duration_group';
299 else if(isset($typesbyday[$day]['durationuser'])) {
300 $class .= ' duration_user';
303 // If event has a class set then add it to the table day <td> tag
304 // Note: only one colour for minicalendar
305 if(isset($eventsbyday[$day])) {
306 foreach($eventsbyday[$day] as $eventid) {
307 if (!isset($events[$eventid])) {
308 continue;
310 $event = $events[$eventid];
311 if (!empty($event->class)) {
312 $class .= ' '.$event->class;
314 break;
318 // Special visual fx for today
319 //Accessibility: hidden text for today, and popup.
320 if($display->thismonth && $day == $d) {
321 $class .= ' today';
322 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
324 if(! isset($eventsbyday[$day])) {
325 $class .= ' eventnone';
326 $popup = calendar_get_popup(true, false);
327 $cell = '<a href="#" '.$popup.'>'.$day.'</a>';
329 $cell = '<span class="accesshide">'.$today.' </span>'.$cell;
332 // Just display it
333 if(!empty($class)) {
334 $class = ' class="'.$class.'"';
336 $content .= '<td'.$class.'>'.$cell."</td>\n";
339 // Paddding (the last week may have blank days at the end)
340 for($i = $dayweek; $i <= $display->maxwday; ++$i) {
341 $content .= '<td class="dayblank">&nbsp;</td>';
343 $content .= '</tr>'; // Last row ends
345 $content .= '</table>'; // Tabular display of days ends
347 return $content;
351 * calendar_get_popup, called at multiple points in from calendar_get_mini.
352 * Copied and modified from calendar_get_mini.
353 * @uses OverLib popup.
354 * @param $is_today bool, false except when called on the current day.
355 * @param $event_timestart mixed, $events[$eventid]->timestart, OR false if there are no events.
356 * @param $popupcontent string.
357 * @return $popup string, contains onmousover and onmouseout events.
359 function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
360 $popupcaption = '';
361 if($is_today) {
362 $popupcaption = get_string('today', 'calendar').' ';
364 if (false === $event_timestart) {
365 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
366 $popupcontent = get_string('eventnone', 'calendar');
368 } else {
369 $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
371 $popupcontent = str_replace("'", "\'", htmlspecialchars($popupcontent));
372 $popupcaption = str_replace("'", "\'", htmlspecialchars($popupcaption));
373 $popup = 'onmouseover="return overlib(\''.$popupcontent.'\', CAPTION, \''.$popupcaption.'\');" onmouseout="return nd();"';
374 return $popup;
377 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
378 global $CFG;
380 $display = &new stdClass;
381 $display->range = $daysinfuture; // How many days in the future we 'll look
382 $display->maxevents = $maxevents;
384 $output = array();
386 // Prepare "course caching", since it may save us a lot of queries
387 $coursecache = array();
389 $processed = 0;
390 $now = time(); // We 'll need this later
391 $usermidnighttoday = usergetmidnight($now);
393 if ($fromtime) {
394 $display->tstart = $fromtime;
395 } else {
396 $display->tstart = $usermidnighttoday;
399 // This works correctly with respect to the user's DST, but it is accurate
400 // only because $fromtime is always the exact midnight of some day!
401 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
403 // Get the events matching our criteria
404 $whereclause = calendar_sql_where($display->tstart, $display->tend, $users, $groups, $courses);
405 if ($whereclause === false) {
406 $events = false;
407 } else {
408 $events = get_records_select('event', $whereclause, 'timestart');
411 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
412 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
413 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
414 // arguments to this function.
416 $morehref = '';
417 if(!empty($courses)) {
418 $courses = array_diff($courses, array(SITEID));
419 if(count($courses) == 1) {
420 $morehref = '&amp;course='.reset($courses);
424 if($events !== false) {
426 foreach($events as $event) {
427 if(!empty($event->modulename)) {
428 $mod = get_coursemodule_from_instance($event->modulename, $event->instance);
429 if (!groups_course_module_visible($mod)) {
430 continue;
434 if($processed >= $display->maxevents) {
435 break;
438 $event->time = calendar_format_event_time($event, $now, $morehref);
439 $output[] = $event;
440 ++$processed;
443 return $output;
446 function calendar_add_event_metadata($event) {
447 global $CFG;
449 //Support multilang in event->name
450 $event->name = format_string($event->name,true);
452 if(!empty($event->modulename)) { // Activity event
453 // The module name is set. I will assume that it has to be displayed, and
454 // also that it is an automatically-generated event. And of course that the
455 // fields for get_coursemodule_from_instance are set correctly.
456 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
458 if ($module === false) {
459 return;
462 $modulename = get_string('modulename', $event->modulename);
463 $eventtype = get_string($event->eventtype, $event->modulename);
464 $icon = $CFG->modpixpath.'/'.$event->modulename.'/icon.gif';
466 $event->icon = '<img height="16" width="16" src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" style="vertical-align: middle;" />';
467 $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
468 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$module->course.'">'.$coursecache[$module->course]->fullname.'</a>';
469 $event->cmid = $module->id;
472 } else if($event->courseid == SITEID) { // Site event
473 $event->icon = '<img height="16" width="16" src="'.$CFG->pixpath.'/c/site.gif" alt="'.get_string('globalevent', 'calendar').'" style="vertical-align: middle;" />';
474 $event->cssclass = 'event_global';
475 } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
476 calendar_get_course_cached($coursecache, $event->courseid);
477 $event->icon = '<img height="16" width="16" src="'.$CFG->pixpath.'/c/course.gif" alt="'.get_string('courseevent', 'calendar').'" style="vertical-align: middle;" />';
478 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$event->courseid.'">'.$coursecache[$event->courseid]->fullname.'</a>';
479 $event->cssclass = 'event_course';
480 } else if ($event->groupid) { // Group event
481 $event->icon = '<img height="16" width="16" src="'.$CFG->pixpath.'/c/group.gif" alt="'.get_string('groupevent', 'calendar').'" style="vertical-align: middle;" />';
482 $event->cssclass = 'event_group';
483 } else if($event->userid) { // User event
484 $event->icon = '<img height="16" width="16" src="'.$CFG->pixpath.'/c/user.gif" alt="'.get_string('userevent', 'calendar').'" style="vertical-align: middle;" />';
485 $event->cssclass = 'event_user';
487 return $event;
490 function calendar_print_event($event) {
491 global $CFG, $USER;
493 static $strftimetime;
495 $event = calendar_add_event_metadata($event);
496 echo '<a name="event_'.$event->id.'"></a><table class="event" cellspacing="0">';
497 echo '<tr><td class="picture">';
498 if (!empty($event->icon)) {
499 echo $event->icon;
500 } else {
501 print_spacer(16,16);
503 echo '</td>';
504 echo '<td class="topic">';
506 if (!empty($event->referer)) {
507 echo '<div class="referer">'.$event->referer.'</div>';
508 } else {
509 echo '<div class="name">'.$event->name."</div>";
511 if (!empty($event->courselink)) {
512 echo '<div class="course">'.$event->courselink.' </div>';
514 if (!empty($event->time)) {
515 echo '<span class="date">'.$event->time.'</span>';
516 } else {
517 echo '<span class="date">'.calendar_time_representation($event->timestart).'</span>';
520 echo '</td></tr>';
521 echo '<tr><td class="side">&nbsp;</td>';
523 // If event has a class set then add it to the event <td> tag
524 $eventclass='';
525 if (!empty($event->class)) {
526 $eventclass = ' '.$event->class;
529 if (isset($event->cssclass)) {
530 $eclass = $event->cssclass.$eventclass;
531 } else {
532 $eclass = $eventclass;
535 echo '<td class="description '.$eclass.'">';
536 echo format_text($event->description, FORMAT_HTML);
537 if (calendar_edit_event_allowed($event)) {
538 echo '<div class="commands">';
539 $calendarcourseid = '';
540 if (!empty($event->calendarcourseid)) {
541 $calendarcourseid = '&amp;course='.$event->calendarcourseid;
543 if (empty($event->cmid)) {
544 $editlink = CALENDAR_URL.'event.php?action=edit&amp;id='.$event->id.$calendarcourseid;
545 $deletelink = CALENDAR_URL.'event.php?action=delete&amp;id='.$event->id.$calendarcourseid;
546 } else {
547 $editlink = $CFG->wwwroot.'/course/mod.php?update='.$event->cmid.'&amp;return=true&amp;sesskey='.$USER->sesskey;
548 $deletelink = $CFG->wwwroot.'/course/mod.php?delete='.$event->cmid.'&amp;sesskey='.$USER->sesskey;;
550 echo ' <a href="'.$editlink.'"><img
551 src="'.$CFG->pixpath.'/t/edit.gif" alt="'.get_string('tt_editevent', 'calendar').'"
552 title="'.get_string('tt_editevent', 'calendar').'" /></a>';
553 echo ' <a href="'.$deletelink.'"><img
554 src="'.$CFG->pixpath.'/t/delete.gif" alt="'.get_string('tt_deleteevent', 'calendar').'"
555 title="'.get_string('tt_deleteevent', 'calendar').'" /></a>';
556 echo '</div>';
558 echo '</td></tr></table>';
562 function calendar_sql_where($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
563 $whereclause = '';
564 // Quick test
565 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
566 return false;
569 if(is_array($users) && !empty($users)) {
570 // Events from a number of users
571 if(!empty($whereclause)) $whereclause .= ' OR';
572 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
574 else if(is_numeric($users)) {
575 // Events from one user
576 if(!empty($whereclause)) $whereclause .= ' OR';
577 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
579 else if($users === true) {
580 // Events from ALL users
581 if(!empty($whereclause)) $whereclause .= ' OR';
582 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
584 else if($users === false) {
585 // No user at all, do nothing
588 if(is_array($groups) && !empty($groups)) {
589 // Events from a number of groups
590 if(!empty($whereclause)) $whereclause .= ' OR';
591 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
593 else if(is_numeric($groups)) {
594 // Events from one group
595 if(!empty($whereclause)) $whereclause .= ' OR ';
596 $whereclause .= ' groupid = '.$groups;
598 else if($groups === true) {
599 // Events from ALL groups
600 if(!empty($whereclause)) $whereclause .= ' OR ';
601 $whereclause .= ' groupid != 0';
603 // boolean false (no groups at all): we don't need to do anything
605 if(is_array($courses)) {
606 // A number of courses (maybe none at all!)
607 if(!empty($courses)) {
608 if(!empty($whereclause)) {
609 $whereclause .= ' OR';
611 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
613 else {
614 // This means NO courses, not that we don't care!
615 // No need to do anything
618 else if(is_numeric($courses)) {
619 // One course
620 if(!empty($whereclause)) $whereclause .= ' OR';
621 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
623 else if($courses === true) {
624 // Events from ALL courses
625 if(!empty($whereclause)) $whereclause .= ' OR';
626 $whereclause .= ' (groupid = 0 AND courseid != 0)';
629 // Security check: if, by now, we have NOTHING in $whereclause, then it means
630 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
631 // events no matter what. Allowing the code to proceed might return a completely
632 // valid query with only time constraints, thus selecting ALL events in that time frame!
633 if(empty($whereclause)) {
634 return false;
637 if($withduration) {
638 $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
640 else {
641 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
643 if(!empty($whereclause)) {
644 // We have additional constraints
645 $whereclause = $timeclause.' AND ('.$whereclause.')';
647 else {
648 // Just basic time filtering
649 $whereclause = $timeclause;
652 if ($ignorehidden) {
653 $whereclause .= ' AND visible = 1';
656 return $whereclause;
659 function calendar_top_controls($type, $data) {
660 global $CFG, $CALENDARDAYS, $THEME;
661 $content = '';
662 if(!isset($data['d'])) {
663 $data['d'] = 1;
666 // Ensure course id passed if relevant
667 // Required due to changes in view/lib.php mainly (calendar_session_vars())
668 $courseid = '';
669 if (!empty($data['id'])) {
670 $courseid = '&amp;course='.$data['id'];
673 if(!checkdate($data['m'], $data['d'], $data['y'])) {
674 $time = time();
676 else {
677 $time = make_timestamp($data['y'], $data['m'], $data['d']);
679 $date = usergetdate($time);
681 $data['m'] = $date['mon'];
682 $data['y'] = $date['year'];
684 //Accessibility: calendar block controls, replaced <table> with <div>.
685 //$nexttext = link_arrow_right(get_string('monthnext', 'access'), $url='', $accesshide=true);
686 //$prevtext = link_arrow_left(get_string('monthprev', 'access'), $url='', $accesshide=true);
688 switch($type) {
689 case 'frontpage':
690 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
691 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
692 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'index.php?', 0, $nextmonth, $nextyear, $accesshide=true);
693 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'index.php?', 0, $prevmonth, $prevyear, true);
694 $content .= "\n".'<div class="calendar-controls">'. $prevlink;
695 $content .= '<span class="hide"> | </span><span class="current"><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month'.$courseid.'&amp;', 1, $data['m'], $data['y']).'">'.userdate($time, get_string('strftimemonthyear')).'</a></span>';
696 $content .= '<span class="hide"> | </span>'. $nextlink ."\n";
697 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
698 break;
699 case 'course':
700 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
701 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
702 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $nextmonth, $nextyear, $accesshide=true);
703 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $prevmonth, $prevyear, true);
704 $content .= "\n".'<div class="calendar-controls">'. $prevlink;
705 $content .= '<span class="hide"> | </span><span class="current"><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month'.$courseid.'&amp;', 1, $data['m'], $data['y']).'">'.userdate($time, get_string('strftimemonthyear')).'</a></span>';
706 $content .= '<span class="hide"> | </span>'. $nextlink ."\n";
707 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
708 break;
709 case 'upcoming':
710 $content .= '<div style="text-align: center;"><a href="'.CALENDAR_URL.'view.php?view=upcoming"'.$courseid.'>'.userdate($time, get_string('strftimemonthyear'))."</a></div>\n";
711 break;
712 case 'display':
713 $content .= '<div style="text-align: center;"><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month'.$courseid.'&amp;', 1, $data['m'], $data['y']).'">'.userdate($time, get_string('strftimemonthyear'))."</a></div>\n";
714 break;
715 case 'month':
716 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
717 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
718 $prevdate = make_timestamp($prevyear, $prevmonth, 1);
719 $nextdate = make_timestamp($nextyear, $nextmonth, 1);
720 $content .= "\n".'<div class="calendar-controls">';
721 $content .= calendar_get_link_previous(userdate($prevdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $prevmonth, $prevyear);
722 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimemonthyear'))."</span>\n";
723 $content .= '<span class="hide"> | </span>'.calendar_get_link_next(userdate($nextdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $nextmonth, $nextyear);
724 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
725 break;
726 case 'day':
727 $data['d'] = $date['mday']; // Just for convenience
728 $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
729 $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] + 1));
730 $prevname = calendar_wday_name($CALENDARDAYS[$prevdate['wday']]);
731 $nextname = calendar_wday_name($CALENDARDAYS[$nextdate['wday']]);
732 $content .= "\n".'<div class="calendar-controls">';
733 $content .= calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&amp;', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
735 // Get the format string
736 $text = get_string('strftimedaydate');
738 // Regexp hackery to make a link out of the month/year part
739 $text = ereg_replace('(%B.+%Y|%Y.+%B|%Y.+%m[^ ]+)', '<a href="'.calendar_get_link_href('view.php?view=month&amp;', 1, $data['m'], $data['y']).'">\\1</a>', $text);
740 $text = ereg_replace('(F.+Y|Y.+F|Y.+m[^ ]+)', '<a href="'.calendar_get_link_href('view.php?view=month&amp;', 1, $data['m'], $data['y']).'">\\1</a>', $text);
742 // Replace with actual values and lose any day leading zero
743 $text = userdate($time, $text);
744 // Print the actual thing
745 $content .= '<span class="hide"> | </span><span class="current">'.$text.'</span>';
747 $content .= '<span class="hide"> | </span>'. calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&amp;', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);
748 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
749 break;
751 return $content;
754 function calendar_filter_controls($type, $vars = NULL, $course = NULL, $courses = NULL) {
755 global $CFG, $SESSION, $USER;
757 $groupevents = true;
758 $getvars = '';
760 $id = optional_param( 'id',0,PARAM_INT );
762 switch($type) {
763 case 'event':
764 case 'upcoming':
765 case 'day':
766 case 'month':
767 $getvars = '&amp;from='.$type;
768 break;
769 case 'course':
770 if ($id > 0) {
771 $getvars = '&amp;from=course&amp;id='.$id;
772 } else {
773 $getvars = '&amp;from=course';
775 if (isset($course->groupmode) and $course->groupmode == NOGROUPS and $course->groupmodeforce) {
776 $groupevents = false;
778 break;
781 if (!empty($vars)) {
782 $getvars .= '&amp;'.$vars;
785 $content = '<table>';
787 $content .= '<tr>';
788 if($SESSION->cal_show_global) {
789 $content .= '<td class="eventskey event_global" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hideglobal', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showglobal'.$getvars."'".'" /></td>';
790 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showglobal'.$getvars.'" title="'.get_string('tt_hideglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
792 else {
793 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showglobal', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showglobal'.$getvars."'".'" /></td>';
794 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showglobal'.$getvars.'" title="'.get_string('tt_showglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
796 $tr = '';
798 if(!empty($USER->id) && !isguest()) {
800 $content .= $tr;
801 $tr = $tr ? '' : "</tr>\n<tr>";
803 if($groupevents) {
805 // This course MIGHT have group events defined, so show the filter
806 if($SESSION->cal_show_groups) {
807 $content .= '<td class="eventskey event_group" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hidegroups', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showgroups'.$getvars."'".'" /></td>';
808 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showgroups'.$getvars.'" title="'.get_string('tt_hidegroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
809 } else {
810 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showgroups', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showgroups'.$getvars."'".'" /></td>';
811 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showgroups'.$getvars.'" title="'.get_string('tt_showgroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
813 } else {
815 // This course CANNOT have group events, so lose the filter
816 $content .= '<td style="width: 11px;"></td><td>&nbsp;</td>'."\n";
819 $content .= $tr;
820 $tr = $tr ? '' : "</tr>\n<tr>";
822 if ($SESSION->cal_show_user) {
823 $content .= '<td class="eventskey event_user" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hideuser', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showuser'.$getvars."'".'" /></td>';
824 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
825 } else {
826 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showuser', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showuser'.$getvars."'".'" /></td>';
827 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
831 // Remove global SITE ID from courses array as do not want to display this
832 if (!empty($courses)) {
833 $key = array_search(SITEID, $courses);
834 if ($key !== false) {
835 unset($courses[$key]);
839 if (empty($courses) || count($courses) == 1) {
841 // If not multiple courses then just display default single course colour highlighting
842 $content .= $tr;
843 $tr = $tr ? '' : "</tr>\n<tr>";
845 if($SESSION->cal_show_course) {
846 $content .= '<td class="eventskey event_course" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hidecourse', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showcourses'.$getvars."'".'" /></td>';
847 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_hidecourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
849 else {
850 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_showcourse', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showcourses'.$getvars."'".'" /></td>';
851 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_showcourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
853 } else {
855 // Otherwise display list of course shortnames and relevant colours
856 // Get list of course shortnames (Limit to 12 for now - who would have more than that?)
857 $select = 'id in ('.implode(',', $courses).')';
858 $sort = 'id';
859 $fields = 'id, shortname';
860 $courseshortnames = get_records_select('course', $select, $sort, $fields, 0, 12);
862 for ($i = 0; $i < CALENDAR_MAXCOURSES; $i++) {
864 // Concatenate shortnames if there are more than 3 courses
865 $strshortnames = '';
866 $n = 0;
867 for ($j = $i; $j < count($courses); $j += CALENDAR_MAXCOURSES) {
868 $strshortnames .= ', <a title="" href="'.$CFG->wwwroot.'/course/view.php?id='.$courses[$j].'">'.(!empty($courseshortnames[$courses[$j]]->shortname) ? $courseshortnames[$courses[$j]]->shortname : $courses[$j]).'</a>';
869 $n++;
872 if ($n) {
874 $content .= $tr;
875 $tr = $tr ? '' : "</tr>\n<tr>";
877 if ($n < 2) {
878 $strcourse = get_string('course', 'calendar');
879 } else {
880 $strcourse = get_string('courses', 'calendar');
883 if($SESSION->cal_show_course) {
884 $content .= '<td class="eventskey event_course'.$i.'" style="width: 11px;"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hidecourse', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showcourses'.$getvars."'".'" /></td>';
885 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_hidecourse', 'calendar').'">'.$strcourse.'</a>: '.substr($strshortnames, 2).'</td>'."\n";
887 else {
888 $content .= '<td style="width: 11px;"><img src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_showcourse', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showcourses'.$getvars."'".'" /></td>';
889 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_showcourse', 'calendar').'">'.$strcourse.'</a>: '.substr($strshortnames, 2).'</td>'."\n";
894 $content .= "</tr>\n</table>\n";
896 return $content;
899 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
901 static $shortformat;
902 if(empty($shortformat)) {
903 $shortformat = get_string('strftimedayshort');
906 if($now === false) {
907 $now = time();
910 // To have it in one place, if a change is needed
911 $formal = userdate($tstamp, $shortformat);
913 $datestamp = usergetdate($tstamp);
914 $datenow = usergetdate($now);
916 if($usecommonwords == false) {
917 // We don't want words, just a date
918 return $formal;
920 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
921 // Today
922 return get_string('today', 'calendar');
924 else if(
925 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
926 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
928 // Yesterday
929 return get_string('yesterday', 'calendar');
931 else if(
932 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
933 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
935 // Tomorrow
936 return get_string('tomorrow', 'calendar');
938 else {
939 return $formal;
943 function calendar_time_representation($time) {
944 static $langtimeformat = NULL;
945 if($langtimeformat === NULL) {
946 $langtimeformat = get_string('strftimetime');
948 $timeformat = get_user_preferences('calendar_timeformat');
949 if(empty($timeformat)){
950 $timeformat = get_config(NULL,'calendar_site_timeformat');
952 // The ? is needed because the preference might be present, but empty
953 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
957 * TODO document
959 function calendar_get_link_href($linkbase, $d, $m, $y) {
960 if(empty($linkbase)) return '';
961 $paramstr = '';
962 if(!empty($d)) $paramstr .= '&amp;cal_d='.$d;
963 if(!empty($m)) $paramstr .= '&amp;cal_m='.$m;
964 if(!empty($y)) $paramstr .= '&amp;cal_y='.$y;
965 if(!empty($paramstr)) $paramstr = substr($paramstr, 5);
966 return $linkbase.$paramstr;
970 * TODO document
972 function calendar_get_link_tag($text, $linkbase, $d, $m, $y) {
973 $href = calendar_get_link_href($linkbase, $d, $m, $y);
974 if(empty($href)) return $text;
975 return '<a href="'.$href.'">'.$text.'</a>';
979 * Build and return a previous month HTML link, with an arrow.
980 * @param string $text The text label.
981 * @param string $linkbase The URL stub.
982 * @param int $d $m $y Day of month, month and year numbers.
983 * @param bool $accesshide Default visible, or hide from all except screenreaders.
984 * @return string HTML string.
986 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide=false) {
987 $href = calendar_get_link_href($linkbase, $d, $m, $y);
988 if(empty($href)) return $text;
989 return link_arrow_left($text, $href, $accesshide, 'previous');
993 * Build and return a next month HTML link, with an arrow.
994 * @param string $text The text label.
995 * @param string $linkbase The URL stub.
996 * @param int $d $m $y Day of month, month and year numbers.
997 * @param bool $accesshide Default visible, or hide from all except screenreaders.
998 * @return string HTML string.
1000 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide=false) {
1001 $href = calendar_get_link_href($linkbase, $d, $m, $y);
1002 if(empty($href)) return $text;
1003 return link_arrow_right($text, $href, $accesshide, 'next');
1006 function calendar_wday_name($englishname) {
1007 return get_string(strtolower($englishname), 'calendar');
1010 function calendar_days_in_month($month, $year) {
1011 return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
1014 function calendar_get_sideblock_upcoming($events, $linkhref = NULL) {
1015 $content = '';
1016 $lines = count($events);
1017 if (!$lines) {
1018 return $content;
1021 for ($i = 0; $i < $lines; ++$i) {
1022 if (!isset($events[$i]->time)) { // Just for robustness
1023 continue;
1025 $events[$i] = calendar_add_event_metadata($events[$i]);
1026 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span> ';
1027 if (!empty($events[$i]->referer)) {
1028 // That's an activity event, so let's provide the hyperlink
1029 $content .= $events[$i]->referer;
1030 } else {
1031 if(!empty($linkhref)) {
1032 $ed = usergetdate($events[$i]->timestart);
1033 $href = calendar_get_link_href(CALENDAR_URL.$linkhref, $ed['mday'], $ed['mon'], $ed['year']);
1034 $content .= '<a href="'.$href.'#event_'.$events[$i]->id.'">'.$events[$i]->name.'</a>';
1036 else {
1037 $content .= $events[$i]->name;
1040 $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
1041 $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
1042 if ($i < $lines - 1) $content .= '<hr />';
1045 return $content;
1048 function calendar_add_month($month, $year) {
1049 if($month == 12) {
1050 return array(1, $year + 1);
1052 else {
1053 return array($month + 1, $year);
1057 function calendar_sub_month($month, $year) {
1058 if($month == 1) {
1059 return array(12, $year - 1);
1061 else {
1062 return array($month - 1, $year);
1066 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1067 $eventsbyday = array();
1068 $typesbyday = array();
1069 $durationbyday = array();
1071 if($events === false) {
1072 return;
1075 foreach($events as $event) {
1077 $startdate = usergetdate($event->timestart);
1078 // Set end date = start date if no duration
1079 if ($event->timeduration) {
1080 $enddate = usergetdate($event->timestart + $event->timeduration - 1);
1081 } else {
1082 $enddate = $startdate;
1085 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
1086 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1087 // Out of bounds
1088 continue;
1091 $eventdaystart = intval($startdate['mday']);
1093 if($startdate['mon'] == $month && $startdate['year'] == $year) {
1094 // Give the event to its day
1095 $eventsbyday[$eventdaystart][] = $event->id;
1097 // Mark the day as having such an event
1098 if($event->courseid == SITEID && $event->groupid == 0) {
1099 $typesbyday[$eventdaystart]['startglobal'] = true;
1100 // Set event class for global event
1101 $events[$event->id]->class = 'event_global';
1103 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1104 $typesbyday[$eventdaystart]['startcourse'] = true;
1105 // Set event class for course event
1106 $events[$event->id]->class = 'event_course'.array_search($event->courseid, $courses) % CALENDAR_MAXCOURSES;
1108 else if($event->groupid) {
1109 $typesbyday[$eventdaystart]['startgroup'] = true;
1110 // Set event class for group event
1111 $events[$event->id]->class = 'event_group';
1113 else if($event->userid) {
1114 $typesbyday[$eventdaystart]['startuser'] = true;
1115 // Set event class for user event
1116 $events[$event->id]->class = 'event_user';
1120 if($event->timeduration == 0) {
1121 // Proceed with the next
1122 continue;
1125 // The event starts on $month $year or before. So...
1126 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
1128 // Also, it ends on $month $year or later...
1129 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
1131 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1132 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
1133 $durationbyday[$i][] = $event->id;
1134 if($event->courseid == SITEID && $event->groupid == 0) {
1135 $typesbyday[$i]['durationglobal'] = true;
1137 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1138 $typesbyday[$i]['durationcourse'] = true;
1140 else if($event->groupid) {
1141 $typesbyday[$i]['durationgroup'] = true;
1143 else if($event->userid) {
1144 $typesbyday[$i]['durationuser'] = true;
1149 return;
1152 function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1153 $module = get_coursemodule_from_instance($modulename, $instance);
1155 if($module === false) return false;
1156 if(!calendar_get_course_cached($coursecache, $module->course)) {
1157 return false;
1159 return $module;
1162 function calendar_get_course_cached(&$coursecache, $courseid) {
1163 global $COURSE;
1164 if (!isset($coursecache[$courseid])) {
1165 if ($courseid == $COURSE->id) {
1166 $coursecache[$courseid] = $COURSE;
1167 } else {
1168 $coursecache[$courseid] = get_record('course', 'id', $courseid);
1171 return $coursecache[$courseid];
1174 function calendar_session_vars() {
1175 global $SESSION, $USER;
1177 if(!empty($USER->id) && isset($USER->realuser) && !isset($SESSION->cal_loggedinas)) {
1178 // We just logged in as someone else, update the filtering
1179 unset($SESSION->cal_users_shown);
1180 unset($SESSION->cal_courses_shown);
1181 $SESSION->cal_loggedinas = true;
1182 if(intval(get_user_preferences('calendar_persistflt', 0))) {
1183 calendar_set_filters_status(get_user_preferences('calendar_savedflt', 0xff));
1186 else if(!empty($USER->id) && !isset($USER->realuser) && isset($SESSION->cal_loggedinas)) {
1187 // We just logged back to our real self, update again
1188 unset($SESSION->cal_users_shown);
1189 unset($SESSION->cal_courses_shown);
1190 unset($SESSION->cal_loggedinas);
1191 if(intval(get_user_preferences('calendar_persistflt', 0))) {
1192 calendar_set_filters_status(get_user_preferences('calendar_savedflt', 0xff));
1196 if(!isset($SESSION->cal_course_referer)) {
1197 $SESSION->cal_course_referer = 0;
1199 if(!isset($SESSION->cal_show_global)) {
1200 $SESSION->cal_show_global = true;
1202 if(!isset($SESSION->cal_show_groups)) {
1203 $SESSION->cal_show_groups = true;
1205 if(!isset($SESSION->cal_show_course)) {
1206 $SESSION->cal_show_course = true;
1208 if(!isset($SESSION->cal_show_user)) {
1209 $SESSION->cal_show_user = true;
1211 // if(empty($SESSION->cal_courses_shown)) {
1212 $SESSION->cal_courses_shown = calendar_get_default_courses(true);
1214 if(empty($SESSION->cal_users_shown)) {
1215 // The empty() instead of !isset() here makes a whole world of difference,
1216 // as it will automatically change to the user's id when the user first logs
1217 // in. With !isset(), it would never do that.
1218 $SESSION->cal_users_shown = !empty($USER->id) ? $USER->id : false;
1220 else if(is_numeric($SESSION->cal_users_shown) && !empty($USER->id) && $SESSION->cal_users_shown != $USER->id) {
1221 // Follow the white rabbit, for example if a teacher logs in as a student
1222 $SESSION->cal_users_shown = $USER->id;
1226 function calendar_overlib_html() {
1227 return '<div id="overDiv" style="position: absolute; visibility: hidden; z-index:1000;"></div>'
1228 .'<script type="text/javascript" src="'.CALENDAR_URL.'overlib.cfg.php"></script>';
1231 function calendar_set_referring_course($courseid) {
1232 global $SESSION;
1233 $SESSION->cal_course_referer = intval($courseid);
1236 function calendar_set_filters(&$courses, &$group, &$user, $courseeventsfrom = NULL, $groupeventsfrom = NULL, $ignorefilters = false) {
1237 global $SESSION, $USER, $CFG;
1239 // Insidious bug-wannabe: setting $SESSION->cal_courses_shown to $course->id would cause
1240 // the code to function incorrectly UNLESS we convert it to an integer. One case where
1241 // PHP's loose type system works against us.
1242 if(is_string($SESSION->cal_courses_shown)) {
1243 $SESSION->cal_courses_shown = intval($SESSION->cal_courses_shown);
1246 if($courseeventsfrom === NULL) {
1247 $courseeventsfrom = $SESSION->cal_courses_shown;
1249 if($groupeventsfrom === NULL) {
1250 $groupeventsfrom = $SESSION->cal_courses_shown;
1253 if(($SESSION->cal_show_course && $SESSION->cal_show_global) || $ignorefilters) {
1254 if(is_int($courseeventsfrom)) {
1255 $courses = array(SITEID, $courseeventsfrom);
1257 else if(is_array($courseeventsfrom)) {
1258 $courses = array_keys($courseeventsfrom);
1259 $courses[] = SITEID;
1262 else if($SESSION->cal_show_course) {
1263 if(is_int($courseeventsfrom)) {
1264 $courses = array($courseeventsfrom);
1266 else if(is_array($courseeventsfrom)) {
1267 $courses = array_keys($courseeventsfrom);
1269 $courses = array_diff($courses, array(SITEID));
1271 else if($SESSION->cal_show_global) {
1272 $courses = array(SITEID);
1274 else {
1275 $courses = false;
1277 //BUG 6130 clean $courses array as SESSION has bad entries.
1278 // [pj] TODO: See if this has to do with my new change in get_default_courses and can be taken out
1279 if (is_array($courses)) {
1280 foreach ($courses as $index => $value) {
1281 if (empty($value)) unset($courses[$index]);
1284 // Sort courses for consistent colour highlighting
1285 // Effectively ignoring SITEID as setting as last course id
1286 $key = array_search(SITEID, $courses);
1287 if ($key !== false) {
1288 unset($courses[$key]);
1289 sort($courses);
1290 $courses[] = SITEID;
1291 } else {
1292 sort($courses);
1296 if($SESSION->cal_show_user || $ignorefilters) {
1297 // This doesn't work for arrays yet (maybe someday it will)
1298 $user = $SESSION->cal_users_shown;
1300 else {
1301 $user = false;
1303 if($SESSION->cal_show_groups || $ignorefilters) {
1304 if(is_int($groupeventsfrom)) {
1305 $groupcourses = array($groupeventsfrom);
1307 else if(is_array($groupeventsfrom)) {
1308 $groupcourses = array_keys($groupeventsfrom);
1311 // XXX TODO: not sure how to replace $CFG->calendar_adminseesall
1312 if(has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM, SITEID)) && !empty($CFG->calendar_adminseesall)) {
1313 $group = true;
1315 else {
1316 $grouparray = array();
1318 // We already have the courses to examine in $courses
1319 // For each course...
1321 foreach($groupcourses as $courseid) {
1323 if (!isset($courseeventsfrom[$courseid]->context)) { // SHOULD be set MDL-11221
1324 if (is_object($courseeventsfrom[$courseid])) {
1325 $courseeventsfrom[$courseid]->context = get_context_instance(CONTEXT_COURSE, $courseid);
1329 // If the user is an editing teacher in there,
1330 if (!empty($USER->id) && isset($courseeventsfrom[$courseid]->context) && has_capability('moodle/calendar:manageentries', $courseeventsfrom[$courseid]->context)) {
1331 // If this course has groups, show events from all of them
1332 if(is_int($groupeventsfrom)) {
1333 if (is_object($courseeventsfrom[$courseid])) { // SHOULD be set MDL-11221
1334 $courserecord = $courseeventsfrom[$courseid];
1335 } else {
1336 $courserecord = get_record('course', 'id', $courseid);
1338 $courserecord = get_record('course', 'id', $courseid);
1339 if ($courserecord->groupmode != NOGROUPS || !$courserecord->groupmodeforce) {
1340 $groupids[] = $courseid;
1343 else if(isset($SESSION->cal_courses_shown[$courseid]) && ($SESSION->cal_courses_shown[$courseid]->groupmode != NOGROUPS || !$SESSION->cal_courses_shown[$courseid]->groupmodeforce)) {
1344 $groupids[] = $courseid;
1348 // Otherwise (not editing teacher) show events from the group he is a member of
1349 else if(isset($USER->groupmember[$courseid])) {
1350 //changed to 2D array
1351 foreach ($USER->groupmember[$courseid] as $groupid){
1352 $grouparray[] = $groupid;
1357 if (!empty($groupids)) {
1358 $sql = "SELECT id
1359 FROM {$CFG->prefix}groups
1360 WHERE courseid IN (".implode(',', $groupids).')';
1362 if ($grouprecords= get_records_sql($sql)) {
1363 $grouparray = array_merge($grouparray, array_keys($grouprecords));
1367 if(empty($grouparray)) {
1368 $group = false;
1370 else {
1371 $group = $grouparray;
1376 else {
1377 $group = false;
1381 function calendar_edit_event_allowed($event) {
1383 global $USER;
1385 // can not be using guest account
1386 if ($USER->username == "guest") {
1387 return false;
1390 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
1391 // if user has manageentries at site level, return true
1392 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1393 return true;
1396 // if groupid is set, it's definitely a group event
1397 if ($event->groupid) {
1398 //TODO:check.
1399 if (! groups_group_exists($event->groupid)) {
1400 return false;
1403 // this is ok because if you have this capability at course level, you should be able
1404 // to edit group calendar too
1405 // there is no need to check membership, because if you have this capability
1406 // you will have a role in this group context
1407 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_GROUP, $event->groupid));
1408 } else if ($event->courseid) {
1409 // if groupid is not set, but course is set,
1410 // it's definiely a course event
1411 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $event->courseid));
1412 } else if ($event->userid && $event->userid == $USER->id) {
1413 // if course is not set, but userid id set, it's a user event
1414 return (has_capability('moodle/calendar:manageownentries', $sitecontext));
1416 return false;
1419 function calendar_get_default_courses($ignoreref = false) {
1420 global $USER, $CFG, $SESSION;
1422 if(!empty($SESSION->cal_course_referer) && !$ignoreref) {
1423 return array($SESSION->cal_course_referer => 1);
1426 if(empty($USER->id)) {
1427 return array();
1430 $courses = array();
1431 if (has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
1432 if (!empty($CFG->calendar_adminseesall)) {
1433 $courses = get_records_sql('SELECT id, 1 FROM '.$CFG->prefix.'course');
1434 return $courses;
1438 if (isset($CFG->adminseesall)) {
1439 $courses = get_my_courses($USER->id, null, null, $CFG->adminseesall);
1441 else {
1442 $courses = get_my_courses($USER->id, null, null, false);
1445 return $courses;
1448 function calendar_preferences_button() {
1449 global $CFG, $USER;
1451 // Guests have no preferences
1452 if (empty($USER->id) || isguest()) {
1453 return '';
1456 return "<form $CFG->frametarget method=\"get\" ".
1457 " action=\"$CFG->wwwroot/calendar/preferences.php\">".
1458 "<div><input type=\"submit\" value=\"".get_string("preferences", "calendar")." ...\" /></div></form>";
1461 function calendar_format_event_time($event, $now, $morehref, $usecommonwords = true, $showtime=0) {
1462 $startdate = usergetdate($event->timestart);
1463 $enddate = usergetdate($event->timestart + $event->timeduration);
1464 $usermidnightstart = usergetmidnight($event->timestart);
1466 if($event->timeduration) {
1467 // To avoid doing the math if one IF is enough :)
1468 $usermidnightend = usergetmidnight($event->timestart + $event->timeduration);
1470 else {
1471 $usermidnightend = $usermidnightstart;
1474 // OK, now to get a meaningful display...
1475 // First of all we have to construct a human-readable date/time representation
1477 if($event->timeduration) {
1478 // It has a duration
1479 if($usermidnightstart == $usermidnightend ||
1480 ($event->timestart == $usermidnightstart) && ($event->timeduration == 86400 || $event->timeduration == 86399) ||
1481 ($event->timestart + $event->timeduration <= $usermidnightstart + 86400)) {
1482 // But it's all on the same day
1483 $timestart = calendar_time_representation($event->timestart);
1484 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1485 $time = $timestart.' <strong>&raquo;</strong> '.$timeend;
1487 if ($event->timestart == $usermidnightstart && ($event->timeduration == 86400 || $event->timeduration == 86399)) {
1488 $time = get_string('allday', 'calendar');
1491 // Set printable representation
1492 if (!$showtime) {
1493 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1494 $eventtime = calendar_get_link_tag($day, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $enddate['mday'], $enddate['mon'], $enddate['year']).', '.$time;
1495 } else {
1496 $eventtime = $time;
1498 } else {
1499 // It spans two or more days
1500 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords).', ';
1501 if ($showtime == $usermidnightstart) {
1502 $daystart = '';
1504 $timestart = calendar_time_representation($event->timestart);
1505 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords).', ';
1506 if ($showtime == $usermidnightend) {
1507 $dayend = '';
1509 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1511 // Set printable representation
1512 if ($now >= $usermidnightstart && $now < ($usermidnightstart + 86400)) {
1513 $eventtime = $timestart.' <strong>&raquo;</strong> '.calendar_get_link_tag($dayend, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $enddate['mday'], $enddate['mon'], $enddate['year']).
1514 $timeend;
1515 } else {
1516 $eventtime = calendar_get_link_tag($daystart, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $startdate['mday'], $startdate['mon'], $startdate['year']).
1517 $timestart.' <strong>&raquo;</strong> '.calendar_get_link_tag($dayend, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $enddate['mday'], $enddate['mon'], $enddate['year']).
1518 $timeend;
1521 } else {
1522 $time = ' ';
1524 // Set printable representation
1525 if (!$showtime) {
1526 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1527 $eventtime = calendar_get_link_tag($day, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $startdate['mday'], $startdate['mon'], $startdate['year']).trim($time);
1528 } else {
1529 $eventtime = $time;
1533 if($event->timestart + $event->timeduration < $now) {
1534 // It has expired
1535 $eventtime = '<span class="dimmed_text">'.str_replace(' href=', ' class="dimmed" href=', $eventtime).'</span>';
1538 return $eventtime;
1541 function calendar_print_month_selector($name, $selected) {
1543 $months = array();
1545 for ($i=1; $i<=12; $i++) {
1546 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
1549 choose_from_menu($months, $name, $selected, '');
1552 function calendar_get_filters_status() {
1553 global $SESSION;
1555 $status = 0;
1556 if($SESSION->cal_show_global) {
1557 $status += 1;
1559 if($SESSION->cal_show_course) {
1560 $status += 2;
1562 if($SESSION->cal_show_groups) {
1563 $status += 4;
1565 if($SESSION->cal_show_user) {
1566 $status += 8;
1568 return $status;
1571 function calendar_set_filters_status($packed_bitfield) {
1572 global $SESSION, $USER;
1574 if(!isset($USER) || empty($USER->id)) {
1575 return false;
1578 $SESSION->cal_show_global = ($packed_bitfield & 1);
1579 $SESSION->cal_show_course = ($packed_bitfield & 2);
1580 $SESSION->cal_show_groups = ($packed_bitfield & 4);
1581 $SESSION->cal_show_user = ($packed_bitfield & 8);
1583 return true;
1586 function calendar_get_allowed_types(&$allowed) {
1587 global $USER, $CFG, $SESSION;
1588 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1589 $allowed->user = has_capability('moodle/calendar:manageownentries', $sitecontext);
1590 $allowed->groups = false; // This may change just below
1591 $allowed->courses = false; // This may change just below
1592 $allowed->site = has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, SITEID));
1594 if(!empty($SESSION->cal_course_referer) && $SESSION->cal_course_referer != SITEID && has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $SESSION->cal_course_referer))) {
1595 $course = get_record('course', 'id', $SESSION->cal_course_referer);
1597 $allowed->courses = array($course->id => 1);
1599 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1600 $allowed->groups = groups_get_all_groups($SESSION->cal_course_referer);
1606 * see if user can add calendar entries at all
1607 * used to print the "New Event" button
1608 * @return bool
1610 function calendar_user_can_add_event() {
1611 calendar_get_allowed_types($allowed);
1612 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);