MDL-24350: fixed XHTML strict by removing an additional of '</div>'
[moodle.git] / calendar / lib.php
blob74051f439254d6a28346910f6af9d25e75c94422
1 <?php
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);
48 define('CALENDAR_UPCOMING_DAYS', isset($CFG->calendar_lookahead) ? intval($CFG->calendar_lookahead) : CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD);
49 define('CALENDAR_UPCOMING_MAXEVENTS', isset($CFG->calendar_maxevents) ? intval($CFG->calendar_maxevents) : CALENDAR_DEFAULT_UPCOMING_MAXEVENTS);
50 define('CALENDAR_WEEKEND', isset($CFG->calendar_weekend) ? intval($CFG->calendar_weekend) : CALENDAR_DEFAULT_WEEKEND);
51 define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
52 define('CALENDAR_TF_24', '%H:%M');
53 define('CALENDAR_TF_12', '%I:%M %p');
55 /**
56 * CALENDAR_STARTING_WEEKDAY has since been deprecated please call calendar_get_starting_weekday() instead
57 * @deprecated
59 define('CALENDAR_STARTING_WEEKDAY', CALENDAR_DEFAULT_STARTING_WEEKDAY);
61 $CALENDARDAYS = array('sunday','monday','tuesday','wednesday','thursday','friday','saturday');
63 /**
64 * Gets the first day of the week
66 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
68 * @return int
70 function calendar_get_starting_weekday() {
71 global $CFG;
73 if (isset($CFG->calendar_startwday)) {
74 $firstday = $CFG->calendar_startwday;
75 } else {
76 $firstday = get_string('firstdayofweek', 'langconfig');
79 if(!is_numeric($firstday)) {
80 return CALENDAR_DEFAULT_STARTING_WEEKDAY;
81 } else {
82 return intval($firstday) % 7;
86 /**
87 * Generates the HTML for a miniature calendar
89 * @global core_renderer $OUTPUT
90 * @param array $courses
91 * @param array $groups
92 * @param array $users
93 * @param int $cal_month
94 * @param int $cal_year
95 * @return string
97 function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_year = false) {
98 global $CFG, $USER, $OUTPUT;
100 $display = new stdClass;
101 $display->minwday = get_user_preferences('calendar_startwday', calendar_get_starting_weekday());
102 $display->maxwday = $display->minwday + 6;
104 $content = '';
106 if(!empty($cal_month) && !empty($cal_year)) {
107 $thisdate = usergetdate(time()); // Date and time the user sees at his location
108 if($cal_month == $thisdate['mon'] && $cal_year == $thisdate['year']) {
109 // Navigated to this month
110 $date = $thisdate;
111 $display->thismonth = true;
112 } else {
113 // Navigated to other month, let's do a nice trick and save us a lot of work...
114 if(!checkdate($cal_month, 1, $cal_year)) {
115 $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']);
116 $display->thismonth = true;
117 } else {
118 $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year);
119 $display->thismonth = false;
122 } else {
123 $date = usergetdate(time()); // Date and time the user sees at his location
124 $display->thismonth = true;
127 // Fill in the variables we 're going to use, nice and tidy
128 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display
129 $display->maxdays = calendar_days_in_month($m, $y);
131 if (get_user_timezone_offset() < 99) {
132 // We 'll keep these values as GMT here, and offset them when the time comes to query the db
133 $display->tstart = gmmktime(0, 0, 0, $m, 1, $y); // This is GMT
134 $display->tend = gmmktime(23, 59, 59, $m, $display->maxdays, $y); // GMT
135 } else {
136 // no timezone info specified
137 $display->tstart = mktime(0, 0, 0, $m, 1, $y);
138 $display->tend = mktime(23, 59, 59, $m, $display->maxdays, $y);
141 $startwday = dayofweek(1, $m, $y);
143 // Align the starting weekday to fall in our display range
144 // This is simple, not foolproof.
145 if($startwday < $display->minwday) {
146 $startwday += 7;
149 // TODO: THIS IS TEMPORARY CODE!
150 // [pj] I was just reading through this and realized that I when writing this code I was probably
151 // asking for trouble, as all these time manipulations seem to be unnecessary and a simple
152 // make_timestamp would accomplish the same thing. So here goes a test:
153 //$test_start = make_timestamp($y, $m, 1);
154 //$test_end = make_timestamp($y, $m, $display->maxdays, 23, 59, 59);
155 //if($test_start != usertime($display->tstart) - dst_offset_on($display->tstart)) {
156 //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);
158 //if($test_end != usertime($display->tend) - dst_offset_on($display->tend)) {
159 //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);
163 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
164 $events = calendar_get_events(
165 usertime($display->tstart) - dst_offset_on($display->tstart),
166 usertime($display->tend) - dst_offset_on($display->tend),
167 $users, $groups, $courses);
169 // Set event course class for course events
170 if (!empty($events)) {
171 foreach ($events as $eventid => $event) {
172 if (!empty($event->modulename)) {
173 $cm = get_coursemodule_from_instance($event->modulename, $event->instance);
174 if (!groups_course_module_visible($cm)) {
175 unset($events[$eventid]);
181 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
182 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
183 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
184 // arguments to this function.
186 $hrefparams = array();
187 if(!empty($courses)) {
188 $courses = array_diff($courses, array(SITEID));
189 if(count($courses) == 1) {
190 $hrefparams['course'] = reset($courses);
194 // We want to have easy access by day, since the display is on a per-day basis.
195 // Arguments passed by reference.
196 //calendar_events_by_day($events, $display->tstart, $eventsbyday, $durationbyday, $typesbyday);
197 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
199 //Accessibility: added summary and <abbr> elements.
200 ///global $CALENDARDAYS; appears to be broken.
201 $days_title = array('sunday','monday','tuesday','wednesday','thursday','friday','saturday');
203 $summary = get_string('calendarheading', 'calendar', userdate(make_timestamp($y, $m), get_string('strftimemonthyear')));
204 $summary = get_string('tabledata', 'access', $summary);
205 $content .= '<table class="minicalendar calendartable" summary="'.$summary.'">'; // Begin table
206 $content .= '<tr class="weekdays">'; // Header row: day names
208 // Print out the names of the weekdays
209 $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
210 for($i = $display->minwday; $i <= $display->maxwday; ++$i) {
211 // This uses the % operator to get the correct weekday no matter what shift we have
212 // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
213 $content .= '<th scope="col"><abbr title="'. get_string($days_title[$i % 7], 'calendar') .'">'.
214 get_string($days[$i % 7], 'calendar') ."</abbr></th>\n";
217 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
219 // For the table display. $week is the row; $dayweek is the column.
220 $dayweek = $startwday;
222 // Paddding (the first week may have blank days in the beginning)
223 for($i = $display->minwday; $i < $startwday; ++$i) {
224 $content .= '<td class="dayblank">&nbsp;</td>'."\n";
227 // Now display all the calendar
228 for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
229 if($dayweek > $display->maxwday) {
230 // We need to change week (table row)
231 $content .= '</tr><tr>';
232 $dayweek = $display->minwday;
235 // Reset vars
236 $cell = '';
237 if(CALENDAR_WEEKEND & (1 << ($dayweek % 7))) {
238 // Weekend. This is true no matter what the exact range is.
239 $class = 'weekend day';
240 } else {
241 // Normal working day.
242 $class = 'day';
245 // Special visual fx if an event is defined
246 if(isset($eventsbyday[$day])) {
247 $class .= ' hasevent';
248 $hrefparams['view'] = 'day';
249 $dayhref = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $hrefparams), $day, $m, $y);
251 // OverLib popup
252 $popupcontent = '';
253 foreach($eventsbyday[$day] as $eventid) {
254 if (!isset($events[$eventid])) {
255 continue;
257 $event = $events[$eventid];
258 $popupalt = '';
259 $component = 'moodle';
260 if(!empty($event->modulename)) {
261 $popupicon = 'icon';
262 $popupalt = $event->modulename;
263 $component = $event->modulename;
264 } else if ($event->courseid == SITEID) { // Site event
265 $popupicon = 'c/site';
266 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
267 $popupicon = 'c/course';
268 } else if ($event->groupid) { // Group event
269 $popupicon = 'c/group';
270 } else if ($event->userid) { // User event
271 $popupicon = 'c/user';
274 $dayhref->set_anchor('event_'.$event->id);
276 $popupcontent .= html_writer::start_tag('div');
277 $popupcontent .= $OUTPUT->pix_icon($popupicon, $popupalt);
278 $popupcontent .= html_writer::link($dayhref, format_string($event->name, true));
279 $popupcontent .= html_writer::end_tag('div');
282 //Accessibility: functionality moved to calendar_get_popup.
283 if($display->thismonth && $day == $d) {
284 $popup = calendar_get_popup(true, $events[$eventid]->timestart, $popupcontent);
285 } else {
286 $popup = calendar_get_popup(false, $events[$eventid]->timestart, $popupcontent);
289 // Class and cell content
290 if(isset($typesbyday[$day]['startglobal'])) {
291 $class .= ' calendar_event_global';
292 } else if(isset($typesbyday[$day]['startcourse'])) {
293 $class .= ' calendar_event_course';
294 } else if(isset($typesbyday[$day]['startgroup'])) {
295 $class .= ' calendar_event_group';
296 } else if(isset($typesbyday[$day]['startuser'])) {
297 $class .= ' calendar_event_user';
299 $cell = '<a href="'.(string)$dayhref.'" '.$popup.'>'.$day.'</a>';
300 } else {
301 $cell = $day;
304 $durationclass = false;
305 if (isset($typesbyday[$day]['durationglobal'])) {
306 $durationclass = ' duration_global';
307 } else if(isset($typesbyday[$day]['durationcourse'])) {
308 $durationclass = ' duration_course';
309 } else if(isset($typesbyday[$day]['durationgroup'])) {
310 $durationclass = ' duration_group';
311 } else if(isset($typesbyday[$day]['durationuser'])) {
312 $durationclass = ' duration_user';
314 if ($durationclass) {
315 $class .= ' duration '.$durationclass;
318 // If event has a class set then add it to the table day <td> tag
319 // Note: only one colour for minicalendar
320 if(isset($eventsbyday[$day])) {
321 foreach($eventsbyday[$day] as $eventid) {
322 if (!isset($events[$eventid])) {
323 continue;
325 $event = $events[$eventid];
326 if (!empty($event->class)) {
327 $class .= ' '.$event->class;
329 break;
333 // Special visual fx for today
334 //Accessibility: hidden text for today, and popup.
335 if($display->thismonth && $day == $d) {
336 $class .= ' today';
337 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
339 if(! isset($eventsbyday[$day])) {
340 $class .= ' eventnone';
341 $popup = calendar_get_popup(true, false);
342 $cell = '<a href="#" '.$popup.'>'.$day.'</a>';
344 $cell = get_accesshide($today.' ').$cell;
347 // Just display it
348 if(!empty($class)) {
349 $class = ' class="'.$class.'"';
351 $content .= '<td'.$class.'>'.$cell."</td>\n";
354 // Paddding (the last week may have blank days at the end)
355 for($i = $dayweek; $i <= $display->maxwday; ++$i) {
356 $content .= '<td class="dayblank">&nbsp;</td>';
358 $content .= '</tr>'; // Last row ends
360 $content .= '</table>'; // Tabular display of days ends
362 return $content;
366 * calendar_get_popup, called at multiple points in from calendar_get_mini.
367 * Copied and modified from calendar_get_mini.
368 * @global moodle_page $PAGE
369 * @param $is_today bool, false except when called on the current day.
370 * @param $event_timestart mixed, $events[$eventid]->timestart, OR false if there are no events.
371 * @param $popupcontent string.
372 * @return $popup string, contains onmousover and onmouseout events.
374 function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
375 global $PAGE;
376 static $popupcount;
377 if ($popupcount === null) {
378 $popupcount = 1;
380 $popupcaption = '';
381 if($is_today) {
382 $popupcaption = get_string('today', 'calendar').' ';
384 if (false === $event_timestart) {
385 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
386 $popupcontent = get_string('eventnone', 'calendar');
388 } else {
389 $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
391 $id = 'calendar_tooltip_'.$popupcount;
392 $PAGE->requires->yui_module('moodle-calendar-eventmanager', 'M.core_calendar.add_event', array(array('eventId'=>$id,'title'=>$popupcaption, 'content'=>$popupcontent)));
394 $popupcount++;
395 return 'id="'.$id.'"';
398 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
399 global $CFG, $COURSE, $DB;
401 $display = new stdClass;
402 $display->range = $daysinfuture; // How many days in the future we 'll look
403 $display->maxevents = $maxevents;
405 $output = array();
407 // Prepare "course caching", since it may save us a lot of queries
408 $coursecache = array();
410 $processed = 0;
411 $now = time(); // We 'll need this later
412 $usermidnighttoday = usergetmidnight($now);
414 if ($fromtime) {
415 $display->tstart = $fromtime;
416 } else {
417 $display->tstart = $usermidnighttoday;
420 // This works correctly with respect to the user's DST, but it is accurate
421 // only because $fromtime is always the exact midnight of some day!
422 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
424 // Get the events matching our criteria
425 $events = calendar_get_events($display->tstart, $display->tend, $users, $groups, $courses);
427 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
428 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
429 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
430 // arguments to this function.
432 $hrefparams = array();
433 if(!empty($courses)) {
434 $courses = array_diff($courses, array(SITEID));
435 if(count($courses) == 1) {
436 $hrefparams['course'] = reset($courses);
440 if ($events !== false) {
442 $modinfo =& get_fast_modinfo($COURSE);
444 foreach($events as $event) {
447 if (!empty($event->modulename)) {
448 if ($event->courseid == $COURSE->id) {
449 if (isset($modinfo->instances[$event->modulename][$event->instance])) {
450 $cm = $modinfo->instances[$event->modulename][$event->instance];
451 if (!$cm->uservisible) {
452 continue;
455 } else {
456 if (!$cm = get_coursemodule_from_instance($event->modulename, $event->instance)) {
457 continue;
459 if (!coursemodule_visible_for_user($cm)) {
460 continue;
463 if ($event->modulename == 'assignment'){
464 // TODO: rewrite this hack somehow
465 if (!calendar_edit_event_allowed($event)){ // cannot manage entries, eg. student
466 if (!$assignment = $DB->get_record('assignment', array('id'=>$event->instance))) {
467 // print_error("invalidid", 'assignment');
468 continue;
470 // assign assignment to assignment object to use hidden_is_hidden method
471 require_once($CFG->dirroot.'/mod/assignment/lib.php');
473 if (!file_exists($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php')) {
474 continue;
476 require_once ($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
478 $assignmentclass = 'assignment_'.$assignment->assignmenttype;
479 $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm);
481 if ($assignmentinstance->description_is_hidden()){//force not to show description before availability
482 $event->description = get_string('notavailableyet', 'assignment');
488 if ($processed >= $display->maxevents) {
489 break;
492 $event->time = calendar_format_event_time($event, $now, $hrefparams);
493 $output[] = $event;
494 ++$processed;
497 return $output;
500 function calendar_add_event_metadata($event) {
501 global $CFG, $OUTPUT;
503 //Support multilang in event->name
504 $event->name = format_string($event->name,true);
506 if(!empty($event->modulename)) { // Activity event
507 // The module name is set. I will assume that it has to be displayed, and
508 // also that it is an automatically-generated event. And of course that the
509 // fields for get_coursemodule_from_instance are set correctly.
510 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
512 if ($module === false) {
513 return;
516 $modulename = get_string('modulename', $event->modulename);
517 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
518 // will be used as alt text if the event icon
519 $eventtype = get_string($event->eventtype, $event->modulename);
520 } else {
521 $eventtype = '';
523 $icon = $OUTPUT->pix_url('icon', $event->modulename) . '';
525 $event->icon = '<img height="16" width="16" src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" style="vertical-align: middle;" />';
526 $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
527 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$module->course.'">'.$coursecache[$module->course]->fullname.'</a>';
528 $event->cmid = $module->id;
531 } else if($event->courseid == SITEID) { // Site event
532 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/site') . '" alt="'.get_string('globalevent', 'calendar').'" style="vertical-align: middle;" />';
533 $event->cssclass = 'calendar_event_global';
534 } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
535 calendar_get_course_cached($coursecache, $event->courseid);
536 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/course') . '" alt="'.get_string('courseevent', 'calendar').'" style="vertical-align: middle;" />';
537 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$event->courseid.'">'.$coursecache[$event->courseid]->fullname.'</a>';
538 $event->cssclass = 'calendar_event_course';
539 } else if ($event->groupid) { // Group event
540 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/group') . '" alt="'.get_string('groupevent', 'calendar').'" style="vertical-align: middle;" />';
541 $event->cssclass = 'calendar_event_group';
542 } else if($event->userid) { // User event
543 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/user') . '" alt="'.get_string('userevent', 'calendar').'" style="vertical-align: middle;" />';
544 $event->cssclass = 'calendar_event_user';
546 return $event;
550 * Prints a calendar event
552 * @deprecated 2.0
554 function calendar_print_event($event, $showactions=true) {
555 global $CFG, $USER, $OUTPUT, $PAGE;
556 debugging('calendar_print_event is deprecated please update your code', DEBUG_DEVELOPER);
557 $renderer = $PAGE->get_renderer('core_calendar');
558 if (!($event instanceof calendar_event)) {
559 $event = new calendar_event($event);
561 echo $renderer->event($event);
565 * Get calendar events
566 * @param int $tstart Start time of time range for events
567 * @param int $tend End time of time range for events
568 * @param array/int/boolean $users array of users, user id or boolean for all/no user events
569 * @param array/int/boolean $groups array of groups, group id or boolean for all/no group events
570 * @param array/int/boolean $courses array of courses, course id or boolean for all/no course events
571 * @param boolean $withduration whether only events starting within time range selected
572 * or events in progress/already started selected as well
573 * @param boolean $ignorehidden whether to select only visible events or all events
574 * @return array of selected events or an empty array if there aren't any (or there was an error)
576 function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
577 global $DB;
579 $whereclause = '';
580 // Quick test
581 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
582 return array();
585 if(is_array($users) && !empty($users)) {
586 // Events from a number of users
587 if(!empty($whereclause)) $whereclause .= ' OR';
588 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
589 } else if(is_numeric($users)) {
590 // Events from one user
591 if(!empty($whereclause)) $whereclause .= ' OR';
592 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
593 } else if($users === true) {
594 // Events from ALL users
595 if(!empty($whereclause)) $whereclause .= ' OR';
596 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
597 } else if($users === false) {
598 // No user at all, do nothing
601 if(is_array($groups) && !empty($groups)) {
602 // Events from a number of groups
603 if(!empty($whereclause)) $whereclause .= ' OR';
604 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
605 } else if(is_numeric($groups)) {
606 // Events from one group
607 if(!empty($whereclause)) $whereclause .= ' OR ';
608 $whereclause .= ' groupid = '.$groups;
609 } else if($groups === true) {
610 // Events from ALL groups
611 if(!empty($whereclause)) $whereclause .= ' OR ';
612 $whereclause .= ' groupid != 0';
614 // boolean false (no groups at all): we don't need to do anything
616 if(is_array($courses) && !empty($courses)) {
617 if(!empty($whereclause)) {
618 $whereclause .= ' OR';
620 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
621 } else if(is_numeric($courses)) {
622 // One course
623 if(!empty($whereclause)) $whereclause .= ' OR';
624 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
625 } else if ($courses === true) {
626 // Events from ALL courses
627 if(!empty($whereclause)) $whereclause .= ' OR';
628 $whereclause .= ' (groupid = 0 AND courseid != 0)';
631 // Security check: if, by now, we have NOTHING in $whereclause, then it means
632 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
633 // events no matter what. Allowing the code to proceed might return a completely
634 // valid query with only time constraints, thus selecting ALL events in that time frame!
635 if(empty($whereclause)) {
636 return array();
639 if($withduration) {
640 $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
642 else {
643 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
645 if(!empty($whereclause)) {
646 // We have additional constraints
647 $whereclause = $timeclause.' AND ('.$whereclause.')';
649 else {
650 // Just basic time filtering
651 $whereclause = $timeclause;
654 if ($ignorehidden) {
655 $whereclause .= ' AND visible = 1';
658 $events = $DB->get_records_select('event', $whereclause, null, 'timestart');
659 if ($events === false) {
660 $events = array();
662 return $events;
665 function calendar_top_controls($type, $data) {
666 global $CFG, $CALENDARDAYS;
667 $content = '';
668 if(!isset($data['d'])) {
669 $data['d'] = 1;
672 // Ensure course id passed if relevant
673 // Required due to changes in view/lib.php mainly (calendar_session_vars())
674 $courseid = '';
675 if (!empty($data['id'])) {
676 $courseid = '&amp;course='.$data['id'];
679 if(!checkdate($data['m'], $data['d'], $data['y'])) {
680 $time = time();
682 else {
683 $time = make_timestamp($data['y'], $data['m'], $data['d']);
685 $date = usergetdate($time);
687 $data['m'] = $date['mon'];
688 $data['y'] = $date['year'];
690 //Accessibility: calendar block controls, replaced <table> with <div>.
691 //$nexttext = link_arrow_right(get_string('monthnext', 'access'), $url='', $accesshide=true);
692 //$prevtext = link_arrow_left(get_string('monthprev', 'access'), $url='', $accesshide=true);
694 switch($type) {
695 case 'frontpage':
696 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
697 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
698 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'index.php?', 0, $nextmonth, $nextyear, $accesshide=true);
699 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'index.php?', 0, $prevmonth, $prevyear, true);
701 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
702 if (!empty($data['id'])) {
703 $calendarlink->param('course', $data['id']);
706 if (right_to_left()) {
707 $left = $nextlink;
708 $right = $prevlink;
709 } else {
710 $left = $prevlink;
711 $right = $nextlink;
714 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
715 $content .= $left.'<span class="hide"> | </span>';
716 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
717 $content .= '<span class="hide"> | </span>'. $right;
718 $content .= "<span class=\"clearer\"><!-- --></span>\n";
719 $content .= html_writer::end_tag('div');
721 break;
722 case 'course':
723 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
724 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
725 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $nextmonth, $nextyear, $accesshide=true);
726 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $prevmonth, $prevyear, true);
728 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
729 if (!empty($data['id'])) {
730 $calendarlink->param('course', $data['id']);
733 if (right_to_left()) {
734 $left = $nextlink;
735 $right = $prevlink;
736 } else {
737 $left = $prevlink;
738 $right = $nextlink;
741 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
742 $content .= $left.'<span class="hide"> | </span>';
743 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
744 $content .= '<span class="hide"> | </span>'. $right;
745 $content .= "<span class=\"clearer\"><!-- --></span>";
746 $content .= html_writer::end_tag('div');
747 break;
748 case 'upcoming':
749 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'upcoming')), 1, $data['m'], $data['y']);
750 if (!empty($data['id'])) {
751 $calendarlink->param('course', $data['id']);
753 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
754 $content .= html_writer::tag('div', $calendarlink, array('class'=>'centered'));
755 break;
756 case 'display':
757 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
758 if (!empty($data['id'])) {
759 $calendarlink->param('course', $data['id']);
761 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
762 $content .= html_writer::tag('h3', $calendarlink);
763 break;
764 case 'month':
765 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
766 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
767 $prevdate = make_timestamp($prevyear, $prevmonth, 1);
768 $nextdate = make_timestamp($nextyear, $nextmonth, 1);
769 $prevlink = calendar_get_link_previous(userdate($prevdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $prevmonth, $prevyear);
770 $nextlink = calendar_get_link_next(userdate($nextdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $nextmonth, $nextyear);
772 if (right_to_left()) {
773 $left = $nextlink;
774 $right = $prevlink;
775 } else {
776 $left = $prevlink;
777 $right = $nextlink;
780 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
781 $content .= $left . '<span class="hide"> | </span><h1 class="current">'.userdate($time, get_string('strftimemonthyear'))."</h1>";
782 $content .= '<span class="hide"> | </span>' . $right;
783 $content .= '<span class="clearer"><!-- --></span>';
784 $content .= html_writer::end_tag('div')."\n";
785 break;
786 case 'day':
787 $data['d'] = $date['mday']; // Just for convenience
788 $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
789 $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] + 1));
790 $prevname = calendar_wday_name($CALENDARDAYS[$prevdate['wday']]);
791 $nextname = calendar_wday_name($CALENDARDAYS[$nextdate['wday']]);
792 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&amp;', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
793 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&amp;', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);
795 if (right_to_left()) {
796 $left = $nextlink;
797 $right = $prevlink;
798 } else {
799 $left = $prevlink;
800 $right = $nextlink;
803 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
804 $content .= $left;
805 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimedaydate')).'</span>';
806 $content .= '<span class="hide"> | </span>'. $right;
807 $content .= "<span class=\"clearer\"><!-- --></span>";
808 $content .= html_writer::end_tag('div')."\n";
810 break;
812 return $content;
815 function calendar_filter_controls($type, $vars = NULL, $course = NULL, $courses = NULL) {
816 global $CFG, $SESSION, $USER, $OUTPUT;
818 $groupevents = true;
819 $getvars = '';
821 $id = optional_param( 'id',0,PARAM_INT );
823 switch($type) {
824 case 'event':
825 case 'upcoming':
826 case 'day':
827 case 'month':
828 $getvars = '&amp;from='.$type;
829 break;
830 case 'course':
831 if ($id > 0) {
832 $getvars = '&amp;from=course&amp;id='.$id;
833 } else {
834 $getvars = '&amp;from=course';
836 if (isset($course->groupmode) and $course->groupmode == NOGROUPS and $course->groupmodeforce) {
837 $groupevents = false;
839 break;
842 if (!empty($vars)) {
843 $getvars .= '&amp;'.$vars;
846 $content = '<table>';
848 $content .= '<tr>';
849 if($SESSION->cal_show_global) {
850 $content .= '<td class="eventskey calendar_event_global" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" 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>';
851 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showglobal'.$getvars.'" title="'.get_string('tt_hideglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
852 } else {
853 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" 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>';
854 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showglobal'.$getvars.'" title="'.get_string('tt_showglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
856 if($SESSION->cal_show_course) {
857 $content .= '<td class="eventskey calendar_event_course" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" 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>';
858 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_hidecourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
859 } else {
860 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" 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>';
861 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_showcourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
866 if (isloggedin() && !isguestuser()) {
867 $content .= "</tr>\n<tr>";
869 if($groupevents) {
870 // This course MIGHT have group events defined, so show the filter
871 if($SESSION->cal_show_groups) {
872 $content .= '<td class="eventskey calendar_event_group" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" 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>';
873 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showgroups'.$getvars.'" title="'.get_string('tt_hidegroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
874 } else {
875 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" 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>';
876 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showgroups'.$getvars.'" title="'.get_string('tt_showgroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
878 } else {
879 // This course CANNOT have group events, so lose the filter
880 $content .= '<td style="width: 11px;"></td><td>&nbsp;</td>'."\n";
882 if($SESSION->cal_show_user) {
883 $content .= '<td class="eventskey calendar_event_user" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" 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>';
884 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
885 } else {
886 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" 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>';
887 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
890 $content .= "</tr>\n</table>\n";
892 return $content;
895 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
897 static $shortformat;
898 if(empty($shortformat)) {
899 $shortformat = get_string('strftimedayshort');
902 if($now === false) {
903 $now = time();
906 // To have it in one place, if a change is needed
907 $formal = userdate($tstamp, $shortformat);
909 $datestamp = usergetdate($tstamp);
910 $datenow = usergetdate($now);
912 if($usecommonwords == false) {
913 // We don't want words, just a date
914 return $formal;
916 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
917 // Today
918 return get_string('today', 'calendar');
920 else if(
921 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
922 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
924 // Yesterday
925 return get_string('yesterday', 'calendar');
927 else if(
928 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
929 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
931 // Tomorrow
932 return get_string('tomorrow', 'calendar');
934 else {
935 return $formal;
939 function calendar_time_representation($time) {
940 static $langtimeformat = NULL;
941 if($langtimeformat === NULL) {
942 $langtimeformat = get_string('strftimetime');
944 $timeformat = get_user_preferences('calendar_timeformat');
945 if(empty($timeformat)){
946 $timeformat = get_config(NULL,'calendar_site_timeformat');
948 // The ? is needed because the preference might be present, but empty
949 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
953 * Adds day, month, year arguments to a URL and returns a moodle_url object.
955 * @param string|moodle_url $linkbase
956 * @param int $d
957 * @param int $m
958 * @param int $y
959 * @return moodle_url
961 function calendar_get_link_href($linkbase, $d, $m, $y) {
962 if (empty($linkbase)) {
963 return '';
965 if (!($linkbase instanceof moodle_url)) {
966 $linkbase = new moodle_url();
968 if (!empty($d)) {
969 $linkbase->param('cal_d', $d);
971 if (!empty($m)) {
972 $linkbase->param('cal_m', $m);
974 if (!empty($y)) {
975 $linkbase->param('cal_y', $y);
977 return $linkbase;
981 * This function has been deprecated as of Moodle 2.0... DO NOT USE!!!!!
983 * @deprecated
984 * @since 2.0
986 * @param string $text
987 * @param string|moodle_url $linkbase
988 * @param int|null $d
989 * @param int|null $m
990 * @param int|null $y
991 * @return string HTML link
993 function calendar_get_link_tag($text, $linkbase, $d, $m, $y) {
994 $url = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
995 if (empty($url)) {
996 return $text;
998 return html_writer::link($url, $text);
1002 * Build and return a previous month HTML link, with an arrow.
1004 * @param string $text The text label.
1005 * @param string|moodle_url $linkbase The URL stub.
1006 * @param int $d $m $y Day of month, month and year numbers.
1007 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1008 * @return string HTML string.
1010 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide=false) {
1011 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1012 if (empty($href)) {
1013 return $text;
1015 return link_arrow_left($text, (string)$href, $accesshide, 'previous');
1019 * Build and return a next month HTML link, with an arrow.
1021 * @param string $text The text label.
1022 * @param string|moodle_url $linkbase The URL stub.
1023 * @param int $d $m $y Day of month, month and year numbers.
1024 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1025 * @return string HTML string.
1027 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide=false) {
1028 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1029 if (empty($href)) {
1030 return $text;
1032 return link_arrow_right($text, (string)$href, $accesshide, 'next');
1035 function calendar_wday_name($englishname) {
1036 return get_string(strtolower($englishname), 'calendar');
1039 function calendar_days_in_month($month, $year) {
1040 return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
1043 function calendar_get_block_upcoming($events, $linkhref = NULL) {
1044 $content = '';
1045 $lines = count($events);
1046 if (!$lines) {
1047 return $content;
1050 for ($i = 0; $i < $lines; ++$i) {
1051 if (!isset($events[$i]->time)) { // Just for robustness
1052 continue;
1054 $events[$i] = calendar_add_event_metadata($events[$i]);
1055 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span> ';
1056 if (!empty($events[$i]->referer)) {
1057 // That's an activity event, so let's provide the hyperlink
1058 $content .= $events[$i]->referer;
1059 } else {
1060 if(!empty($linkhref)) {
1061 $ed = usergetdate($events[$i]->timestart);
1062 $href = calendar_get_link_href(new moodle_url(CALENDAR_URL.$linkhref), $ed['mday'], $ed['mon'], $ed['year']);
1063 $href->set_anchor('event_'.$events[$i]->id);
1064 $content .= html_writer::link($href, $events[$i]->name);
1066 else {
1067 $content .= $events[$i]->name;
1070 $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
1071 $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
1072 if ($i < $lines - 1) $content .= '<hr />';
1075 return $content;
1078 function calendar_add_month($month, $year) {
1079 if($month == 12) {
1080 return array(1, $year + 1);
1082 else {
1083 return array($month + 1, $year);
1087 function calendar_sub_month($month, $year) {
1088 if($month == 1) {
1089 return array(12, $year - 1);
1091 else {
1092 return array($month - 1, $year);
1096 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1097 $eventsbyday = array();
1098 $typesbyday = array();
1099 $durationbyday = array();
1101 if($events === false) {
1102 return;
1105 foreach($events as $event) {
1107 $startdate = usergetdate($event->timestart);
1108 // Set end date = start date if no duration
1109 if ($event->timeduration) {
1110 $enddate = usergetdate($event->timestart + $event->timeduration - 1);
1111 } else {
1112 $enddate = $startdate;
1115 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
1116 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1117 // Out of bounds
1118 continue;
1121 $eventdaystart = intval($startdate['mday']);
1123 if($startdate['mon'] == $month && $startdate['year'] == $year) {
1124 // Give the event to its day
1125 $eventsbyday[$eventdaystart][] = $event->id;
1127 // Mark the day as having such an event
1128 if($event->courseid == SITEID && $event->groupid == 0) {
1129 $typesbyday[$eventdaystart]['startglobal'] = true;
1130 // Set event class for global event
1131 $events[$event->id]->class = 'calendar_event_global';
1133 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1134 $typesbyday[$eventdaystart]['startcourse'] = true;
1135 // Set event class for course event
1136 $events[$event->id]->class = 'calendar_event_course';
1138 else if($event->groupid) {
1139 $typesbyday[$eventdaystart]['startgroup'] = true;
1140 // Set event class for group event
1141 $events[$event->id]->class = 'calendar_event_group';
1143 else if($event->userid) {
1144 $typesbyday[$eventdaystart]['startuser'] = true;
1145 // Set event class for user event
1146 $events[$event->id]->class = 'calendar_event_user';
1150 if($event->timeduration == 0) {
1151 // Proceed with the next
1152 continue;
1155 // The event starts on $month $year or before. So...
1156 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
1158 // Also, it ends on $month $year or later...
1159 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
1161 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1162 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
1163 $durationbyday[$i][] = $event->id;
1164 if($event->courseid == SITEID && $event->groupid == 0) {
1165 $typesbyday[$i]['durationglobal'] = true;
1167 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1168 $typesbyday[$i]['durationcourse'] = true;
1170 else if($event->groupid) {
1171 $typesbyday[$i]['durationgroup'] = true;
1173 else if($event->userid) {
1174 $typesbyday[$i]['durationuser'] = true;
1179 return;
1182 function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1183 $module = get_coursemodule_from_instance($modulename, $instance);
1185 if($module === false) return false;
1186 if(!calendar_get_course_cached($coursecache, $module->course)) {
1187 return false;
1189 return $module;
1192 function calendar_get_course_cached(&$coursecache, $courseid) {
1193 global $COURSE, $DB;
1195 if (!isset($coursecache[$courseid])) {
1196 if ($courseid == $COURSE->id) {
1197 $coursecache[$courseid] = $COURSE;
1198 } else {
1199 $coursecache[$courseid] = $DB->get_record('course', array('id'=>$courseid));
1202 return $coursecache[$courseid];
1205 function calendar_session_vars($course=null) {
1206 global $SESSION, $USER;
1208 if(!isset($SESSION->cal_course_referer)) {
1209 $SESSION->cal_course_referer = 0;
1211 if(!isset($SESSION->cal_show_global)) {
1212 $SESSION->cal_show_global = true;
1214 if(!isset($SESSION->cal_show_groups)) {
1215 $SESSION->cal_show_groups = true;
1217 if(!isset($SESSION->cal_show_course)) {
1218 $SESSION->cal_show_course = true;
1220 if(!isset($SESSION->cal_show_user)) {
1221 $SESSION->cal_show_user = true;
1223 if ($course !== null) {
1224 // speedup hack for calendar related blocks
1225 if(isset($course->coursenode)) {
1226 // coursenode has been set up, which seems to break things further down the line.
1227 // Use a clone of $course with coursenode removed.
1228 $course = clone $course;
1229 unset($course->coursenode);
1231 $SESSION->cal_courses_shown = array($course->id => $course);
1232 } else {
1233 $SESSION->cal_courses_shown = calendar_get_default_courses(true);
1235 if(empty($SESSION->cal_users_shown)) {
1236 // The empty() instead of !isset() here makes a whole world of difference,
1237 // as it will automatically change to the user's id when the user first logs
1238 // in. With !isset(), it would never do that.
1239 $SESSION->cal_users_shown = isloggedin() ? $USER->id : false;
1240 } else if(is_numeric($SESSION->cal_users_shown) && isloggedin() && $SESSION->cal_users_shown != $USER->id) {
1241 // Follow the white rabbit, for example if a teacher logs in as a student
1242 $SESSION->cal_users_shown = $USER->id;
1246 function calendar_set_referring_course($courseid) {
1247 global $SESSION;
1248 $SESSION->cal_course_referer = intval($courseid);
1251 function calendar_set_filters(&$courses, &$group, &$user, $courseeventsfrom = NULL, $groupeventsfrom = NULL, $ignorefilters = false) {
1252 global $SESSION, $USER, $CFG, $DB;
1254 // Insidious bug-wannabe: setting $SESSION->cal_courses_shown to $course->id would cause
1255 // the code to function incorrectly UNLESS we convert it to an integer. One case where
1256 // PHP's loose type system works against us.
1257 if(is_string($SESSION->cal_courses_shown)) {
1258 $SESSION->cal_courses_shown = intval($SESSION->cal_courses_shown);
1260 if($courseeventsfrom === NULL) {
1261 $courseeventsfrom = $SESSION->cal_courses_shown;
1264 // MDL-9059, $courseeventsfrom can be an int, or an array of ints, or an array of course objects
1265 // convert all to array of objects
1266 // we probably should do some clean up and make sure that session is set to use the proper form
1267 if (is_int($courseeventsfrom)) { // case of an int, e.g. calendar view page
1268 $c = array();
1269 $c[$courseeventsfrom] = $DB->get_record('course', array('id'=>$courseeventsfrom));
1270 $courseeventsfrom = $c;
1271 } else if (is_array($courseeventsfrom)) { // case of an array of ints, e.g. course home page
1272 foreach ($courseeventsfrom as $i=>$courseid) { // TODO: this seems wrong, the array is often constructed as [courseid] => 1 ???
1273 if (is_int($courseid)) {
1274 $courseeventsfrom[$i] = $DB->get_record('course', array('id'=>$courseid));
1279 if($groupeventsfrom === NULL) {
1280 $groupeventsfrom = $SESSION->cal_courses_shown;
1283 if(($SESSION->cal_show_course && $SESSION->cal_show_global) || $ignorefilters) {
1284 if(is_int($courseeventsfrom)) {
1285 $courses = array(SITEID, $courseeventsfrom);
1287 else if(is_array($courseeventsfrom)) {
1288 $courses = array_keys($courseeventsfrom);
1289 $courses[] = SITEID;
1292 else if($SESSION->cal_show_course) {
1293 if(is_int($courseeventsfrom)) {
1294 $courses = array($courseeventsfrom);
1296 else if(is_array($courseeventsfrom)) {
1297 $courses = array_keys($courseeventsfrom);
1299 $courses = array_diff($courses, array(SITEID));
1301 else if($SESSION->cal_show_global) {
1302 $courses = array(SITEID);
1304 else {
1305 $courses = false;
1307 //BUG 6130 clean $courses array as SESSION has bad entries.
1308 // [pj] TODO: See if this has to do with my new change in get_default_courses and can be taken out
1309 if (is_array($courses)) {
1310 foreach ($courses as $index => $value) {
1311 if (empty($value)) unset($courses[$index]);
1314 // Sort courses for consistent colour highlighting
1315 // Effectively ignoring SITEID as setting as last course id
1316 $key = array_search(SITEID, $courses);
1317 if ($key !== false) {
1318 unset($courses[$key]);
1319 sort($courses);
1320 $courses[] = SITEID;
1321 } else {
1322 sort($courses);
1326 if($SESSION->cal_show_user || $ignorefilters) {
1327 // This doesn't work for arrays yet (maybe someday it will)
1328 $user = $SESSION->cal_users_shown;
1330 else {
1331 $user = false;
1333 if($SESSION->cal_show_groups || $ignorefilters) {
1334 if(is_int($groupeventsfrom)) {
1335 $groupcourses = array($groupeventsfrom);
1337 else if(is_array($groupeventsfrom)) {
1338 $groupcourses = array_keys($groupeventsfrom);
1341 // XXX TODO: not sure how to replace $CFG->calendar_adminseesall
1342 if(has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM)) && !empty($CFG->calendar_adminseesall)) {
1343 $group = true;
1345 else {
1346 $grouparray = array();
1348 // We already have the courses to examine in $courses
1349 // For each course...
1351 foreach($groupcourses as $courseid) {
1353 if (!isset($courseeventsfrom[$courseid]->context)) { // SHOULD be set MDL-11221
1354 if (is_object($courseeventsfrom[$courseid])) {
1355 $courseeventsfrom[$courseid]->context = get_context_instance(CONTEXT_COURSE, $courseid);
1359 // If the user is an editing teacher in there,
1360 if (isloggedin() && isset($courseeventsfrom[$courseid]->context) && has_capability('moodle/calendar:manageentries', $courseeventsfrom[$courseid]->context)) {
1361 // If this course has groups, show events from all of them
1362 if(is_int($groupeventsfrom)) {
1363 if (is_object($courseeventsfrom[$courseid])) { // SHOULD be set MDL-11221
1364 $courserecord = $courseeventsfrom[$courseid];
1365 } else {
1366 $courserecord = $DB->get_record('course', array('id'=>$courseid));
1368 $courserecord = $DB->get_record('course', array('id'=>$courseid));
1369 if ($courserecord->groupmode != NOGROUPS || !$courserecord->groupmodeforce) {
1370 $groupids[] = $courseid;
1373 else if(isset($SESSION->cal_courses_shown[$courseid]) && ($SESSION->cal_courses_shown[$courseid]->groupmode != NOGROUPS || !$SESSION->cal_courses_shown[$courseid]->groupmodeforce)) {
1374 $groupids[] = $courseid;
1378 // Otherwise (not editing teacher) show events from the group he is a member of
1379 else if(isset($USER->groupmember[$courseid])) {
1380 //changed to 2D array
1381 foreach ($USER->groupmember[$courseid] as $groupid){
1382 $grouparray[] = $groupid;
1387 if (!empty($groupids)) {
1388 $sql = "SELECT *
1389 FROM {groups}
1390 WHERE courseid IN (".implode(',', $groupids).')';
1392 if ($grouprecords = $DB->get_records_sql($sql, null)) {
1393 foreach ($grouprecords as $grouprecord) {
1394 $grouparray[] = $grouprecord->id;
1399 if(empty($grouparray)) {
1400 $group = false;
1402 else {
1403 $group = $grouparray;
1408 else {
1409 $group = false;
1413 function calendar_edit_event_allowed($event) {
1414 global $USER, $DB;
1416 // Must be logged in
1417 if (!isloggedin()) {
1418 return false;
1421 // can not be using guest account
1422 if (isguestuser()) {
1423 return false;
1426 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1427 // if user has manageentries at site level, return true
1428 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1429 return true;
1432 // if groupid is set, it's definitely a group event
1433 if (!empty($event->groupid)) {
1434 // Allow users to add/edit group events if:
1435 // 1) They have manageentries (= entries for whole course)
1436 // 2) They have managegroupentries AND are in the group
1437 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1438 return $group && (
1439 has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $group->courseid)) ||
1440 (has_capability('moodle/calendar:managegroupentries', get_context_instance(CONTEXT_COURSE, $group->courseid))
1441 && groups_is_member($event->groupid)));
1442 } else if (!empty($event->courseid)) {
1443 // if groupid is not set, but course is set,
1444 // it's definiely a course event
1445 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $event->courseid));
1446 } else if (!empty($event->userid) && $event->userid == $USER->id) {
1447 // if course is not set, but userid id set, it's a user event
1448 return (has_capability('moodle/calendar:manageownentries', $sitecontext));
1450 return false;
1453 function calendar_get_default_courses($ignoreref = false) {
1454 global $USER, $CFG, $SESSION, $DB;
1456 if(!empty($SESSION->cal_course_referer) && !$ignoreref) {
1457 return array($SESSION->cal_course_referer => 1);
1460 if (!isloggedin()) {
1461 return array();
1464 $courses = array();
1465 if (has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
1466 if (!empty($CFG->calendar_adminseesall)) {
1467 $courses = $DB->get_records_sql('SELECT id, 1 FROM {course}');
1468 return $courses;
1472 $courses = enrol_get_my_courses();
1474 return $courses;
1477 function calendar_preferences_button() {
1478 global $CFG, $USER;
1480 // Guests have no preferences
1481 if (!isloggedin() || isguestuser()) {
1482 return '';
1485 return "<form method=\"get\" ".
1486 " action=\"$CFG->wwwroot/calendar/preferences.php\">".
1487 "<div><input type=\"submit\" value=\"".get_string("preferences", "calendar")." ...\" /></div></form>";
1490 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime=0) {
1491 $startdate = usergetdate($event->timestart);
1492 $enddate = usergetdate($event->timestart + $event->timeduration);
1493 $usermidnightstart = usergetmidnight($event->timestart);
1495 if($event->timeduration) {
1496 // To avoid doing the math if one IF is enough :)
1497 $usermidnightend = usergetmidnight($event->timestart + $event->timeduration);
1499 else {
1500 $usermidnightend = $usermidnightstart;
1503 if (empty($linkparams) || !is_array($linkparams)) {
1504 $linkparams = array();
1506 $linkparams['view'] = 'day';
1508 // OK, now to get a meaningful display...
1509 // First of all we have to construct a human-readable date/time representation
1511 if($event->timeduration) {
1512 // It has a duration
1513 if($usermidnightstart == $usermidnightend ||
1514 ($event->timestart == $usermidnightstart) && ($event->timeduration == 86400 || $event->timeduration == 86399) ||
1515 ($event->timestart + $event->timeduration <= $usermidnightstart + 86400)) {
1516 // But it's all on the same day
1517 $timestart = calendar_time_representation($event->timestart);
1518 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1519 $time = $timestart.' <strong>&raquo;</strong> '.$timeend;
1521 if ($event->timestart == $usermidnightstart && ($event->timeduration == 86400 || $event->timeduration == 86399)) {
1522 $time = get_string('allday', 'calendar');
1525 // Set printable representation
1526 if (!$showtime) {
1527 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1528 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1529 $eventtime = html_writer::link($url, $day).', '.$time;
1530 } else {
1531 $eventtime = $time;
1533 } else {
1534 // It spans two or more days
1535 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords).', ';
1536 if ($showtime == $usermidnightstart) {
1537 $daystart = '';
1539 $timestart = calendar_time_representation($event->timestart);
1540 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords).', ';
1541 if ($showtime == $usermidnightend) {
1542 $dayend = '';
1544 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1546 // Set printable representation
1547 if ($now >= $usermidnightstart && $now < ($usermidnightstart + 86400)) {
1548 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1549 $eventtime = $timestart.' <strong>&raquo;</strong> '.html_writer::link($url, $dayend).$timeend;
1550 } else {
1551 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1552 $eventtime = html_writer::link($url, $daystart).$timestart.' <strong>&raquo;</strong> ';
1554 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1555 $eventtime .= html_writer::link($url, $dayend).$timeend;
1558 } else {
1559 $time = ' ';
1561 // Set printable representation
1562 if (!$showtime) {
1563 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1564 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1565 $eventtime = html_writer::link($url, $day).trim($time);
1566 } else {
1567 $eventtime = $time;
1571 if($event->timestart + $event->timeduration < $now) {
1572 // It has expired
1573 $eventtime = '<span class="dimmed_text">'.str_replace(' href=', ' class="dimmed" href=', $eventtime).'</span>';
1576 return $eventtime;
1579 function calendar_print_month_selector($name, $selected) {
1580 $months = array();
1581 for ($i=1; $i<=12; $i++) {
1582 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
1584 echo html_writer::select($months, $name, $selected, false);
1587 function calendar_get_filters_status() {
1588 global $SESSION;
1590 $status = 0;
1591 if($SESSION->cal_show_global) {
1592 $status += 1;
1594 if($SESSION->cal_show_course) {
1595 $status += 2;
1597 if($SESSION->cal_show_groups) {
1598 $status += 4;
1600 if($SESSION->cal_show_user) {
1601 $status += 8;
1603 return $status;
1606 function calendar_set_filters_status($packed_bitfield) {
1607 global $SESSION, $USER;
1609 if (!isloggedin()) {
1610 return false;
1613 $SESSION->cal_show_global = ($packed_bitfield & 1);
1614 $SESSION->cal_show_course = ($packed_bitfield & 2);
1615 $SESSION->cal_show_groups = ($packed_bitfield & 4);
1616 $SESSION->cal_show_user = ($packed_bitfield & 8);
1618 return true;
1621 function calendar_get_allowed_types(&$allowed) {
1622 global $USER, $CFG, $SESSION, $DB;
1623 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1624 $allowed->user = has_capability('moodle/calendar:manageownentries', $sitecontext);
1625 $allowed->groups = false; // This may change just below
1626 $allowed->courses = false; // This may change just below
1627 $allowed->site = has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, SITEID));
1629 if(!empty($SESSION->cal_course_referer) && $SESSION->cal_course_referer != SITEID) {
1630 $course = $DB->get_record('course', array('id'=>$SESSION->cal_course_referer));
1631 $coursecontext = get_context_instance(CONTEXT_COURSE, $SESSION->cal_course_referer);
1633 if(has_capability('moodle/calendar:manageentries', $coursecontext)) {
1634 $allowed->courses = array($course->id => 1);
1636 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1637 $allowed->groups = groups_get_all_groups($SESSION->cal_course_referer);
1639 } else if(has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
1640 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1641 $allowed->groups = groups_get_all_groups($SESSION->cal_course_referer, $USER->id);
1648 * see if user can add calendar entries at all
1649 * used to print the "New Event" button
1650 * @return bool
1652 function calendar_user_can_add_event() {
1653 calendar_get_allowed_types($allowed);
1654 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);
1658 * Check wether the current user is permitted to add events
1660 * @param object $event
1661 * @return bool
1663 function calendar_add_event_allowed($event) {
1664 global $USER, $DB;
1666 // can not be using guest account
1667 if (!isloggedin() or isguestuser()) {
1668 return false;
1671 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1672 // if user has manageentries at site level, always return true
1673 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1674 return true;
1677 switch ($event->eventtype) {
1678 case 'course':
1679 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $event->courseid));
1681 case 'group':
1682 // Allow users to add/edit group events if:
1683 // 1) They have manageentries (= entries for whole course)
1684 // 2) They have managegroupentries AND are in the group
1685 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1686 return $group && (
1687 has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $group->courseid)) ||
1688 (has_capability('moodle/calendar:managegroupentries', get_context_instance(CONTEXT_COURSE, $group->courseid))
1689 && groups_is_member($event->groupid)));
1691 case 'user':
1692 if ($event->userid == $USER->id) {
1693 return (has_capability('moodle/calendar:manageownentries', $sitecontext));
1695 //there is no 'break;' intentionally
1697 case 'site':
1698 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, SITEID));
1700 default:
1701 if (isset($event->courseid) && $event->courseid > 0) {
1702 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $event->courseid));
1704 return false;
1709 * A class to manage calendar events
1711 * This class provides the required functionality in order to manage calendar events.
1712 * It was introduced as part of Moodle 2.0 and was created in order to provide a
1713 * better framework for dealing with calendar events in particular regard to file
1714 * handling through the new file API
1716 * @property int $id The id within the event table
1717 * @property string $name The name of the event
1718 * @property string $description The description of the event
1719 * @property int $format The format of the description FORMAT_?
1720 * @property int $courseid The course the event is associated with (0 if none)
1721 * @property int $groupid The group the event is associated with (0 if none)
1722 * @property int $userid The user the event is associated with (0 if none)
1723 * @property int $repeatid If this is a repeated event this will be set to the
1724 * id of the original
1725 * @property string $modulename If added by a module this will be the module name
1726 * @property int $instance If added by a module this will be the module instance
1727 * @property string $eventtype The event type
1728 * @property int $timestart The start time as a timestamp
1729 * @property int $timeduration The duration of the event in seconds
1730 * @property int $visible 1 if the event is visible
1731 * @property int $uuid ?
1732 * @property int $sequence ?
1733 * @property int $timemodified The time last modified as a timestamp
1735 class calendar_event {
1738 * An object containing the event properties can be accessed via the
1739 * magic __get/set methods
1740 * @var array
1742 protected $properties = null;
1744 * The converted event discription with file paths resolved
1745 * This gets populated when someone requests description for the first time
1746 * @var string
1748 protected $_description = null;
1750 * The options to use with this description editor
1751 * @var array
1753 protected $editoroptions = array(
1754 'subdirs'=>false,
1755 'forcehttps'=>false,
1756 'maxfiles'=>-1,
1757 'maxbytes'=>null,
1758 'trusttext'=>false);
1760 * The context to use with the description editor
1761 * @var object
1763 protected $editorcontext = null;
1766 * Instantiates a new event and optionally populates its properties with the
1767 * data provided
1769 * @param stdClass $data Optional. An object containing the properties to for
1770 * an event
1772 public function __construct($data=null) {
1773 global $CFG, $USER;
1775 // First convert to object if it is not already (should either be object or assoc array)
1776 if (!is_object($data)) {
1777 $data = (object)$data;
1780 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
1782 $data->eventrepeats = 0;
1784 if (empty($data->id)) {
1785 $data->id = null;
1788 // Default to a user event
1789 if (empty($data->eventtype)) {
1790 $data->eventtype = 'user';
1793 // Default to the current user
1794 if (empty($data->userid)) {
1795 $data->userid = $USER->id;
1798 if (!empty($data->timeduration) && is_array($data->timeduration)) {
1799 $data->timeduration = make_timestamp($data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'], $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
1801 if (!empty($data->description) && is_array($data->description)) {
1802 $data->format = $data->description['format'];
1803 $data->description = $data->description['text'];
1804 } else if (empty($data->description)) {
1805 $data->description = '';
1806 $data->format = editors_get_preferred_format();
1808 // Ensure form is defaulted correctly
1809 if (empty($data->format)) {
1810 $data->format = editors_get_preferred_format();
1813 $this->properties = $data;
1817 * Magic property method
1819 * Attempts to call a set_$key method if one exists otherwise falls back
1820 * to simply set the property
1822 * @param string $key
1823 * @param mixed $value
1825 public function __set($key, $value) {
1826 if (method_exists($this, 'set_'.$key)) {
1827 $this->{'set_'.$key}($value);
1829 $this->properties->{$key} = $value;
1833 * Magic get method
1835 * Attempts to call a get_$key method to return the property and ralls over
1836 * to return the raw property
1838 * @param str $key
1839 * @return mixed
1841 public function __get($key) {
1842 if (method_exists($this, 'get_'.$key)) {
1843 return $this->{'get_'.$key}();
1845 if (!isset($this->properties->{$key})) {
1846 throw new coding_exception('Undefined property requested');
1848 return $this->properties->{$key};
1852 * Stupid PHP needs an isset magic method if you use the get magic method and
1853 * still want empty calls to work.... blah ~!
1855 * @param string $key
1856 * @return bool
1858 public function __isset($key) {
1859 return !empty($this->properties->{$key});
1863 * Returns an array of editoroptions for this event: Called by __get
1864 * Please use $blah = $event->editoroptions;
1865 * @return array
1867 protected function get_editoroptions() {
1868 return $this->editoroptions;
1872 * Returns an event description: Called by __get
1873 * Please use $blah = $event->description;
1875 * @return string
1877 protected function get_description() {
1878 global $USER;
1879 if ($this->_description === null) {
1880 // Check if we have already resolved the context for this event
1881 if ($this->editorcontext === null) {
1882 // Switch on the event type to decide upon the appropriate context
1883 // to use for this event
1884 switch ($this->properties->eventtype) {
1885 case 'course':
1886 case 'group':
1887 // Course and group event files are served from the course context
1888 // and there are checks in plugin.php to ensure permissions are
1889 // followed
1890 $this->editorcontext = get_context_instance(CONTEXT_COURSE, $this->properties->courseid);
1891 break;
1892 case 'user':
1893 // User context
1894 $this->editorcontext = get_context_instance(CONTEXT_USER, $USER->id);
1895 break;
1896 case 'site':
1897 // Site context
1898 $this->editorcontext = get_context_instance(CONTEXT_SYSTEM);
1899 break;
1900 default:
1901 // Hmmmm some modules use custom eventtype strings, if that is the
1902 // case we are going to abandon using files. Anything that uses a
1903 // custom type is being added manually through code
1904 return clean_text($this->properties->description, $this->properties->format);
1905 break;
1909 // Work out the item id for the editor, if this is a repeated event then the files will
1910 // be associated with the original
1911 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
1912 $itemid = $this->properties->repeatid;
1913 } else {
1914 $itemid = $this->properties->id;
1917 // Convert file paths in the description so that things display correctly
1918 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php', $this->editorcontext->id, 'calendar', 'event_description', $itemid);
1919 // Clean the text so no nasties get through
1920 $this->_description = clean_text($this->_description, $this->properties->format);
1922 // Finally return the description
1923 return $this->_description;
1927 * Return the number of repeat events there are in this events series
1929 * @return int
1931 public function count_repeats() {
1932 global $DB;
1933 if (!empty($this->properties->repeatid)) {
1934 $this->properties->eventrepeats = $DB->count_records('event', array('repeatid'=>$this->properties->repeatid));
1935 // We don't want to count ourselves
1936 $this->properties->eventrepeats--;
1938 return $this->properties->eventrepeats;
1942 * Update or create an event within the database
1944 * Pass in a object containing the event properties and this function will
1945 * insert it into the database and deal with any associated files
1947 * @see add_event()
1948 * @see update_event()
1950 * @param stdClass $data
1952 public function update($data) {
1953 global $CFG, $DB, $USER;
1955 foreach ($data as $key=>$value) {
1956 $this->properties->$key = $value;
1959 $this->properties->timemodified = time();
1960 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
1962 if (empty($this->properties->id) || $this->properties->id < 1) {
1964 if (!calendar_add_event_allowed($this->properties)) {
1965 print_error('nopermissions');
1968 if ($usingeditor) {
1969 switch ($this->properties->eventtype) {
1970 case 'user':
1971 $this->editorcontext = get_context_instance(CONTEXT_USER, $USER->id);
1972 $this->properties->courseid = 0;
1973 $this->properties->groupid = 0;
1974 $this->properties->userid = $USER->id;
1975 break;
1976 case 'site':
1977 $this->editorcontext = get_context_instance(CONTEXT_SYSTEM);
1978 $this->properties->courseid = SITEID;
1979 $this->properties->groupid = 0;
1980 $this->properties->userid = $USER->id;
1981 break;
1982 case 'course':
1983 $this->editorcontext = get_context_instance(CONTEXT_COURSE, $this->properties->courseid);
1984 $this->properties->groupid = 0;
1985 $this->properties->userid = $USER->id;
1986 break;
1987 case 'group':
1988 $this->editorcontext = get_context_instance(CONTEXT_COURSE, $this->properties->courseid);
1989 $this->properties->userid = $USER->id;
1990 break;
1991 default:
1992 // Ewww we should NEVER get here, but just incase we do lets
1993 // fail gracefully
1994 $usingeditor = false;
1995 break;
1998 $editor = $this->properties->description;
1999 $this->properties->format = $this->properties->description['format'];
2000 $this->properties->description = $this->properties->description['text'];
2003 // Insert the event into the database
2004 $this->properties->id = $DB->insert_record('event', $this->properties);
2006 if ($usingeditor) {
2007 $this->properties->description = file_save_draft_area_files(
2008 $editor['itemid'],
2009 $this->editorcontext->id,
2010 'calendar',
2011 'event_description',
2012 $this->properties->id,
2013 $this->editoroptions,
2014 $editor['text'],
2015 $this->editoroptions['forcehttps']);
2017 $DB->set_field('event', 'description', $this->properties->description, array('id'=>$this->properties->id));
2020 // Log the event entry.
2021 add_to_log($this->properties->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2023 $repeatedids = array();
2025 if (!empty($this->properties->repeat)) {
2026 $this->properties->repeatid = $this->properties->id;
2027 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id'=>$this->properties->id));
2029 $eventcopy = clone($this->properties);
2030 unset($eventcopy->id);
2032 for($i = 1; $i < $eventcopy->repeats; $i++) {
2034 $eventcopy->timestart = ($eventcopy->timestart+WEEKSECS) + dst_offset_on($eventcopy->timestart) - dst_offset_on($eventcopy->timestart+WEEKSECS);
2036 // Get the event id for the log record.
2037 $eventcopyid = $DB->insert_record('event', $eventcopy);
2039 // If the context has been set delete all associated files
2040 if ($usingeditor) {
2041 $fs = get_file_storage();
2042 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
2043 foreach ($files as $file) {
2044 $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
2048 $repeatedids[] = $eventcopyid;
2049 // Log the event entry.
2050 add_to_log($eventcopy->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$eventcopyid, $eventcopy->name);
2054 // Hook for tracking added events
2055 self::calendar_event_hook('add_event', array($this->properties, $repeatedids));
2056 return true;
2057 } else {
2059 if(!calendar_edit_event_allowed($this->properties)) {
2060 print_error('nopermissions');
2063 if ($usingeditor) {
2064 if ($this->editorcontext !== null) {
2065 $this->properties->description = file_save_draft_area_files(
2066 $this->properties->description['itemid'],
2067 $this->editorcontext->id,
2068 'calendar',
2069 'event_description',
2070 $this->properties->id,
2071 $this->editoroptions,
2072 $this->properties->description['text'],
2073 $this->editoroptions['forcehttps']);
2074 } else {
2075 $this->properties->format = $this->properties->description['format'];
2076 $this->properties->description = $this->properties->description['text'];
2080 $event = $DB->get_record('event', array('id'=>$this->properties->id));
2082 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
2084 if ($updaterepeated) {
2085 // Update all
2086 if ($this->properties->timestart != $event->timestart) {
2087 $timestartoffset = $this->properties->timestart - $event->timestart;
2088 $sql = "UPDATE {event}
2089 SET name = ?,
2090 description = ?,
2091 timestart = timestart + ?,
2092 timeduration = ?,
2093 timemodified = ?
2094 WHERE repeatid = ?";
2095 $params = array($this->properties->name, $this->properties->description, $timestartoffset, $this->properties->timeduration, time(), $event->repeatid);
2096 } else {
2097 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
2098 $params = array($this->properties->name, $this->properties->description, $this->properties->timeduration, time(), $event->repeatid);
2100 $DB->execute($sql, $params);
2102 // Log the event update.
2103 add_to_log($this->properties->courseid, 'calendar', 'edit all', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2104 } else {
2105 $DB->update_record('event', $this->properties);
2106 $event = calendar_event::load($this->properties->id);
2107 $this->properties = $event->properties();
2108 add_to_log($this->properties->courseid, 'calendar', 'edit', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2111 // Hook for tracking event updates
2112 self::calendar_event_hook('update_event', array($this->properties, $updaterepeated));
2113 return true;
2118 * Deletes an event and if selected an repeated events in the same series
2120 * This function deletes an event, any associated events if $deleterepeated=true,
2121 * and cleans up any files associated with the events.
2123 * @see delete_event()
2125 * @param bool $deleterepeated
2126 * @return bool
2128 public function delete($deleterepeated=false) {
2129 global $DB, $USER, $CFG;
2131 // If $this->properties->id is not set then something is wrong
2132 if (empty($this->properties->id)) {
2133 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
2134 return false;
2137 // Delete the event
2138 $DB->delete_records('event', array('id'=>$this->properties->id));
2140 // If the editor context hasn't already been set then set it now
2141 if ($this->editorcontext === null) {
2142 switch ($this->properties->eventtype) {
2143 case 'course':
2144 case 'group':
2145 $this->editorcontext = get_context_instance(CONTEXT_COURSE, $this->properties->courseid);
2146 break;
2147 case 'user':
2148 $this->editorcontext = get_context_instance(CONTEXT_USER, $USER->id);
2149 break;
2150 case 'site':
2151 $this->editorcontext = get_context_instance(CONTEXT_SYSTEM);
2152 break;
2153 default:
2154 // There is a chance we can get here as some modules use there own
2155 // eventtype strings. In this case the event has been added by code
2156 // and we don't need to worry about it anyway
2157 break;
2161 // If the context has been set delete all associated files
2162 if ($this->editorcontext !== null) {
2163 $fs = get_file_storage();
2164 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
2165 foreach ($files as $file) {
2166 $file->delete();
2170 // Fire the event deleted hook
2171 self::calendar_event_hook('delete_event', array($this->properties->id, $deleterepeated));
2173 // If we need to delete repeated events then we will fetch them all and delete one by one
2174 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2175 // Get all records where the repeatid is the same as the event being removed
2176 $events = $DB->get_records('event', array('repeatid'=>$this->properties->repeatid));
2177 // For each of the returned events populate a calendar_event object and call delete
2178 // make sure the arg passed is false as we are already deleting all repeats
2179 foreach ($events as $event) {
2180 $event = new calendar_event($event);
2181 $event->delete(false);
2185 return true;
2189 * Fetch all event properties
2191 * This function returns all of the events properties as an object and optionally
2192 * can prepare an editor for the description field at the same time. This is
2193 * designed to work when the properties are going to be used to set the default
2194 * values of a moodle forms form.
2196 * @param bool $prepareeditor If set to true a editor is prepared for use with
2197 * the mforms editor element. (for description)
2198 * @return stdClass Object containing event properties
2200 public function properties($prepareeditor=false) {
2201 global $USER, $CFG, $DB;
2203 // First take a copy of the properties. We don't want to actually change the
2204 // properties or we'd forever be converting back and forwards between an
2205 // editor formatted description and not
2206 $properties = clone($this->properties);
2207 // Clean the description here
2208 $properties->description = clean_text($properties->description, $properties->format);
2210 // If set to true we need to prepare the properties for use with an editor
2211 // and prepare the file area
2212 if ($prepareeditor) {
2214 // We may or may not have a property id. If we do then we need to work
2215 // out the context so we can copy the existing files to the draft area
2216 if (!empty($properties->id)) {
2218 if ($properties->eventtype === 'site') {
2219 // Site context
2220 $this->editorcontext = get_context_instance(CONTEXT_SYSTEM);
2221 } else if ($properties->eventtype === 'user') {
2222 // User context
2223 $this->editorcontext = get_context_instance(CONTEXT_USER, $USER->id);
2224 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
2225 // First check the course is valid
2226 $course = $DB->get_record('course', array('id'=>$properties->courseid));
2227 if (!$course) {
2228 print_error('invalidcourse');
2230 // Course context
2231 $this->editorcontext = get_context_instance(CONTEXT_COURSE, $course->id);
2232 // We have a course and are within the course context so we had
2233 // better use the courses max bytes value
2234 $this->editoroptions['maxbytes'] = $course->maxbytes;
2235 } else {
2236 // If we get here we have a custom event type as used by some
2237 // modules. In this case the event will have been added by
2238 // code and we won't need the editor
2239 $this->editoroptions['maxbytes'] = 0;
2240 $this->editoroptions['maxfiles'] = 0;
2243 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
2244 $contextid = false;
2245 } else {
2246 // Get the context id that is what we really want
2247 $contextid = $this->editorcontext->id;
2249 } else {
2251 // If we get here then this is a new event in which case we don't need a
2252 // context as there is no existing files to copy to the draft area.
2253 $contextid = null;
2256 // If the contextid === false we don't support files so no preparing
2257 // a draft area
2258 if ($contextid !== false) {
2259 // Just encase it has already been submitted
2260 $draftiddescription = file_get_submitted_draft_itemid('description');
2261 // Prepare the draft area, this copies existing files to the draft area as well
2262 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar', 'event_description', $properties->id, $this->editoroptions, $properties->description);
2263 } else {
2264 $draftiddescription = 0;
2267 // Structure the description field as the editor requires
2268 $properties->description = array('text'=>$properties->description, 'format'=>$properties->format, 'itemid'=>$draftiddescription);
2271 // Finally return the properties
2272 return $properties;
2276 * Toggles the visibility of an event
2278 * @param null|bool $force If it is left null the events visibility is flipped,
2279 * If it is false the event is made hidden, if it is true it
2280 * is made visible.
2282 public function toggle_visibility($force=null) {
2283 global $CFG, $DB;
2285 // Set visible to the default if it is not already set
2286 if (empty($this->properties->visible)) {
2287 $this->properties->visible = 1;
2290 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
2291 // Make this event visible
2292 $this->properties->visible = 1;
2293 // Fire the hook
2294 self::calendar_event_hook('show_event', array($this->properties));
2295 } else {
2296 // Make this event hidden
2297 $this->properties->visible = 0;
2298 // Fire the hook
2299 self::calendar_event_hook('hide_event', array($this->properties));
2302 // Update the database to reflect this change
2303 return $DB->set_field('event', 'visible', $this->properties->visible, array('id'=>$this->properties->id));
2307 * Attempts to call the hook for the specified action should a calendar type
2308 * by set $CFG->calendar, and the appopriate function defined
2310 * @static
2311 * @staticvar bool $extcalendarinc Used to track the inclusion of the calendar lib
2312 * @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
2313 * @param array $args The args to pass to the hook, usually the event is the first element
2314 * @return bool
2316 public static function calendar_event_hook($action, array $args) {
2317 global $CFG;
2318 static $extcalendarinc;
2319 if ($extcalendarinc === null) {
2320 if (!empty($CFG->calendar) && file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
2321 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
2322 $extcalendarinc = true;
2323 } else {
2324 $extcalendarinc = false;
2327 if($extcalendarinc === false) {
2328 return false;
2330 $hook = $CFG->calendar .'_'.$action;
2331 if (function_exists($hook)) {
2332 call_user_func_array($hook, $args);
2333 return true;
2335 return false;
2339 * Returns a calendar_event object when provided with an event id
2341 * This function makes use of MUST_EXIST, if the event id passed in is invalid
2342 * it will result in an exception being thrown
2344 * @param int|object $param
2345 * @return calendar_event|false
2347 public static function load($param) {
2348 global $DB;
2349 if (is_object($param)) {
2350 $event = new calendar_event($param);
2351 } else {
2352 $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST);
2353 $event = new calendar_event($event);
2355 return $event;
2359 * Creates a new event and returns a calendar_event object
2361 * @param object|array $properties An object containing event properties
2362 * @return calendar_event|false The event object or false if it failed
2364 public static function create($properties) {
2365 if (is_array($properties)) {
2366 $properties = (object)$properties;
2368 if (!is_object($properties)) {
2369 throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2371 $event = new calendar_event();
2372 if ($event->update($properties)) {
2373 return $event;
2374 } else {
2375 return false;
2381 * Calendar information class
2383 * This class is used simply to organise the information pertaining to a calendar
2384 * and is used primarily to make information easily available.
2386 class calendar_information {
2388 * The day
2389 * @var int
2391 public $day;
2393 * The month
2394 * @var int
2396 public $month;
2398 * The year
2399 * @var int
2401 public $year;
2404 * A course id
2405 * @var int
2407 public $courseid = null;
2409 * An array of courses
2410 * @var array
2412 public $courses = array();
2414 * An array of groups
2415 * @var array
2417 public $groups = array();
2419 * An array of users
2420 * @var array
2422 public $users = array();
2425 * Creates a new instance
2427 * @param int $day
2428 * @param int $month
2429 * @param int $year
2431 public function __construct($day, $month, $year) {
2432 $this->day = $day;
2433 $this->month = $month;
2434 $this->year = $year;
2438 * Ensures the date for the calendar is correct and either sets it to now
2439 * or throws a moodle_exception if not
2441 * @param bool $defaultonow
2442 * @return bool
2444 public function checkdate($defaultonow = true) {
2445 if (!checkdate($this->month, $this->day, $this->year)) {
2446 if ($defaultonow) {
2447 $now = usergetdate(time());
2448 $this->day = intval($now['mday']);
2449 $this->month = intval($now['mon']);
2450 $this->year = intval($now['year']);
2451 return true;
2452 } else {
2453 throw new moodle_exception('invaliddate');
2456 return true;
2459 * Gets todays timestamp for the calendar
2460 * @return int
2462 public function timestamp_today() {
2463 return make_timestamp($this->year, $this->month, $this->day);
2466 * Gets tomorrows timestamp for the calendar
2467 * @return int
2469 public function timestamp_tomorrow() {
2470 return make_timestamp($this->year, $this->month, $this->day+1);
2473 * Adds the pretend blocks for teh calendar
2475 * @param core_calendar_renderer $renderer
2476 * @param bool $showfilters
2477 * @param string|null $view
2479 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
2480 if ($showfilters) {
2481 $filters = new block_contents();
2482 $filters->content = $renderer->fake_block_filters($this->courseid, $this->day, $this->month, $this->year, $view, $this->courses);
2483 $filters->footer = '';
2484 $filters->title = get_string('eventskey', 'calendar');
2485 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
2487 $block = new block_contents;
2488 $block->content = $renderer->fake_block_threemonths($this);
2489 $block->footer = '';
2490 $block->title = get_string('monthlyview', 'calendar');
2491 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);