2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * @package core_calendar
21 * @copyright 2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 if (!defined('MOODLE_INTERNAL')) {
27 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
31 * These are read by the administration component to provide default values
35 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
37 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
40 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
42 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
45 * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
47 define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
49 // This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
50 // Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
53 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
55 define('CALENDAR_DEFAULT_WEEKEND', 65);
58 * CALENDAR_URL - path to calendar's folder
60 define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
63 * CALENDAR_TF_24 - Calendar time in 24 hours format
65 define('CALENDAR_TF_24', '%H:%M');
68 * CALENDAR_TF_12 - Calendar time in 12 hours format
70 define('CALENDAR_TF_12', '%I:%M %p');
73 * CALENDAR_EVENT_GLOBAL - Global calendar event types
75 define('CALENDAR_EVENT_GLOBAL', 1);
78 * CALENDAR_EVENT_COURSE - Course calendar event types
80 define('CALENDAR_EVENT_COURSE', 2);
83 * CALENDAR_EVENT_GROUP - group calendar event types
85 define('CALENDAR_EVENT_GROUP', 4);
88 * CALENDAR_EVENT_USER - user calendar event types
90 define('CALENDAR_EVENT_USER', 8);
94 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
96 define('CALENDAR_IMPORT_FROM_FILE', 0);
99 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
101 define('CALENDAR_IMPORT_FROM_URL', 1);
104 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
106 define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
109 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
111 define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
114 * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
116 define('CALENDAR_SUBSCRIPTION_UPDATE', 1);
119 * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
121 define('CALENDAR_SUBSCRIPTION_REMOVE', 2);
124 * CALENDAR_EVENT_USER_OVERRIDE_PRIORITY - Constant for the user override priority.
126 define('CALENDAR_EVENT_USER_OVERRIDE_PRIORITY', 9999999);
129 * Return the days of the week
131 * @return array array of days
133 function calendar_get_days() {
134 $calendartype = \core_calendar\type_factory::get_calendar_instance();
135 return $calendartype->get_weekdays();
139 * Get the subscription from a given id
142 * @param int $id id of the subscription
143 * @return stdClass Subscription record from DB
144 * @throws moodle_exception for an invalid id
146 function calendar_get_subscription($id) {
149 $cache = cache::make('core', 'calendar_subscriptions');
150 $subscription = $cache->get($id);
151 if (empty($subscription)) {
152 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
154 $cache->set($id, $subscription);
156 return $subscription;
160 * Gets the first day of the week
162 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
166 function calendar_get_starting_weekday() {
167 $calendartype = \core_calendar\type_factory::get_calendar_instance();
168 return $calendartype->get_starting_weekday();
172 * Generates the HTML for a miniature calendar
174 * @param array $courses list of course to list events from
175 * @param array $groups list of group
176 * @param array $users user's info
177 * @param int|bool $calmonth calendar month in numeric, default is set to false
178 * @param int|bool $calyear calendar month in numeric, default is set to false
179 * @param string|bool $placement the place/page the calendar is set to appear - passed on the the controls function
180 * @param int|bool $courseid id of the course the calendar is displayed on - passed on the the controls function
181 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
182 * and $calyear to support multiple calendars
183 * @return string $content return html table for mini calendar
185 function calendar_get_mini($courses, $groups, $users, $calmonth = false, $calyear = false, $placement = false,
186 $courseid = false, $time = 0) {
187 global $CFG, $OUTPUT, $PAGE;
189 // Get the calendar type we are using.
190 $calendartype = \core_calendar\type_factory::get_calendar_instance();
192 $display = new stdClass;
194 // Assume we are not displaying this month for now.
195 $display->thismonth = false;
199 // Do this check for backwards compatibility. The core should be passing a timestamp rather than month and year.
200 // If a month and year are passed they will be in Gregorian.
201 if (!empty($calmonth) && !empty($calyear)) {
202 // Ensure it is a valid date, else we will just set it to the current timestamp.
203 if (checkdate($calmonth, 1, $calyear)) {
204 $time = make_timestamp($calyear, $calmonth, 1);
208 $date = usergetdate($time);
209 if ($calmonth == $date['mon'] && $calyear == $date['year']) {
210 $display->thismonth = true;
212 // We can overwrite date now with the date used by the calendar type, if it is not Gregorian, otherwise
213 // there is no need as it is already in Gregorian.
214 if ($calendartype->get_name() != 'gregorian') {
215 $date = $calendartype->timestamp_to_date_array($time);
217 } else if (!empty($time)) {
218 // Get the specified date in the calendar type being used.
219 $date = $calendartype->timestamp_to_date_array($time);
220 $thisdate = $calendartype->timestamp_to_date_array(time());
221 if ($date['month'] == $thisdate['month'] && $date['year'] == $thisdate['year']) {
222 $display->thismonth = true;
223 // If we are the current month we want to set the date to the current date, not the start of the month.
227 // Get the current date in the calendar type being used.
229 $date = $calendartype->timestamp_to_date_array($time);
230 $display->thismonth = true;
233 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display.
235 // Get Gregorian date for the start of the month.
236 $gregoriandate = $calendartype->convert_to_gregorian($date['year'], $date['mon'], 1);
238 // Store the gregorian date values to be used later.
239 list($gy, $gm, $gd, $gh, $gmin) = array($gregoriandate['year'], $gregoriandate['month'], $gregoriandate['day'],
240 $gregoriandate['hour'], $gregoriandate['minute']);
242 // Get the max number of days in this month for this calendar type.
243 $display->maxdays = calendar_days_in_month($m, $y);
244 // Get the starting week day for this month.
245 $startwday = dayofweek(1, $m, $y);
246 // Get the days in a week.
247 $daynames = calendar_get_days();
248 // Store the number of days in a week.
249 $numberofdaysinweek = $calendartype->get_num_weekdays();
251 // Set the min and max weekday.
252 $display->minwday = calendar_get_starting_weekday();
253 $display->maxwday = $display->minwday + ($numberofdaysinweek - 1);
255 // These are used for DB queries, so we want unixtime, so we need to use Gregorian dates.
256 $display->tstart = make_timestamp($gy, $gm, $gd, $gh, $gmin, 0);
257 $display->tend = $display->tstart + ($display->maxdays * DAYSECS) - 1;
259 // Align the starting weekday to fall in our display range
260 // This is simple, not foolproof.
261 if ($startwday < $display->minwday) {
262 $startwday += $numberofdaysinweek;
265 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
266 $events = calendar_get_events($display->tstart, $display->tend, $users, $groups, $courses);
268 // Set event course class for course events
269 if (!empty($events)) {
270 foreach ($events as $eventid => $event) {
271 if (!empty($event->modulename)) {
272 $cm = get_coursemodule_from_instance($event->modulename, $event->instance);
273 if (!\core_availability\info_module::is_user_visible($cm, 0, false)) {
274 unset($events[$eventid]);
280 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
281 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
282 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
283 // arguments to this function.
284 $hrefparams = array();
285 if(!empty($courses)) {
286 $courses = array_diff($courses, array(SITEID));
287 if(count($courses) == 1) {
288 $hrefparams['course'] = reset($courses);
292 // We want to have easy access by day, since the display is on a per-day basis.
293 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
295 // Accessibility: added summary and <abbr> elements.
296 $summary = get_string('calendarheading', 'calendar', userdate($display->tstart, get_string('strftimemonthyear')));
298 $content .= '<table class="minicalendar calendartable" summary="' . $summary . '">';
299 if (($placement !== false) && ($courseid !== false)) {
300 $content .= '<caption>'. calendar_top_controls($placement, array('id' => $courseid, 'time' => $time)) .'</caption>';
302 $content .= '<tr class="weekdays">'; // Header row: day names
304 // Print out the names of the weekdays.
305 for ($i = $display->minwday; $i <= $display->maxwday; ++$i) {
306 $pos = $i % $numberofdaysinweek;
307 $content .= '<th scope="col"><abbr title="'. $daynames[$pos]['fullname'] .'">'.
308 $daynames[$pos]['shortname'] ."</abbr></th>\n";
311 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
313 // For the table display. $week is the row; $dayweek is the column.
314 $dayweek = $startwday;
316 // Paddding (the first week may have blank days in the beginning)
317 for($i = $display->minwday; $i < $startwday; ++$i) {
318 $content .= '<td class="dayblank"> </td>'."\n";
321 $weekend = CALENDAR_DEFAULT_WEEKEND;
322 if (isset($CFG->calendar_weekend)) {
323 $weekend = intval($CFG->calendar_weekend);
326 // Now display all the calendar
327 $daytime = strtotime('-1 day', $display->tstart);
328 for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
329 $cellattributes = array();
330 $daytime = strtotime('+1 day', $daytime);
331 if($dayweek > $display->maxwday) {
332 // We need to change week (table row)
333 $content .= '</tr><tr>';
334 $dayweek = $display->minwday;
338 if ($weekend & (1 << ($dayweek % $numberofdaysinweek))) {
339 // Weekend. This is true no matter what the exact range is.
340 $class = 'weekend day';
342 // Normal working day.
347 if (!empty($eventsbyday[$day])) {
348 $eventids = $eventsbyday[$day];
351 if (!empty($durationbyday[$day])) {
352 $eventids = array_unique(array_merge($eventids, $durationbyday[$day]));
355 $finishclass = false;
357 if (!empty($eventids)) {
358 // There is at least one event on this day.
360 $class .= ' hasevent';
361 $hrefparams['view'] = 'day';
362 $dayhref = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $hrefparams), 0, 0, 0, $daytime);
365 foreach ($eventids as $eventid) {
366 if (!isset($events[$eventid])) {
369 $event = new calendar_event($events[$eventid]);
371 $component = 'moodle';
372 if (!empty($event->modulename)) {
374 $popupalt = $event->modulename;
375 $component = $event->modulename;
376 } else if ($event->courseid == SITEID) { // Site event.
377 $popupicon = 'i/siteevent';
378 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event.
379 $popupicon = 'i/courseevent';
380 } else if ($event->groupid) { // Group event.
381 $popupicon = 'i/groupevent';
382 } else { // Must be a user event.
383 $popupicon = 'i/userevent';
386 if ($event->timeduration) {
387 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
388 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
389 if ($enddate['mon'] == $m && $enddate['year'] == $y && $enddate['mday'] == $day) {
394 $dayhref->set_anchor('event_'.$event->id);
396 $popupcontent .= html_writer::start_tag('div');
397 $popupcontent .= $OUTPUT->pix_icon($popupicon, $popupalt, $component);
398 // Show ical source if needed.
399 if (!empty($event->subscription) && $CFG->calendar_showicalsource) {
401 $a->name = format_string($event->name, true);
402 $a->source = $event->subscription->name;
403 $name = get_string('namewithsource', 'calendar', $a);
406 $samedate = $startdate['mon'] == $enddate['mon'] &&
407 $startdate['year'] == $enddate['year'] &&
408 $startdate['mday'] == $enddate['mday'];
411 $name = format_string($event->name, true);
413 $name = format_string($event->name, true) . ' (' . get_string('eventendtime', 'calendar') . ')';
416 $name = format_string($event->name, true);
419 $popupcontent .= html_writer::link($dayhref, $name);
420 $popupcontent .= html_writer::end_tag('div');
423 if ($display->thismonth && $day == $d) {
424 $popupdata = calendar_get_popup(true, $daytime, $popupcontent);
426 $popupdata = calendar_get_popup(false, $daytime, $popupcontent);
428 $cellattributes = array_merge($cellattributes, $popupdata);
430 // Class and cell content
431 if(isset($typesbyday[$day]['startglobal'])) {
432 $class .= ' calendar_event_global';
433 } else if(isset($typesbyday[$day]['startcourse'])) {
434 $class .= ' calendar_event_course';
435 } else if(isset($typesbyday[$day]['startgroup'])) {
436 $class .= ' calendar_event_group';
437 } else if(isset($typesbyday[$day]['startuser'])) {
438 $class .= ' calendar_event_user';
441 $class .= ' duration_finish';
443 $cell = html_writer::link($dayhref, $day);
448 $durationclass = false;
449 if (isset($typesbyday[$day]['durationglobal'])) {
450 $durationclass = ' duration_global';
451 } else if(isset($typesbyday[$day]['durationcourse'])) {
452 $durationclass = ' duration_course';
453 } else if(isset($typesbyday[$day]['durationgroup'])) {
454 $durationclass = ' duration_group';
455 } else if(isset($typesbyday[$day]['durationuser'])) {
456 $durationclass = ' duration_user';
458 if ($durationclass) {
459 $class .= ' duration '.$durationclass;
462 // If event has a class set then add it to the table day <td> tag
463 // Note: only one colour for minicalendar
464 if(isset($eventsbyday[$day])) {
465 foreach($eventsbyday[$day] as $eventid) {
466 if (!isset($events[$eventid])) {
469 $event = $events[$eventid];
470 if (!empty($event->class)) {
471 $class .= ' '.$event->class;
477 if ($display->thismonth && $day == $d) {
478 // The current cell is for today - add appropriate classes and additional information for styling.
480 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
482 if (!isset($eventsbyday[$day]) && !isset($durationbyday[$day])) {
483 $class .= ' eventnone';
484 $popupdata = calendar_get_popup(true, false);
485 $cellattributes = array_merge($cellattributes, $popupdata);
486 $cell = html_writer::link('#', $day);
488 $cell = get_accesshide($today . ' ') . $cell;
492 $cellattributes['class'] = $class;
493 $content .= html_writer::tag('td', $cell, $cellattributes);
496 // Paddding (the last week may have blank days at the end)
497 for($i = $dayweek; $i <= $display->maxwday; ++$i) {
498 $content .= '<td class="dayblank"> </td>';
500 $content .= '</tr>'; // Last row ends
502 $content .= '</table>'; // Tabular display of days ends
504 static $jsincluded = false;
506 $PAGE->requires->yui_module('moodle-calendar-info', 'Y.M.core_calendar.info.init');
513 * Gets the calendar popup
515 * It called at multiple points in from calendar_get_mini.
516 * Copied and modified from calendar_get_mini.
518 * @param bool $is_today false except when called on the current day.
519 * @param mixed $event_timestart $events[$eventid]->timestart, OR false if there are no events.
520 * @param string $popupcontent content for the popup window/layout.
521 * @return string eventid for the calendar_tooltip popup window/layout.
523 function calendar_get_popup($today = false, $timestart, $popupcontent = '') {
528 $popupcaption = get_string('today', 'calendar') . ' ';
531 if (false === $timestart) {
532 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
533 $popupcontent = get_string('eventnone', 'calendar');
536 $popupcaption .= get_string('eventsfor', 'calendar', userdate($timestart, get_string('strftimedayshort')));
540 'data-core_calendar-title' => $popupcaption,
541 'data-core_calendar-popupcontent' => $popupcontent,
546 * Gets the calendar upcoming event
548 * @param array $courses array of courses
549 * @param array|int|bool $groups array of groups, group id or boolean for all/no group events
550 * @param array|int|bool $users array of users, user id or boolean for all/no user events
551 * @param int $daysinfuture number of days in the future we 'll look
552 * @param int $maxevents maximum number of events
553 * @param int $fromtime start time
554 * @return array $output array of upcoming events
556 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
557 global $CFG, $COURSE, $DB;
559 $display = new stdClass;
560 $display->range = $daysinfuture; // How many days in the future we 'll look
561 $display->maxevents = $maxevents;
565 // Prepare "course caching", since it may save us a lot of queries
566 $coursecache = array();
569 $now = time(); // We 'll need this later
570 $usermidnighttoday = usergetmidnight($now);
573 $display->tstart = $fromtime;
575 $display->tstart = $usermidnighttoday;
578 // This works correctly with respect to the user's DST, but it is accurate
579 // only because $fromtime is always the exact midnight of some day!
580 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
582 // Get the events matching our criteria
583 $events = calendar_get_events($display->tstart, $display->tend, $users, $groups, $courses);
585 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
586 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
587 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
588 // arguments to this function.
590 $hrefparams = array();
591 if(!empty($courses)) {
592 $courses = array_diff($courses, array(SITEID));
593 if(count($courses) == 1) {
594 $hrefparams['course'] = reset($courses);
598 if ($events !== false) {
600 $modinfo = get_fast_modinfo($COURSE);
602 foreach($events as $event) {
605 if (!empty($event->modulename)) {
606 if ($event->courseid == $COURSE->id) {
607 if (isset($modinfo->instances[$event->modulename][$event->instance])) {
608 $cm = $modinfo->instances[$event->modulename][$event->instance];
609 if (!$cm->uservisible) {
614 if (!$cm = get_coursemodule_from_instance($event->modulename, $event->instance)) {
617 if (!\core_availability\info_module::is_user_visible($cm, 0, false)) {
623 if ($processed >= $display->maxevents) {
627 $event->time = calendar_format_event_time($event, $now, $hrefparams);
637 * Get a HTML link to a course.
639 * @param int $courseid the course id
640 * @return string a link to the course (as HTML); empty if the course id is invalid
642 function calendar_get_courselink($courseid) {
648 calendar_get_course_cached($coursecache, $courseid);
649 $context = context_course::instance($courseid);
650 $fullname = format_string($coursecache[$courseid]->fullname, true, array('context' => $context));
651 $url = new moodle_url('/course/view.php', array('id' => $courseid));
652 $link = html_writer::link($url, $fullname);
659 * Add calendar event metadata
661 * @param stdClass $event event info
662 * @return stdClass $event metadata
664 function calendar_add_event_metadata($event) {
665 global $CFG, $OUTPUT;
667 //Support multilang in event->name
668 $event->name = format_string($event->name,true);
670 if(!empty($event->modulename)) { // Activity event
671 // The module name is set. I will assume that it has to be displayed, and
672 // also that it is an automatically-generated event. And of course that the
673 // fields for get_coursemodule_from_instance are set correctly.
674 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
676 if ($module === false) {
680 $modulename = get_string('modulename', $event->modulename);
681 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
682 // will be used as alt text if the event icon
683 $eventtype = get_string($event->eventtype, $event->modulename);
687 $icon = $OUTPUT->pix_url('icon', $event->modulename) . '';
689 $event->icon = '<img src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" class="icon" />';
690 $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
691 $event->courselink = calendar_get_courselink($module->course);
692 $event->cmid = $module->id;
694 } else if($event->courseid == SITEID) { // Site event
695 $event->icon = '<img src="'.$OUTPUT->pix_url('i/siteevent') . '" alt="'.get_string('globalevent', 'calendar').'" class="icon" />';
696 $event->cssclass = 'calendar_event_global';
697 } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
698 $event->icon = '<img src="'.$OUTPUT->pix_url('i/courseevent') . '" alt="'.get_string('courseevent', 'calendar').'" class="icon" />';
699 $event->courselink = calendar_get_courselink($event->courseid);
700 $event->cssclass = 'calendar_event_course';
701 } else if ($event->groupid) { // Group event
702 if ($group = calendar_get_group_cached($event->groupid)) {
703 $groupname = format_string($group->name, true, context_course::instance($group->courseid));
707 $event->icon = html_writer::empty_tag('image', array('src' => $OUTPUT->pix_url('i/groupevent'),
708 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
709 $event->courselink = calendar_get_courselink($event->courseid) . ', ' . $groupname;
710 $event->cssclass = 'calendar_event_group';
711 } else if($event->userid) { // User event
712 $event->icon = '<img src="'.$OUTPUT->pix_url('i/userevent') . '" alt="'.get_string('userevent', 'calendar').'" class="icon" />';
713 $event->cssclass = 'calendar_event_user';
719 * Get calendar events
721 * @param int $tstart Start time of time range for events
722 * @param int $tend End time of time range for events
723 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
724 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
725 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
726 * @param boolean $withduration whether only events starting within time range selected
727 * or events in progress/already started selected as well
728 * @param boolean $ignorehidden whether to select only visible events or all events
729 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
731 function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration = true, $ignorehidden = true) {
736 if (empty($users) && empty($groups) && empty($courses)) {
740 // Array of filter conditions. To be concatenated by the OR operator.
744 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
745 // Events from a number of users
746 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED);
747 $filters[] = "(e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0)";
748 $params = array_merge($params, $inparamsusers);
749 } else if ($users === true) {
750 // Events from ALL users
751 $filters[] = "(e.userid != 0 AND e.courseid = 0 AND e.groupid = 0)";
753 // Boolean false (no users at all): We don't need to do anything.
756 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
757 // Events from a number of groups
758 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED);
759 $filters[] = "e.groupid $insqlgroups";
760 $params = array_merge($params, $inparamsgroups);
761 } else if ($groups === true) {
762 // Events from ALL groups
763 $filters[] = "e.groupid != 0";
765 // Boolean false (no groups at all): We don't need to do anything.
768 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
769 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED);
770 $filters[] = "(e.groupid = 0 AND e.courseid $insqlcourses)";
771 $params = array_merge($params, $inparamscourses);
772 } else if ($courses === true) {
773 // Events from ALL courses
774 $filters[] = "(e.groupid = 0 AND e.courseid != 0)";
777 // Security check: if, by now, we have NOTHING in $whereclause, then it means
778 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
779 // events no matter what. Allowing the code to proceed might return a completely
780 // valid query with only time constraints, thus selecting ALL events in that time frame!
781 if (empty($filters)) {
785 // Build our clause for the filters.
786 $filterclause = implode(' OR ', $filters);
788 // Array of where conditions for our query. To be concatenated by the AND operator.
789 $whereconditions = ["($filterclause)"];
793 $timeclause = "((e.timestart >= :tstart1 OR e.timestart + e.timeduration > :tstart2) AND e.timestart <= :tend)";
794 $params['tstart1'] = $tstart;
795 $params['tstart2'] = $tstart;
796 $params['tend'] = $tend;
798 $timeclause = "(e.timestart >= :tstart AND e.timestart <= :tend)";
799 $params['tstart'] = $tstart;
800 $params['tend'] = $tend;
802 $whereconditions[] = $timeclause;
804 // Show visible only.
806 $whereconditions[] = "(e.visible = 1)";
809 // Build the main query's WHERE clause.
810 $whereclause = implode(' AND ', $whereconditions);
812 // Build SQL subquery and conditions for filtered events based on priorities.
814 $subqueryconditions = [];
816 // Get the user's courses. Otherwise, get the default courses being shown by the calendar.
817 $usercourses = calendar_get_default_courses();
819 // Set calendar filters.
820 list($usercourses, $usergroups, $user) = calendar_set_filters($usercourses, true);
821 $subqueryparams = [];
823 // Flag to indicate whether the query needs to exclude group overrides.
824 $viewgroupsonly = false;
827 // Set filter condition for the user's events.
828 $subqueryconditions[] = "(ev.userid = :user AND ev.courseid = 0 AND ev.groupid = 0)";
829 $subqueryparams['user'] = $user;
831 foreach ($usercourses as $courseid) {
832 if (has_capability('moodle/site:accessallgroups', context_course::instance($courseid))) {
833 $usergroupmembership = groups_get_all_groups($courseid, $user, 0, 'g.id');
834 if (count($usergroupmembership) == 0) {
835 $viewgroupsonly = true;
842 // Set filter condition for the user's group events.
843 if ($usergroups === true || $viewgroupsonly) {
844 // Fetch group events, but not group overrides.
845 $subqueryconditions[] = "(ev.groupid != 0 AND ev.eventtype = 'group')";
846 } else if (!empty($usergroups)) {
847 // Fetch group events and group overrides.
848 list($inusergroups, $inusergroupparams) = $DB->get_in_or_equal($usergroups, SQL_PARAMS_NAMED);
849 $subqueryconditions[] = "(ev.groupid $inusergroups)";
850 $subqueryparams = array_merge($subqueryparams, $inusergroupparams);
853 // Get courses to be used for the subquery.
854 $subquerycourses = [];
855 if (is_array($courses)) {
856 $subquerycourses = $courses;
857 } else if (is_numeric($courses)) {
858 $subquerycourses[] = $courses;
860 // Merge with user courses, if necessary.
861 if (!empty($usercourses)) {
862 $subquerycourses = array_merge($subquerycourses, $usercourses);
863 // Make sure we remove duplicate values.
864 $subquerycourses = array_unique($subquerycourses);
867 // Set subquery filter condition for the courses.
868 if (!empty($subquerycourses)) {
869 list($incourses, $incoursesparams) = $DB->get_in_or_equal($subquerycourses, SQL_PARAMS_NAMED);
870 $subqueryconditions[] = "(ev.groupid = 0 AND ev.courseid $incourses)";
871 $subqueryparams = array_merge($subqueryparams, $incoursesparams);
874 // Build the WHERE condition for the sub-query.
875 if (!empty($subqueryconditions)) {
876 $subquerywhere = 'WHERE ' . implode(" OR ", $subqueryconditions);
879 // Merge subquery parameters to the parameters of the main query.
880 if (!empty($subqueryparams)) {
881 $params = array_merge($params, $subqueryparams);
884 // Sub-query that fetches the list of unique events that were filtered based on priority.
885 $subquery = "SELECT ev.modulename,
888 MAX(ev.priority) as priority
891 GROUP BY ev.modulename, ev.instance, ev.eventtype";
893 // Build the main query.
896 INNER JOIN ($subquery) fe
897 ON e.modulename = fe.modulename
898 AND e.instance = fe.instance
899 AND e.eventtype = fe.eventtype
900 AND (e.priority = fe.priority OR (e.priority IS NULL AND fe.priority IS NULL))
901 LEFT JOIN {modules} m
902 ON e.modulename = m.name
903 WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
904 ORDER BY e.timestart";
905 $events = $DB->get_records_sql($sql, $params);
907 if ($events === false) {
913 /** Get calendar events by id
916 * @param array $eventids list of event ids
917 * @return array Array of event entries, empty array if nothing found
920 function calendar_get_events_by_id($eventids) {
923 if (!is_array($eventids) || empty($eventids)) {
926 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
927 $wheresql = "id $wheresql";
929 return $DB->get_records_select('event', $wheresql, $params);
933 * Get control options for Calendar
935 * @param string $type of calendar
936 * @param array $data calendar information
937 * @return string $content return available control for the calender in html
939 function calendar_top_controls($type, $data) {
940 global $PAGE, $OUTPUT;
942 // Get the calendar type we are using.
943 $calendartype = \core_calendar\type_factory::get_calendar_instance();
947 // Ensure course id passed if relevant.
949 if (!empty($data['id'])) {
950 $courseid = '&course='.$data['id'];
953 // If we are passing a month and year then we need to convert this to a timestamp to
954 // support multiple calendars. No where in core should these be passed, this logic
955 // here is for third party plugins that may use this function.
956 if (!empty($data['m']) && !empty($date['y'])) {
957 if (!isset($data['d'])) {
960 if (!checkdate($data['m'], $data['d'], $data['y'])) {
963 $time = make_timestamp($data['y'], $data['m'], $data['d']);
965 } else if (!empty($data['time'])) {
966 $time = $data['time'];
971 // Get the date for the calendar type.
972 $date = $calendartype->timestamp_to_date_array($time);
974 $urlbase = $PAGE->url;
976 // We need to get the previous and next months in certain cases.
977 if ($type == 'frontpage' || $type == 'course' || $type == 'month') {
978 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
979 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
980 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
981 $prevmonthtime['hour'], $prevmonthtime['minute']);
983 $nextmonth = calendar_add_month($date['mon'], $date['year']);
984 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
985 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
986 $nextmonthtime['hour'], $nextmonthtime['minute']);
991 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false, true, $prevmonthtime);
992 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true, $nextmonthtime);
993 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view' => 'month')), false, false, false, $time);
995 if (!empty($data['id'])) {
996 $calendarlink->param('course', $data['id']);
999 $prevlink = $prevlink;
1002 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
1003 $content .= $prevlink.'<span class="hide"> | </span>';
1004 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
1005 $content .= '<span class="hide"> | </span>'. $right;
1006 $content .= "<span class=\"clearer\"><!-- --></span>\n";
1007 $content .= html_writer::end_tag('div');
1011 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false, true, $prevmonthtime);
1012 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true, $nextmonthtime);
1013 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view' => 'month')), false, false, false, $time);
1015 if (!empty($data['id'])) {
1016 $calendarlink->param('course', $data['id']);
1019 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
1020 $content .= $prevlink.'<span class="hide"> | </span>';
1021 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
1022 $content .= '<span class="hide"> | </span>'. $nextlink;
1023 $content .= "<span class=\"clearer\"><!-- --></span>";
1024 $content .= html_writer::end_tag('div');
1027 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view' => 'upcoming')), false, false, false, $time);
1028 if (!empty($data['id'])) {
1029 $calendarlink->param('course', $data['id']);
1031 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1032 $content .= html_writer::tag('div', $calendarlink, array('class'=>'centered'));
1035 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view' => 'month')), false, false, false, $time);
1036 if (!empty($data['id'])) {
1037 $calendarlink->param('course', $data['id']);
1039 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1040 $content .= html_writer::tag('h3', $calendarlink);
1043 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&', false, false, false, false, $prevmonthtime);
1044 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&', false, false, false, false, $nextmonthtime);
1046 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
1047 $content .= $prevlink . '<span class="hide"> | </span>';
1048 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1049 $content .= '<span class="hide"> | </span>' . $nextlink;
1050 $content .= '<span class="clearer"><!-- --></span>';
1051 $content .= html_writer::end_tag('div')."\n";
1054 $days = calendar_get_days();
1056 $prevtimestamp = strtotime('-1 day', $time);
1057 $nexttimestamp = strtotime('+1 day', $time);
1059 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1060 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1062 $prevname = $days[$prevdate['wday']]['fullname'];
1063 $nextname = $days[$nextdate['wday']]['fullname'];
1064 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&', false, false, false, false, $prevtimestamp);
1065 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&', false, false, false, false, $nexttimestamp);
1067 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
1068 $content .= $prevlink;
1069 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimedaydate')).'</span>';
1070 $content .= '<span class="hide"> | </span>'. $nextlink;
1071 $content .= "<span class=\"clearer\"><!-- --></span>";
1072 $content .= html_writer::end_tag('div')."\n";
1080 * Formats a filter control element.
1082 * @param moodle_url $url of the filter
1083 * @param int $type constant defining the type filter
1084 * @return string html content of the element
1086 function calendar_filter_controls_element(moodle_url $url, $type) {
1089 case CALENDAR_EVENT_GLOBAL:
1090 $typeforhumans = 'global';
1091 $class = 'calendar_event_global';
1093 case CALENDAR_EVENT_COURSE:
1094 $typeforhumans = 'course';
1095 $class = 'calendar_event_course';
1097 case CALENDAR_EVENT_GROUP:
1098 $typeforhumans = 'groups';
1099 $class = 'calendar_event_group';
1101 case CALENDAR_EVENT_USER:
1102 $typeforhumans = 'user';
1103 $class = 'calendar_event_user';
1106 if (calendar_show_event_type($type)) {
1107 $icon = $OUTPUT->pix_icon('t/hide', get_string('hide'));
1108 $str = get_string('hide'.$typeforhumans.'events', 'calendar');
1110 $icon = $OUTPUT->pix_icon('t/show', get_string('show'));
1111 $str = get_string('show'.$typeforhumans.'events', 'calendar');
1113 $content = html_writer::start_tag('li', array('class' => 'calendar_event'));
1114 $content .= html_writer::start_tag('a', array('href' => $url, 'rel' => 'nofollow'));
1115 $content .= html_writer::tag('span', $icon, array('class' => $class));
1116 $content .= html_writer::tag('span', $str, array('class' => 'eventname'));
1117 $content .= html_writer::end_tag('a');
1118 $content .= html_writer::end_tag('li');
1123 * Get the controls filter for calendar.
1125 * Filter is used to hide calendar info from the display page
1127 * @param moodle_url $returnurl return-url for filter controls
1128 * @return string $content return filter controls in html
1130 function calendar_filter_controls(moodle_url $returnurl) {
1131 global $CFG, $USER, $OUTPUT;
1133 $groupevents = true;
1134 $id = optional_param( 'id',0,PARAM_INT );
1135 $seturl = new moodle_url('/calendar/set.php', array('return' => base64_encode($returnurl->out_as_local_url(false)), 'sesskey'=>sesskey()));
1136 $content = html_writer::start_tag('ul');
1138 $seturl->param('var', 'showglobal');
1139 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GLOBAL);
1141 $seturl->param('var', 'showcourses');
1142 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_COURSE);
1144 if (isloggedin() && !isguestuser()) {
1146 // This course MIGHT have group events defined, so show the filter
1147 $seturl->param('var', 'showgroups');
1148 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GROUP);
1150 // This course CANNOT have group events, so lose the filter
1152 $seturl->param('var', 'showuser');
1153 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_USER);
1155 $content .= html_writer::end_tag('ul');
1161 * Return the representation day
1163 * @param int $tstamp Timestamp in GMT
1164 * @param int $now current Unix timestamp
1165 * @param bool $usecommonwords
1166 * @return string the formatted date/time
1168 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1170 static $shortformat;
1171 if(empty($shortformat)) {
1172 $shortformat = get_string('strftimedayshort');
1175 if($now === false) {
1179 // To have it in one place, if a change is needed
1180 $formal = userdate($tstamp, $shortformat);
1182 $datestamp = usergetdate($tstamp);
1183 $datenow = usergetdate($now);
1185 if($usecommonwords == false) {
1186 // We don't want words, just a date
1189 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1191 return get_string('today', 'calendar');
1194 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1195 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
1198 return get_string('yesterday', 'calendar');
1201 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1202 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
1205 return get_string('tomorrow', 'calendar');
1213 * return the formatted representation time
1215 * @param int $time the timestamp in UTC, as obtained from the database
1216 * @return string the formatted date/time
1218 function calendar_time_representation($time) {
1219 static $langtimeformat = NULL;
1220 if($langtimeformat === NULL) {
1221 $langtimeformat = get_string('strftimetime');
1223 $timeformat = get_user_preferences('calendar_timeformat');
1224 if(empty($timeformat)){
1225 $timeformat = get_config(NULL,'calendar_site_timeformat');
1227 // The ? is needed because the preference might be present, but empty
1228 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
1232 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1234 * @param string|moodle_url $linkbase
1235 * @param int $d The number of the day.
1236 * @param int $m The number of the month.
1237 * @param int $y The number of the year.
1238 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1239 * $m and $y are kept for backwards compatibility.
1240 * @return moodle_url|null $linkbase
1242 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1243 if (empty($linkbase)) {
1246 if (!($linkbase instanceof moodle_url)) {
1247 $linkbase = new moodle_url($linkbase);
1250 // If a day, month and year were passed then convert it to a timestamp. If these were passed
1251 // then we can assume the day, month and year are passed as Gregorian, as no where in core
1252 // should we be passing these values rather than the time.
1253 if (!empty($d) && !empty($m) && !empty($y)) {
1254 if (checkdate($m, $d, $y)) {
1255 $time = make_timestamp($y, $m, $d);
1259 } else if (empty($time)) {
1263 $linkbase->param('time', $time);
1269 * Build and return a previous month HTML link, with an arrow.
1271 * @param string $text The text label.
1272 * @param string|moodle_url $linkbase The URL stub.
1273 * @param int $d The number of the date.
1274 * @param int $m The number of the month.
1275 * @param int $y year The number of the year.
1276 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1277 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1278 * $m and $y are kept for backwards compatibility.
1279 * @return string HTML string.
1281 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1282 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y, $time);
1286 return link_arrow_left($text, (string)$href, $accesshide, 'previous');
1290 * Build and return a next month HTML link, with an arrow.
1292 * @param string $text The text label.
1293 * @param string|moodle_url $linkbase The URL stub.
1294 * @param int $d the number of the Day
1295 * @param int $m The number of the month.
1296 * @param int $y The number of the year.
1297 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1298 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1299 * $m and $y are kept for backwards compatibility.
1300 * @return string HTML string.
1302 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1303 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y, $time);
1307 return link_arrow_right($text, (string)$href, $accesshide, 'next');
1311 * Return the name of the weekday
1313 * @param string $englishname
1314 * @return string of the weekeday
1316 function calendar_wday_name($englishname) {
1317 return get_string(strtolower($englishname), 'calendar');
1321 * Return the number of days in month
1323 * @param int $month the number of the month.
1324 * @param int $year the number of the year
1327 function calendar_days_in_month($month, $year) {
1328 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1329 return $calendartype->get_num_days_in_month($year, $month);
1333 * Get the upcoming event block
1335 * @param array $events list of events
1336 * @param moodle_url|string $linkhref link to event referer
1337 * @param boolean $showcourselink whether links to courses should be shown
1338 * @return string|null $content html block content
1340 function calendar_get_block_upcoming($events, $linkhref = NULL, $showcourselink = false) {
1342 $lines = count($events);
1347 for ($i = 0; $i < $lines; ++$i) {
1348 if (!isset($events[$i]->time)) { // Just for robustness
1351 $events[$i] = calendar_add_event_metadata($events[$i]);
1352 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span>';
1353 if (!empty($events[$i]->referer)) {
1354 // That's an activity event, so let's provide the hyperlink
1355 $content .= $events[$i]->referer;
1357 if(!empty($linkhref)) {
1358 $href = calendar_get_link_href(new moodle_url(CALENDAR_URL . $linkhref), 0, 0, 0, $events[$i]->timestart);
1359 $href->set_anchor('event_'.$events[$i]->id);
1360 $content .= html_writer::link($href, $events[$i]->name);
1363 $content .= $events[$i]->name;
1366 $events[$i]->time = str_replace('»', '<br />»', $events[$i]->time);
1367 if ($showcourselink && !empty($events[$i]->courselink)) {
1368 $content .= html_writer::div($events[$i]->courselink, 'course');
1370 $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
1371 if ($i < $lines - 1) $content .= '<hr />';
1378 * Get the next following month
1380 * @param int $month the number of the month.
1381 * @param int $year the number of the year.
1382 * @return array the following month
1384 function calendar_add_month($month, $year) {
1385 // Get the calendar type we are using.
1386 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1387 return $calendartype->get_next_month($year, $month);
1391 * Get the previous month.
1393 * @param int $month the number of the month.
1394 * @param int $year the number of the year.
1395 * @return array previous month
1397 function calendar_sub_month($month, $year) {
1398 // Get the calendar type we are using.
1399 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1400 return $calendartype->get_prev_month($year, $month);
1404 * Get per-day basis events
1406 * @param array $events list of events
1407 * @param int $month the number of the month
1408 * @param int $year the number of the year
1409 * @param array $eventsbyday event on specific day
1410 * @param array $durationbyday duration of the event in days
1411 * @param array $typesbyday event type (eg: global, course, user, or group)
1412 * @param array $courses list of courses
1415 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1416 // Get the calendar type we are using.
1417 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1419 $eventsbyday = array();
1420 $typesbyday = array();
1421 $durationbyday = array();
1423 if($events === false) {
1427 foreach ($events as $event) {
1428 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
1429 // Set end date = start date if no duration
1430 if ($event->timeduration) {
1431 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
1433 $enddate = $startdate;
1436 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
1437 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1442 $eventdaystart = intval($startdate['mday']);
1444 if($startdate['mon'] == $month && $startdate['year'] == $year) {
1445 // Give the event to its day
1446 $eventsbyday[$eventdaystart][] = $event->id;
1448 // Mark the day as having such an event
1449 if($event->courseid == SITEID && $event->groupid == 0) {
1450 $typesbyday[$eventdaystart]['startglobal'] = true;
1451 // Set event class for global event
1452 $events[$event->id]->class = 'calendar_event_global';
1454 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1455 $typesbyday[$eventdaystart]['startcourse'] = true;
1456 // Set event class for course event
1457 $events[$event->id]->class = 'calendar_event_course';
1459 else if($event->groupid) {
1460 $typesbyday[$eventdaystart]['startgroup'] = true;
1461 // Set event class for group event
1462 $events[$event->id]->class = 'calendar_event_group';
1464 else if($event->userid) {
1465 $typesbyday[$eventdaystart]['startuser'] = true;
1466 // Set event class for user event
1467 $events[$event->id]->class = 'calendar_event_user';
1471 if($event->timeduration == 0) {
1472 // Proceed with the next
1476 // The event starts on $month $year or before. So...
1477 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
1479 // Also, it ends on $month $year or later...
1480 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
1482 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1483 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
1484 $durationbyday[$i][] = $event->id;
1485 if($event->courseid == SITEID && $event->groupid == 0) {
1486 $typesbyday[$i]['durationglobal'] = true;
1488 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1489 $typesbyday[$i]['durationcourse'] = true;
1491 else if($event->groupid) {
1492 $typesbyday[$i]['durationgroup'] = true;
1494 else if($event->userid) {
1495 $typesbyday[$i]['durationuser'] = true;
1504 * Get current module cache
1506 * @param array $coursecache list of course cache
1507 * @param string $modulename name of the module
1508 * @param int $instance module instance number
1509 * @return stdClass|bool $module information
1511 function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1512 $module = get_coursemodule_from_instance($modulename, $instance);
1514 if($module === false) return false;
1515 if(!calendar_get_course_cached($coursecache, $module->course)) {
1522 * Get current course cache
1524 * @param array $coursecache list of course cache
1525 * @param int $courseid id of the course
1526 * @return stdClass $coursecache[$courseid] return the specific course cache
1528 function calendar_get_course_cached(&$coursecache, $courseid) {
1529 if (!isset($coursecache[$courseid])) {
1530 $coursecache[$courseid] = get_course($courseid);
1532 return $coursecache[$courseid];
1536 * Get group from groupid for calendar display
1538 * @param int $groupid
1539 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1541 function calendar_get_group_cached($groupid) {
1542 static $groupscache = array();
1543 if (!isset($groupscache[$groupid])) {
1544 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1546 return $groupscache[$groupid];
1550 * Returns the courses to load events for, the
1552 * @param array $courseeventsfrom An array of courses to load calendar events for
1553 * @param bool $ignorefilters specify the use of filters, false is set as default
1554 * @return array An array of courses, groups, and user to load calendar events for based upon filters
1556 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
1557 global $USER, $CFG, $DB;
1559 // For backwards compatability we have to check whether the courses array contains
1560 // just id's in which case we need to load course objects.
1561 $coursestoload = array();
1562 foreach ($courseeventsfrom as $id => $something) {
1563 if (!is_object($something)) {
1564 $coursestoload[] = $id;
1565 unset($courseeventsfrom[$id]);
1568 if (!empty($coursestoload)) {
1569 // TODO remove this in 2.2
1570 debugging('calendar_set_filters now preferes an array of course objects with preloaded contexts', DEBUG_DEVELOPER);
1571 $courseeventsfrom = array_merge($courseeventsfrom, $DB->get_records_list('course', 'id', $coursestoload));
1578 // capabilities that allow seeing group events from all groups
1579 // TODO: rewrite so that moodle/calendar:manageentries is not necessary here
1580 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
1582 $isloggedin = isloggedin();
1584 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
1585 $courses = array_keys($courseeventsfrom);
1587 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
1588 $courses[] = SITEID;
1590 $courses = array_unique($courses);
1593 if (!empty($courses) && in_array(SITEID, $courses)) {
1594 // Sort courses for consistent colour highlighting
1595 // Effectively ignoring SITEID as setting as last course id
1596 $key = array_search(SITEID, $courses);
1597 unset($courses[$key]);
1598 $courses[] = SITEID;
1601 if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
1605 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
1607 if (count($courseeventsfrom)==1) {
1608 $course = reset($courseeventsfrom);
1609 if (has_any_capability($allgroupscaps, context_course::instance($course->id))) {
1610 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
1611 $group = array_keys($coursegroups);
1614 if ($group === false) {
1615 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, context_system::instance())) {
1617 } else if ($isloggedin) {
1618 $groupids = array();
1620 // We already have the courses to examine in $courses
1621 // For each course...
1622 foreach ($courseeventsfrom as $courseid => $course) {
1623 // If the user is an editing teacher in there,
1624 if (!empty($USER->groupmember[$course->id])) {
1625 // We've already cached the users groups for this course so we can just use that
1626 $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
1627 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1628 // If this course has groups, show events from all of those related to the current user
1629 $coursegroups = groups_get_user_groups($course->id, $USER->id);
1630 $groupids = array_merge($groupids, $coursegroups['0']);
1633 if (!empty($groupids)) {
1639 if (empty($courses)) {
1643 return array($courses, $group, $user);
1647 * Return the capability for editing calendar event
1649 * @param calendar_event $event event object
1650 * @return bool capability to edit event
1652 function calendar_edit_event_allowed($event) {
1655 // Must be logged in
1656 if (!isloggedin()) {
1660 // can not be using guest account
1661 if (isguestuser()) {
1665 // You cannot edit calendar subscription events presently.
1666 if (!empty($event->subscriptionid)) {
1670 $sitecontext = context_system::instance();
1671 // if user has manageentries at site level, return true
1672 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1676 // if groupid is set, it's definitely a group event
1677 if (!empty($event->groupid)) {
1678 // Allow users to add/edit group events if:
1679 // 1) They have manageentries (= entries for whole course)
1680 // 2) They have managegroupentries AND are in the group
1681 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1683 has_capability('moodle/calendar:manageentries', $event->context) ||
1684 (has_capability('moodle/calendar:managegroupentries', $event->context)
1685 && groups_is_member($event->groupid)));
1686 } else if (!empty($event->courseid)) {
1687 // if groupid is not set, but course is set,
1688 // it's definiely a course event
1689 return has_capability('moodle/calendar:manageentries', $event->context);
1690 } else if (!empty($event->userid) && $event->userid == $USER->id) {
1691 // if course is not set, but userid id set, it's a user event
1692 return (has_capability('moodle/calendar:manageownentries', $event->context));
1693 } else if (!empty($event->userid)) {
1694 return (has_capability('moodle/calendar:manageentries', $event->context));
1700 * Returns the default courses to display on the calendar when there isn't a specific
1701 * course to display.
1703 * @return array $courses Array of courses to display
1705 function calendar_get_default_courses() {
1708 if (!isloggedin()) {
1713 if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', context_system::instance())) {
1714 $select = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1715 $join = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1716 $sql = "SELECT c.* $select
1719 WHERE EXISTS (SELECT 1 FROM {event} e WHERE e.courseid = c.id)
1721 $courses = $DB->get_records_sql($sql, array('contextlevel' => CONTEXT_COURSE), 0, 20);
1722 foreach ($courses as $course) {
1723 context_helper::preload_from_record($course);
1728 $courses = enrol_get_my_courses();
1734 * Display calendar preference button
1736 * @param stdClass $course course object
1737 * @deprecated since Moodle 3.2
1738 * @todo MDL-55875 This will be deleted in Moodle 3.6.
1739 * @return string return preference button in html
1741 function calendar_preferences_button(stdClass $course) {
1744 // Guests have no preferences
1745 if (!isloggedin() || isguestuser()) {
1748 debugging('This should no longer be used, the calendar preferences are now linked to the user preferences page');
1750 return $OUTPUT->single_button(new moodle_url('/user/calendar.php'), get_string("preferences", "calendar"));
1754 * Get event format time
1756 * @param calendar_event $event event object
1757 * @param int $now current time in gmt
1758 * @param array $linkparams list of params for event link
1759 * @param bool $usecommonwords the words as formatted date/time.
1760 * @param int $showtime determine the show time GMT timestamp
1761 * @return string $eventtime link/string for event time
1763 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
1764 $starttime = $event->timestart;
1765 $endtime = $event->timestart + $event->timeduration;
1767 if (empty($linkparams) || !is_array($linkparams)) {
1768 $linkparams = array();
1771 $linkparams['view'] = 'day';
1773 // OK, now to get a meaningful display...
1774 // Check if there is a duration for this event.
1775 if ($event->timeduration) {
1776 // Get the midnight of the day the event will start.
1777 $usermidnightstart = usergetmidnight($starttime);
1778 // Get the midnight of the day the event will end.
1779 $usermidnightend = usergetmidnight($endtime);
1780 // Check if we will still be on the same day.
1781 if ($usermidnightstart == $usermidnightend) {
1782 // Check if we are running all day.
1783 if ($event->timeduration == DAYSECS) {
1784 $time = get_string('allday', 'calendar');
1785 } else { // Specify the time we will be running this from.
1786 $datestart = calendar_time_representation($starttime);
1787 $dateend = calendar_time_representation($endtime);
1788 $time = $datestart . ' <strong>»</strong> ' . $dateend;
1791 // Set printable representation.
1793 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1794 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
1795 $eventtime = html_writer::link($url, $day) . ', ' . $time;
1799 } else { // It must spans two or more days.
1800 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
1801 if ($showtime == $usermidnightstart) {
1804 $timestart = calendar_time_representation($event->timestart);
1805 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
1806 if ($showtime == $usermidnightend) {
1809 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1811 // Set printable representation.
1812 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
1813 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
1814 $eventtime = $timestart . ' <strong>»</strong> ' . html_writer::link($url, $dayend) . $timeend;
1816 // The event is in the future, print start and end links.
1817 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
1818 $eventtime = html_writer::link($url, $daystart) . $timestart . ' <strong>»</strong> ';
1820 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
1821 $eventtime .= html_writer::link($url, $dayend) . $timeend;
1824 } else { // There is no time duration.
1825 $time = calendar_time_representation($event->timestart);
1826 // Set printable representation.
1828 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1829 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
1830 $eventtime = html_writer::link($url, $day) . ', ' . trim($time);
1836 // Check if It has expired.
1837 if ($event->timestart + $event->timeduration < $now) {
1838 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
1845 * Display month selector options
1847 * @param string $name for the select element
1848 * @param string|array $selected options for select elements
1850 function calendar_print_month_selector($name, $selected) {
1852 for ($i=1; $i<=12; $i++) {
1853 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
1855 echo html_writer::label(get_string('months'), 'menu'. $name, false, array('class' => 'accesshide'));
1856 echo html_writer::select($months, $name, $selected, false);
1860 * Checks to see if the requested type of event should be shown for the given user.
1862 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
1863 * The type to check the display for (default is to display all)
1864 * @param stdClass|int|null $user The user to check for - by default the current user
1865 * @return bool True if the tyep should be displayed false otherwise
1867 function calendar_show_event_type($type, $user = null) {
1868 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1869 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
1871 if (!isset($SESSION->calendarshoweventtype)) {
1872 $SESSION->calendarshoweventtype = $default;
1874 return $SESSION->calendarshoweventtype & $type;
1876 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
1881 * Sets the display of the event type given $display.
1883 * If $display = true the event type will be shown.
1884 * If $display = false the event type will NOT be shown.
1885 * If $display = null the current value will be toggled and saved.
1887 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type object of CALENDAR_EVENT_XXX
1888 * @param bool $display option to display event type
1889 * @param stdClass|int $user moodle user object or id, null means current user
1891 function calendar_set_event_type_display($type, $display = null, $user = null) {
1892 $persist = get_user_preferences('calendar_persistflt', 0, $user);
1893 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1894 if ($persist === 0) {
1896 if (!isset($SESSION->calendarshoweventtype)) {
1897 $SESSION->calendarshoweventtype = $default;
1899 $preference = $SESSION->calendarshoweventtype;
1901 $preference = get_user_preferences('calendar_savedflt', $default, $user);
1903 $current = $preference & $type;
1904 if ($display === null) {
1905 $display = !$current;
1907 if ($display && !$current) {
1908 $preference += $type;
1909 } else if (!$display && $current) {
1910 $preference -= $type;
1912 if ($persist === 0) {
1913 $SESSION->calendarshoweventtype = $preference;
1915 if ($preference == $default) {
1916 unset_user_preference('calendar_savedflt', $user);
1918 set_user_preference('calendar_savedflt', $preference, $user);
1924 * Get calendar's allowed types
1926 * @param stdClass $allowed list of allowed edit for event type
1927 * @param stdClass|int $course object of a course or course id
1929 function calendar_get_allowed_types(&$allowed, $course = null) {
1930 global $USER, $CFG, $DB;
1931 $allowed = new stdClass();
1932 $allowed->user = has_capability('moodle/calendar:manageownentries', context_system::instance());
1933 $allowed->groups = false; // This may change just below
1934 $allowed->courses = false; // This may change just below
1935 $allowed->site = has_capability('moodle/calendar:manageentries', context_course::instance(SITEID));
1937 if (!empty($course)) {
1938 if (!is_object($course)) {
1939 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST);
1941 if ($course->id != SITEID) {
1942 $coursecontext = context_course::instance($course->id);
1943 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
1945 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
1946 $allowed->courses = array($course->id => 1);
1948 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1949 if (has_capability('moodle/site:accessallgroups', $coursecontext)) {
1950 $allowed->groups = groups_get_all_groups($course->id);
1952 $allowed->groups = groups_get_all_groups($course->id, $USER->id);
1955 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
1956 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1957 if (has_capability('moodle/site:accessallgroups', $coursecontext)) {
1958 $allowed->groups = groups_get_all_groups($course->id);
1960 $allowed->groups = groups_get_all_groups($course->id, $USER->id);
1969 * See if user can add calendar entries at all
1970 * used to print the "New Event" button
1972 * @param stdClass $course object of a course or course id
1973 * @return bool has the capability to add at least one event type
1975 function calendar_user_can_add_event($course) {
1976 if (!isloggedin() || isguestuser()) {
1979 calendar_get_allowed_types($allowed, $course);
1980 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);
1984 * Check wether the current user is permitted to add events
1986 * @param stdClass $event object of event
1987 * @return bool has the capability to add event
1989 function calendar_add_event_allowed($event) {
1992 // can not be using guest account
1993 if (!isloggedin() or isguestuser()) {
1997 $sitecontext = context_system::instance();
1998 // if user has manageentries at site level, always return true
1999 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2003 switch ($event->eventtype) {
2005 return has_capability('moodle/calendar:manageentries', $event->context);
2008 // Allow users to add/edit group events if:
2009 // 1) They have manageentries (= entries for whole course)
2010 // 2) They have managegroupentries AND are in the group
2011 $group = $DB->get_record('groups', array('id'=>$event->groupid));
2013 has_capability('moodle/calendar:manageentries', $event->context) ||
2014 (has_capability('moodle/calendar:managegroupentries', $event->context)
2015 && groups_is_member($event->groupid)));
2018 if ($event->userid == $USER->id) {
2019 return (has_capability('moodle/calendar:manageownentries', $event->context));
2021 //there is no 'break;' intentionally
2024 return has_capability('moodle/calendar:manageentries', $event->context);
2027 return has_capability('moodle/calendar:manageentries', $event->context);
2032 * Manage calendar events
2034 * This class provides the required functionality in order to manage calendar events.
2035 * It was introduced as part of Moodle 2.0 and was created in order to provide a
2036 * better framework for dealing with calendar events in particular regard to file
2037 * handling through the new file API
2039 * @package core_calendar
2040 * @category calendar
2041 * @copyright 2009 Sam Hemelryk
2042 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2044 * @property int $id The id within the event table
2045 * @property string $name The name of the event
2046 * @property string $description The description of the event
2047 * @property int $format The format of the description FORMAT_?
2048 * @property int $courseid The course the event is associated with (0 if none)
2049 * @property int $groupid The group the event is associated with (0 if none)
2050 * @property int $userid The user the event is associated with (0 if none)
2051 * @property int $repeatid If this is a repeated event this will be set to the
2052 * id of the original
2053 * @property string $modulename If added by a module this will be the module name
2054 * @property int $instance If added by a module this will be the module instance
2055 * @property string $eventtype The event type
2056 * @property int $timestart The start time as a timestamp
2057 * @property int $timeduration The duration of the event in seconds
2058 * @property int $visible 1 if the event is visible
2059 * @property int $uuid ?
2060 * @property int $sequence ?
2061 * @property int $timemodified The time last modified as a timestamp
2063 class calendar_event {
2065 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
2066 protected $properties = null;
2069 * @var string The converted event discription with file paths resolved. This gets populated when someone requests description for the first time */
2070 protected $_description = null;
2072 /** @var array The options to use with this description editor */
2073 protected $editoroptions = array(
2075 'forcehttps'=>false,
2078 'trusttext'=>false);
2080 /** @var object The context to use with the description editor */
2081 protected $editorcontext = null;
2084 * Instantiates a new event and optionally populates its properties with the
2087 * @param stdClass $data Optional. An object containing the properties to for
2090 public function __construct($data=null) {
2093 // First convert to object if it is not already (should either be object or assoc array)
2094 if (!is_object($data)) {
2095 $data = (object)$data;
2098 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
2100 $data->eventrepeats = 0;
2102 if (empty($data->id)) {
2106 if (!empty($data->subscriptionid)) {
2107 $data->subscription = calendar_get_subscription($data->subscriptionid);
2110 // Default to a user event
2111 if (empty($data->eventtype)) {
2112 $data->eventtype = 'user';
2115 // Default to the current user
2116 if (empty($data->userid)) {
2117 $data->userid = $USER->id;
2120 if (!empty($data->timeduration) && is_array($data->timeduration)) {
2121 $data->timeduration = make_timestamp($data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'], $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
2123 if (!empty($data->description) && is_array($data->description)) {
2124 $data->format = $data->description['format'];
2125 $data->description = $data->description['text'];
2126 } else if (empty($data->description)) {
2127 $data->description = '';
2128 $data->format = editors_get_preferred_format();
2130 // Ensure form is defaulted correctly
2131 if (empty($data->format)) {
2132 $data->format = editors_get_preferred_format();
2135 if (empty($data->context)) {
2136 $data->context = $this->calculate_context($data);
2138 $this->properties = $data;
2142 * Magic property method
2144 * Attempts to call a set_$key method if one exists otherwise falls back
2145 * to simply set the property
2147 * @param string $key property name
2148 * @param mixed $value value of the property
2150 public function __set($key, $value) {
2151 if (method_exists($this, 'set_'.$key)) {
2152 $this->{'set_'.$key}($value);
2154 $this->properties->{$key} = $value;
2160 * Attempts to call a get_$key method to return the property and ralls over
2161 * to return the raw property
2163 * @param string $key property name
2164 * @return mixed property value
2166 public function __get($key) {
2167 if (method_exists($this, 'get_'.$key)) {
2168 return $this->{'get_'.$key}();
2170 if (!isset($this->properties->{$key})) {
2171 throw new coding_exception('Undefined property requested');
2173 return $this->properties->{$key};
2177 * Stupid PHP needs an isset magic method if you use the get magic method and
2178 * still want empty calls to work.... blah ~!
2180 * @param string $key $key property name
2181 * @return bool|mixed property value, false if property is not exist
2183 public function __isset($key) {
2184 return !empty($this->properties->{$key});
2188 * Calculate the context value needed for calendar_event.
2189 * Event's type can be determine by the available value store in $data
2190 * It is important to check for the existence of course/courseid to determine
2192 * Default value is set to CONTEXT_USER
2194 * @param stdClass $data information about event
2195 * @return stdClass The context object.
2197 protected function calculate_context(stdClass $data) {
2201 if (isset($data->courseid) && $data->courseid > 0) {
2202 $context = context_course::instance($data->courseid);
2203 } else if (isset($data->course) && $data->course > 0) {
2204 $context = context_course::instance($data->course);
2205 } else if (isset($data->groupid) && $data->groupid > 0) {
2206 $group = $DB->get_record('groups', array('id'=>$data->groupid));
2207 $context = context_course::instance($group->courseid);
2208 } else if (isset($data->userid) && $data->userid > 0 && $data->userid == $USER->id) {
2209 $context = context_user::instance($data->userid);
2210 } else if (isset($data->userid) && $data->userid > 0 && $data->userid != $USER->id &&
2211 isset($data->instance) && $data->instance > 0) {
2212 $cm = get_coursemodule_from_instance($data->modulename, $data->instance, 0, false, MUST_EXIST);
2213 $context = context_course::instance($cm->course);
2215 $context = context_user::instance($data->userid);
2222 * Returns an array of editoroptions for this event: Called by __get
2223 * Please use $blah = $event->editoroptions;
2225 * @return array event editor options
2227 protected function get_editoroptions() {
2228 return $this->editoroptions;
2232 * Returns an event description: Called by __get
2233 * Please use $blah = $event->description;
2235 * @return string event description
2237 protected function get_description() {
2240 require_once($CFG->libdir . '/filelib.php');
2242 if ($this->_description === null) {
2243 // Check if we have already resolved the context for this event
2244 if ($this->editorcontext === null) {
2245 // Switch on the event type to decide upon the appropriate context
2246 // to use for this event
2247 $this->editorcontext = $this->properties->context;
2248 if ($this->properties->eventtype != 'user' && $this->properties->eventtype != 'course'
2249 && $this->properties->eventtype != 'site' && $this->properties->eventtype != 'group') {
2250 return clean_text($this->properties->description, $this->properties->format);
2254 // Work out the item id for the editor, if this is a repeated event then the files will
2255 // be associated with the original
2256 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2257 $itemid = $this->properties->repeatid;
2259 $itemid = $this->properties->id;
2262 // Convert file paths in the description so that things display correctly
2263 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php', $this->editorcontext->id, 'calendar', 'event_description', $itemid);
2264 // Clean the text so no nasties get through
2265 $this->_description = clean_text($this->_description, $this->properties->format);
2267 // Finally return the description
2268 return $this->_description;
2272 * Return the number of repeat events there are in this events series
2274 * @return int number of event repeated
2276 public function count_repeats() {
2278 if (!empty($this->properties->repeatid)) {
2279 $this->properties->eventrepeats = $DB->count_records('event', array('repeatid'=>$this->properties->repeatid));
2280 // We don't want to count ourselves
2281 $this->properties->eventrepeats--;
2283 return $this->properties->eventrepeats;
2287 * Update or create an event within the database
2289 * Pass in a object containing the event properties and this function will
2290 * insert it into the database and deal with any associated files
2292 * @see self::create()
2293 * @see self::update()
2295 * @param stdClass $data object of event
2296 * @param bool $checkcapability if moodle should check calendar managing capability or not
2297 * @return bool event updated
2299 public function update($data, $checkcapability=true) {
2302 foreach ($data as $key=>$value) {
2303 $this->properties->$key = $value;
2306 $this->properties->timemodified = time();
2307 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
2309 // Prepare event data.
2311 'context' => $this->properties->context,
2312 'objectid' => $this->properties->id,
2314 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
2315 'timestart' => $this->properties->timestart,
2316 'name' => $this->properties->name
2320 if (empty($this->properties->id) || $this->properties->id < 1) {
2322 if ($checkcapability) {
2323 if (!calendar_add_event_allowed($this->properties)) {
2324 print_error('nopermissiontoupdatecalendar');
2329 switch ($this->properties->eventtype) {
2331 $this->properties->courseid = 0;
2332 $this->properties->course = 0;
2333 $this->properties->groupid = 0;
2334 $this->properties->userid = $USER->id;
2337 $this->properties->courseid = SITEID;
2338 $this->properties->course = SITEID;
2339 $this->properties->groupid = 0;
2340 $this->properties->userid = $USER->id;
2343 $this->properties->groupid = 0;
2344 $this->properties->userid = $USER->id;
2347 $this->properties->userid = $USER->id;
2350 // Ewww we should NEVER get here, but just incase we do lets
2352 $usingeditor = false;
2356 // If we are actually using the editor, we recalculate the context because some default values
2357 // were set when calculate_context() was called from the constructor.
2359 $this->properties->context = $this->calculate_context($this->properties);
2360 $this->editorcontext = $this->properties->context;
2363 $editor = $this->properties->description;
2364 $this->properties->format = $this->properties->description['format'];
2365 $this->properties->description = $this->properties->description['text'];
2368 // Insert the event into the database
2369 $this->properties->id = $DB->insert_record('event', $this->properties);
2372 $this->properties->description = file_save_draft_area_files(
2374 $this->editorcontext->id,
2376 'event_description',
2377 $this->properties->id,
2378 $this->editoroptions,
2380 $this->editoroptions['forcehttps']);
2381 $DB->set_field('event', 'description', $this->properties->description, array('id'=>$this->properties->id));
2384 // Log the event entry.
2385 $eventargs['objectid'] = $this->properties->id;
2386 $eventargs['context'] = $this->properties->context;
2387 $event = \core\event\calendar_event_created::create($eventargs);
2390 $repeatedids = array();
2392 if (!empty($this->properties->repeat)) {
2393 $this->properties->repeatid = $this->properties->id;
2394 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id'=>$this->properties->id));
2396 $eventcopy = clone($this->properties);
2397 unset($eventcopy->id);
2399 $timestart = new DateTime('@' . $eventcopy->timestart);
2400 $timestart->setTimezone(core_date::get_user_timezone_object());
2402 for($i = 1; $i < $eventcopy->repeats; $i++) {
2404 $timestart->add(new DateInterval('P7D'));
2405 $eventcopy->timestart = $timestart->getTimestamp();
2407 // Get the event id for the log record.
2408 $eventcopyid = $DB->insert_record('event', $eventcopy);
2410 // If the context has been set delete all associated files
2412 $fs = get_file_storage();
2413 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
2414 foreach ($files as $file) {
2415 $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
2419 $repeatedids[] = $eventcopyid;
2421 // Trigger an event.
2422 $eventargs['objectid'] = $eventcopyid;
2423 $eventargs['other']['timestart'] = $eventcopy->timestart;
2424 $event = \core\event\calendar_event_created::create($eventargs);
2429 // Hook for tracking added events
2430 self::calendar_event_hook('add_event', array($this->properties, $repeatedids));
2434 if ($checkcapability) {
2435 if(!calendar_edit_event_allowed($this->properties)) {
2436 print_error('nopermissiontoupdatecalendar');
2441 if ($this->editorcontext !== null) {
2442 $this->properties->description = file_save_draft_area_files(
2443 $this->properties->description['itemid'],
2444 $this->editorcontext->id,
2446 'event_description',
2447 $this->properties->id,
2448 $this->editoroptions,
2449 $this->properties->description['text'],
2450 $this->editoroptions['forcehttps']);
2452 $this->properties->format = $this->properties->description['format'];
2453 $this->properties->description = $this->properties->description['text'];
2457 $event = $DB->get_record('event', array('id'=>$this->properties->id));
2459 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
2461 if ($updaterepeated) {
2463 if ($this->properties->timestart != $event->timestart) {
2464 $timestartoffset = $this->properties->timestart - $event->timestart;
2465 $sql = "UPDATE {event}
2468 timestart = timestart + ?,
2471 WHERE repeatid = ?";
2472 $params = array($this->properties->name, $this->properties->description, $timestartoffset, $this->properties->timeduration, time(), $event->repeatid);
2474 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
2475 $params = array($this->properties->name, $this->properties->description, $this->properties->timeduration, time(), $event->repeatid);
2477 $DB->execute($sql, $params);
2479 // Trigger an update event for each of the calendar event.
2480 $events = $DB->get_records('event', array('repeatid' => $event->repeatid), '', 'id,timestart');
2481 foreach ($events as $event) {
2482 $eventargs['objectid'] = $event->id;
2483 $eventargs['other']['timestart'] = $event->timestart;
2484 $event = \core\event\calendar_event_updated::create($eventargs);
2488 $DB->update_record('event', $this->properties);
2489 $event = calendar_event::load($this->properties->id);
2490 $this->properties = $event->properties();
2492 // Trigger an update event.
2493 $event = \core\event\calendar_event_updated::create($eventargs);
2497 // Hook for tracking event updates
2498 self::calendar_event_hook('update_event', array($this->properties, $updaterepeated));
2504 * Deletes an event and if selected an repeated events in the same series
2506 * This function deletes an event, any associated events if $deleterepeated=true,
2507 * and cleans up any files associated with the events.
2509 * @see self::delete()
2511 * @param bool $deleterepeated delete event repeatedly
2512 * @return bool succession of deleting event
2514 public function delete($deleterepeated=false) {
2517 // If $this->properties->id is not set then something is wrong
2518 if (empty($this->properties->id)) {
2519 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
2522 $calevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
2524 $DB->delete_records('event', array('id'=>$this->properties->id));
2526 // Trigger an event for the delete action.
2528 'context' => $this->properties->context,
2529 'objectid' => $this->properties->id,
2531 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
2532 'timestart' => $this->properties->timestart,
2533 'name' => $this->properties->name
2535 $event = \core\event\calendar_event_deleted::create($eventargs);
2536 $event->add_record_snapshot('event', $calevent);
2539 // If we are deleting parent of a repeated event series, promote the next event in the series as parent
2540 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
2541 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC", array($this->properties->id), IGNORE_MULTIPLE);
2542 if (!empty($newparent)) {
2543 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?", array($newparent, $this->properties->id));
2544 // Get all records where the repeatid is the same as the event being removed
2545 $events = $DB->get_records('event', array('repeatid' => $newparent));
2546 // For each of the returned events trigger the event_update hook and an update event.
2547 foreach ($events as $event) {
2548 // Trigger an event for the update.
2549 $eventargs['objectid'] = $event->id;
2550 $eventargs['other']['timestart'] = $event->timestart;
2551 $event = \core\event\calendar_event_updated::create($eventargs);
2554 self::calendar_event_hook('update_event', array($event, false));
2559 // If the editor context hasn't already been set then set it now
2560 if ($this->editorcontext === null) {
2561 $this->editorcontext = $this->properties->context;
2564 // If the context has been set delete all associated files
2565 if ($this->editorcontext !== null) {
2566 $fs = get_file_storage();
2567 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
2568 foreach ($files as $file) {
2573 // Fire the event deleted hook
2574 self::calendar_event_hook('delete_event', array($this->properties->id, $deleterepeated));
2576 // If we need to delete repeated events then we will fetch them all and delete one by one
2577 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2578 // Get all records where the repeatid is the same as the event being removed
2579 $events = $DB->get_records('event', array('repeatid'=>$this->properties->repeatid));
2580 // For each of the returned events populate a calendar_event object and call delete
2581 // make sure the arg passed is false as we are already deleting all repeats
2582 foreach ($events as $event) {
2583 $event = new calendar_event($event);
2584 $event->delete(false);
2592 * Fetch all event properties
2594 * This function returns all of the events properties as an object and optionally
2595 * can prepare an editor for the description field at the same time. This is
2596 * designed to work when the properties are going to be used to set the default
2597 * values of a moodle forms form.
2599 * @param bool $prepareeditor If set to true a editor is prepared for use with
2600 * the mforms editor element. (for description)
2601 * @return stdClass Object containing event properties
2603 public function properties($prepareeditor=false) {
2604 global $USER, $CFG, $DB;
2606 // First take a copy of the properties. We don't want to actually change the
2607 // properties or we'd forever be converting back and forwards between an
2608 // editor formatted description and not
2609 $properties = clone($this->properties);
2610 // Clean the description here
2611 $properties->description = clean_text($properties->description, $properties->format);
2613 // If set to true we need to prepare the properties for use with an editor
2614 // and prepare the file area
2615 if ($prepareeditor) {
2617 // We may or may not have a property id. If we do then we need to work
2618 // out the context so we can copy the existing files to the draft area
2619 if (!empty($properties->id)) {
2621 if ($properties->eventtype === 'site') {
2623 $this->editorcontext = $this->properties->context;
2624 } else if ($properties->eventtype === 'user') {
2626 $this->editorcontext = $this->properties->context;
2627 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
2628 // First check the course is valid
2629 $course = $DB->get_record('course', array('id'=>$properties->courseid));
2631 print_error('invalidcourse');
2634 $this->editorcontext = $this->properties->context;
2635 // We have a course and are within the course context so we had
2636 // better use the courses max bytes value
2637 $this->editoroptions['maxbytes'] = $course->maxbytes;
2639 // If we get here we have a custom event type as used by some
2640 // modules. In this case the event will have been added by
2641 // code and we won't need the editor
2642 $this->editoroptions['maxbytes'] = 0;
2643 $this->editoroptions['maxfiles'] = 0;
2646 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
2649 // Get the context id that is what we really want
2650 $contextid = $this->editorcontext->id;
2654 // If we get here then this is a new event in which case we don't need a
2655 // context as there is no existing files to copy to the draft area.
2659 // If the contextid === false we don't support files so no preparing
2661 if ($contextid !== false) {
2662 // Just encase it has already been submitted
2663 $draftiddescription = file_get_submitted_draft_itemid('description');
2664 // Prepare the draft area, this copies existing files to the draft area as well
2665 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar', 'event_description', $properties->id, $this->editoroptions, $properties->description);
2667 $draftiddescription = 0;
2670 // Structure the description field as the editor requires
2671 $properties->description = array('text'=>$properties->description, 'format'=>$properties->format, 'itemid'=>$draftiddescription);
2674 // Finally return the properties
2679 * Toggles the visibility of an event
2681 * @param null|bool $force If it is left null the events visibility is flipped,
2682 * If it is false the event is made hidden, if it is true it
2684 * @return bool if event is successfully updated, toggle will be visible
2686 public function toggle_visibility($force=null) {
2689 // Set visible to the default if it is not already set
2690 if (empty($this->properties->visible)) {
2691 $this->properties->visible = 1;
2694 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
2695 // Make this event visible
2696 $this->properties->visible = 1;
2698 self::calendar_event_hook('show_event', array($this->properties));
2700 // Make this event hidden
2701 $this->properties->visible = 0;
2703 self::calendar_event_hook('hide_event', array($this->properties));
2706 // Update the database to reflect this change
2707 return $DB->set_field('event', 'visible', $this->properties->visible, array('id'=>$this->properties->id));
2711 * Attempts to call the hook for the specified action should a calendar type
2712 * by set $CFG->calendar, and the appopriate function defined
2714 * @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
2715 * @param array $args The args to pass to the hook, usually the event is the first element
2716 * @return bool attempts to call event hook
2718 public static function calendar_event_hook($action, array $args) {
2720 static $extcalendarinc;
2721 if ($extcalendarinc === null) {
2722 if (!empty($CFG->calendar)) {
2723 if (is_readable($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
2724 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
2725 $extcalendarinc = true;
2727 debugging("Calendar lib file missing or not readable at /calendar/{$CFG->calendar}/lib.php.",
2729 $extcalendarinc = false;
2732 $extcalendarinc = false;
2735 if($extcalendarinc === false) {
2738 $hook = $CFG->calendar .'_'.$action;
2739 if (function_exists($hook)) {
2740 call_user_func_array($hook, $args);
2747 * Returns a calendar_event object when provided with an event id
2749 * This function makes use of MUST_EXIST, if the event id passed in is invalid
2750 * it will result in an exception being thrown
2752 * @param int|object $param event object or event id
2753 * @return calendar_event|false status for loading calendar_event
2755 public static function load($param) {
2757 if (is_object($param)) {
2758 $event = new calendar_event($param);
2760 $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST);
2761 $event = new calendar_event($event);
2767 * Creates a new event and returns a calendar_event object
2769 * @param stdClass|array $properties An object containing event properties
2770 * @param bool $checkcapability Check caps or not
2771 * @throws coding_exception
2773 * @return calendar_event|bool The event object or false if it failed
2775 public static function create($properties, $checkcapability = true) {
2776 if (is_array($properties)) {
2777 $properties = (object)$properties;
2779 if (!is_object($properties)) {
2780 throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2782 $event = new calendar_event($properties);
2783 if ($event->update($properties, $checkcapability)) {
2791 * Format the text using the external API.
2792 * This function should we used when text formatting is required in external functions.
2794 * @return array an array containing the text formatted and the text format
2796 public function format_external_text() {
2798 if ($this->editorcontext === null) {
2799 // Switch on the event type to decide upon the appropriate context to use for this event.
2800 $this->editorcontext = $this->properties->context;
2802 if ($this->properties->eventtype != 'user' && $this->properties->eventtype != 'course'
2803 && $this->properties->eventtype != 'site' && $this->properties->eventtype != 'group') {
2804 // We don't have a context here, do a normal format_text.
2805 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id);
2809 // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
2810 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2811 $itemid = $this->properties->repeatid;
2813 $itemid = $this->properties->id;
2816 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id,
2817 'calendar', 'event_description', $itemid);
2822 * Calendar information class
2824 * This class is used simply to organise the information pertaining to a calendar
2825 * and is used primarily to make information easily available.
2827 * @package core_calendar
2828 * @category calendar
2829 * @copyright 2010 Sam Hemelryk
2830 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2832 class calendar_information {
2835 * @var int The timestamp
2837 * Rather than setting the day, month and year we will set a timestamp which will be able
2838 * to be used by multiple calendars.
2842 /** @var int A course id */
2843 public $courseid = null;
2845 /** @var array An array of courses */
2846 public $courses = array();
2848 /** @var array An array of groups */
2849 public $groups = array();
2851 /** @var array An array of users */
2852 public $users = array();
2855 * Creates a new instance
2857 * @param int $day the number of the day
2858 * @param int $month the number of the month
2859 * @param int $year the number of the year
2860 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
2861 * and $calyear to support multiple calendars
2863 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
2864 // If a day, month and year were passed then convert it to a timestamp. If these were passed
2865 // then we can assume the day, month and year are passed as Gregorian, as no where in core
2866 // should we be passing these values rather than the time. This is done for BC.
2867 if (!empty($day) || !empty($month) || !empty($year)) {
2868 $date = usergetdate(time());
2870 $day = $date['mday'];
2872 if (empty($month)) {
2873 $month = $date['mon'];
2876 $year = $date['year'];
2878 if (checkdate($month, $day, $year)) {
2879 $this->time = make_timestamp($year, $month, $day);
2881 $this->time = time();
2883 } else if (!empty($time)) {
2884 $this->time = $time;
2886 $this->time = time();
2891 * Initialize calendar information
2893 * @param stdClass $course object
2894 * @param array $coursestoload An array of courses [$course->id => $course]
2895 * @param bool $ignorefilters options to use filter
2897 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
2898 $this->courseid = $course->id;
2899 $this->course = $course;
2900 list($courses, $group, $user) = calendar_set_filters($coursestoload, $ignorefilters);
2901 $this->courses = $courses;
2902 $this->groups = $group;
2903 $this->users = $user;
2907 * Ensures the date for the calendar is correct and either sets it to now
2908 * or throws a moodle_exception if not
2910 * @param bool $defaultonow use current time
2911 * @throws moodle_exception
2912 * @return bool validation of checkdate
2914 public function checkdate($defaultonow = true) {
2915 if (!checkdate($this->month, $this->day, $this->year)) {
2917 $now = usergetdate(time());
2918 $this->day = intval($now['mday']);
2919 $this->month = intval($now['mon']);
2920 $this->year = intval($now['year']);
2923 throw new moodle_exception('invaliddate');
2930 * Gets todays timestamp for the calendar
2932 * @return int today timestamp
2934 public function timestamp_today() {
2938 * Gets tomorrows timestamp for the calendar
2940 * @return int tomorrow timestamp
2942 public function timestamp_tomorrow() {
2943 return strtotime('+1 day', $this->time);
2946 * Adds the pretend blocks for the calendar
2948 * @param core_calendar_renderer $renderer
2949 * @param bool $showfilters display filters, false is set as default
2950 * @param string|null $view preference view options (eg: day, month, upcoming)
2952 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
2954 $filters = new block_contents();
2955 $filters->content = $renderer->fake_block_filters($this->courseid, 0, 0, 0, $view, $this->courses);
2956 $filters->footer = '';
2957 $filters->title = get_string('eventskey', 'calendar');
2958 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
2960 $block = new block_contents;
2961 $block->content = $renderer->fake_block_threemonths($this);
2962 $block->footer = '';
2963 $block->title = get_string('monthlyview', 'calendar');
2964 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
2969 * Returns option list for the poll interval setting.
2971 * @return array An array of poll interval options. Interval => description.
2973 function calendar_get_pollinterval_choices() {
2975 '0' => new lang_string('never', 'calendar'),
2976 HOURSECS => new lang_string('hourly', 'calendar'),
2977 DAYSECS => new lang_string('daily', 'calendar'),
2978 WEEKSECS => new lang_string('weekly', 'calendar'),
2979 '2628000' => new lang_string('monthly', 'calendar'),
2980 YEARSECS => new lang_string('annually', 'calendar')
2985 * Returns option list of available options for the calendar event type, given the current user and course.
2987 * @param int $courseid The id of the course
2988 * @return array An array containing the event types the user can create.
2990 function calendar_get_eventtype_choices($courseid) {
2992 $allowed = new stdClass;
2993 calendar_get_allowed_types($allowed, $courseid);
2995 if ($allowed->user) {
2996 $choices['user'] = get_string('userevents', 'calendar');
2998 if ($allowed->site) {
2999 $choices['site'] = get_string('siteevents', 'calendar');
3001 if (!empty($allowed->courses)) {
3002 $choices['course'] = get_string('courseevents', 'calendar');
3004 if (!empty($allowed->groups) and is_array($allowed->groups)) {
3005 $choices['group'] = get_string('group');
3008 return array($choices, $allowed->groups);
3012 * Add an iCalendar subscription to the database.
3014 * @param stdClass $sub The subscription object (e.g. from the form)
3015 * @return int The insert ID, if any.
3017 function calendar_add_subscription($sub) {
3018 global $DB, $USER, $SITE;
3020 if ($sub->eventtype === 'site') {
3021 $sub->courseid = $SITE->id;
3022 } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
3023 $sub->courseid = $sub->course;
3028 $sub->userid = $USER->id;
3030 // File subscriptions never update.
3031 if (empty($sub->url)) {
3032 $sub->pollinterval = 0;
3035 if (!empty($sub->name)) {
3036 if (empty($sub->id)) {
3037 $id = $DB->insert_record('event_subscriptions', $sub);
3038 // we cannot cache the data here because $sub is not complete.
3040 // Trigger event, calendar subscription added.
3041 $eventparams = array('objectid' => $sub->id,
3042 'context' => calendar_get_calendar_context($sub),
3043 'other' => array('eventtype' => $sub->eventtype, 'courseid' => $sub->courseid)
3045 $event = \core\event\calendar_subscription_created::create($eventparams);
3049 // Why are we doing an update here?
3050 calendar_update_subscription($sub);
3054 print_error('errorbadsubscription', 'importcalendar');
3059 * Add an iCalendar event to the Moodle calendar.
3061 * @param stdClass $event The RFC-2445 iCalendar event
3062 * @param int $courseid The course ID
3063 * @param int $subscriptionid The iCalendar subscription ID
3064 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
3065 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
3066 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
3068 function calendar_add_icalendar_event($event, $courseid, $subscriptionid, $timezone='UTC') {
3071 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
3072 if (empty($event->properties['SUMMARY'])) {
3076 $name = $event->properties['SUMMARY'][0]->value;
3077 $name = str_replace('\n', '<br />', $name);
3078 $name = str_replace('\\', '', $name);
3079 $name = preg_replace('/\s+/u', ' ', $name);
3081 $eventrecord = new stdClass;
3082 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
3084 if (empty($event->properties['DESCRIPTION'][0]->value)) {
3087 $description = $event->properties['DESCRIPTION'][0]->value;
3088 $description = clean_param($description, PARAM_NOTAGS);
3089 $description = str_replace('\n', '<br />', $description);
3090 $description = str_replace('\\', '', $description);
3091 $description = preg_replace('/\s+/u', ' ', $description);
3093 $eventrecord->description = $description;
3095 // Probably a repeating event with RRULE etc. TODO: skip for now.
3096 if (empty($event->properties['DTSTART'][0]->value)) {
3100 $tz = isset($event->properties['DTSTART'][0]->parameters['TZID']) ? $event->properties['DTSTART'][0]->parameters['TZID'] :
3102 $tz = core_date::normalise_timezone($tz);
3103 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value . ' ' . $tz);
3104 if (empty($event->properties['DTEND'])) {
3105 $eventrecord->timeduration = 0; // no duration if no end time specified
3107 $endtz = isset($event->properties['DTEND'][0]->parameters['TZID']) ? $event->properties['DTEND'][0]->parameters['TZID'] :
3109 $endtz = core_date::normalise_timezone($endtz);
3110 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value . ' ' . $endtz) - $eventrecord->timestart;
3113 // Check to see if it should be treated as an all day event.
3114 if ($eventrecord->timeduration == DAYSECS) {
3115 // Check to see if the event started at Midnight on the imported calendar.
3116 date_default_timezone_set($timezone);
3117 if (date('H:i:s', $eventrecord->timestart) === "00:00:00") {
3118 // This event should be an all day event.
3119 $eventrecord->timeduration = 0;
3121 core_date::set_default_server_timezone();
3124 $eventrecord->uuid = $event->properties['UID'][0]->value;
3125 $eventrecord->timemodified = time();
3127 // Add the iCal subscription details if required.
3128 // We should never do anything with an event without a subscription reference.
3129 $sub = calendar_get_subscription($subscriptionid);
3130 $eventrecord->subscriptionid = $subscriptionid;
3131 $eventrecord->userid = $sub->userid;
3132 $eventrecord->groupid = $sub->groupid;
3133 $eventrecord->courseid = $sub->courseid;
3134 $eventrecord->eventtype = $sub->eventtype;
3136 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid, 'subscriptionid' => $eventrecord->subscriptionid))) {
3137 $eventrecord->id = $updaterecord->id;
3138 $return = CALENDAR_IMPORT_EVENT_UPDATED; // Update.
3140 $return = CALENDAR_IMPORT_EVENT_INSERTED; // Insert.
3142 if ($createdevent = calendar_event::create($eventrecord, false)) {
3143 if (!empty($event->properties['RRULE'])) {
3144 // Repeating events.
3145 date_default_timezone_set($tz); // Change time zone to parse all events.
3146 $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
3147 $rrule->parse_rrule();
3148 $rrule->create_events($createdevent);
3149 core_date::set_default_server_timezone(); // Change time zone back to what it was.
3158 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
3160 * @param int $subscriptionid The ID of the subscription we are acting upon.
3161 * @param int $pollinterval The poll interval to use.
3162 * @param int $action The action to be performed. One of update or remove.
3163 * @throws dml_exception if invalid subscriptionid is provided
3164 * @return string A log of the import progress, including errors
3166 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
3168 // Fetch the subscription from the database making sure it exists.
3169 $sub = calendar_get_subscription($subscriptionid);
3171 // Update or remove the subscription, based on action.
3173 case CALENDAR_SUBSCRIPTION_UPDATE:
3174 // Skip updating file subscriptions.
3175 if (empty($sub->url)) {
3178 $sub->pollinterval = $pollinterval;
3179 calendar_update_subscription($sub);
3181 // Update the events.
3182 return "<p>".get_string('subscriptionupdated', 'calendar', $sub->name)."</p>" . calendar_update_subscription_events($subscriptionid);
3184 case CALENDAR_SUBSCRIPTION_REMOVE:
3185 calendar_delete_subscription($subscriptionid);
3186 return get_string('subscriptionremoved', 'calendar', $sub->name);
3196 * Delete subscription and all related events.
3198 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
3200 function calendar_delete_subscription($subscription) {
3203 if (!is_object($subscription)) {
3204 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST);
3206 // Delete subscription and related events.
3207 $DB->delete_records('event', array('subscriptionid' => $subscription->id));
3208 $DB->delete_records('event_subscriptions', array('id' => $subscription->id));
3209 cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id));
3211 // Trigger event, calendar subscription deleted.
3212 $eventparams = array('objectid' => $subscription->id,
3213 'context' => calendar_get_calendar_context($subscription),
3214 'other' => array('courseid' => $subscription->courseid)
3216 $event = \core\event\calendar_subscription_deleted::create($eventparams);
3220 * From a URL, fetch the calendar and return an iCalendar object.
3222 * @param string $url The iCalendar URL
3223 * @return stdClass The iCalendar object
3225 function calendar_get_icalendar($url) {
3228 require_once($CFG->libdir.'/filelib.php');
3231 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
3232 $calendar = $curl->get($url);
3233 // Http code validation should actually be the job of curl class.
3234 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
3235 throw new moodle_exception('errorinvalidicalurl', 'calendar');
3238 $ical = new iCalendar();
3239 $ical->unserialize($calendar);
3244 * Import events from an iCalendar object into a course calendar.
3246 * @param stdClass $ical The iCalendar object.
3247 * @param int $courseid The course ID for the calendar.
3248 * @param int $subscriptionid The subscription ID.
3249 * @return string A log of the import progress, including errors.
3251 function calendar_import_icalendar_events($ical, $courseid, $subscriptionid = null) {
3257 // Large calendars take a while...
3259 core_php_time_limit::raise(300);
3262 // Mark all events in a subscription with a zero timestamp.
3263 if (!empty($subscriptionid)) {
3264 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
3265 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3267 // Grab the timezone from the iCalendar file to be used later.
3268 if (isset($ical->properties['X-WR-TIMEZONE'][0]->value)) {
3269 $timezone = $ical->properties['X-WR-TIMEZONE'][0]->value;
3273 foreach ($ical->components['VEVENT'] as $event) {
3274 $res = calendar_add_icalendar_event($event, $courseid, $subscriptionid, $timezone);
3276 case CALENDAR_IMPORT_EVENT_UPDATED:
3279 case CALENDAR_IMPORT_EVENT_INSERTED:
3283 $return .= '<p>'.get_string('erroraddingevent', 'calendar').': '.(empty($event->properties['SUMMARY'])?'('.get_string('notitle', 'calendar').')':$event->properties['SUMMARY'][0]->value)." </p>\n";
3287 $return .= "<p> ".get_string('eventsimported', 'calendar', $eventcount)."</p>";
3288 $return .= "<p> ".get_string('eventsupdated', 'calendar', $updatecount)."</p>";
3290 // Delete remaining zero-marked events since they're not in remote calendar.
3291 if (!empty($subscriptionid)) {
3292 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3293 if (!empty($deletecount)) {
3294 $sql = "DELETE FROM {event} WHERE timemodified = :time AND subscriptionid = :id";
3295 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3296 $return .= "<p> ".get_string('eventsdeleted', 'calendar').": {$deletecount} </p>\n";
3304 * Fetch a calendar subscription and update the events in the calendar.
3306 * @param int $subscriptionid The course ID for the calendar.
3307 * @return string A log of the import progress, including errors.
3309 function calendar_update_subscription_events($subscriptionid) {
3312 $sub = calendar_get_subscription($subscriptionid);
3313 // Don't update a file subscription. TODO: Update from a new uploaded file.
3314 if (empty($sub->url)) {
3315 return 'File subscription not updated.';
3317 $ical = calendar_get_icalendar($sub->url);
3318 $return = calendar_import_icalendar_events($ical, $sub->courseid, $subscriptionid);
3319 $sub->lastupdated = time();
3320 calendar_update_subscription($sub);
3325 * Update a calendar subscription. Also updates the associated cache.
3327 * @param stdClass|array $subscription Subscription record.
3328 * @throws coding_exception If something goes wrong
3331 function calendar_update_subscription($subscription) {
3334 if (is_array($subscription)) {
3335 $subscription = (object)$subscription;
3337 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
3338 throw new coding_exception('Cannot update a subscription without a valid id');
3341 $DB->update_record('event_subscriptions', $subscription);
3343 $cache = cache::make('core', 'calendar_subscriptions');
3344 $cache->set($subscription->id, $subscription);
3345 // Trigger event, calendar subscription updated.
3346 $eventparams = array('userid' => $subscription->userid,
3347 'objectid' => $subscription->id,
3348 'context' => calendar_get_calendar_context($subscription),
3349 'other' => array('eventtype' => $subscription->eventtype, 'courseid' => $subscription->courseid)
3351 $event = \core\event\calendar_subscription_updated::create($eventparams);
3356 * Checks to see if the user can edit a given subscription feed.
3358 * @param mixed $subscriptionorid Subscription object or id
3359 * @return bool true if current user can edit the subscription else false
3361 function calendar_can_edit_subscription($subscriptionorid) {
3364 if (is_array($subscriptionorid)) {
3365 $subscription = (object)$subscriptionorid;
3366 } else if (is_object($subscriptionorid)) {
3367 $subscription = $subscriptionorid;
3369 $subscription = calendar_get_subscription($subscriptionorid);
3371 $allowed = new stdClass;
3372 $courseid = $subscription->courseid;
3373 $groupid = $subscription->groupid;
3374 calendar_get_allowed_types($allowed, $courseid);
3375 switch ($subscription->eventtype) {
3377 return $allowed->user;
3379 if (isset($allowed->courses[$courseid])) {
3380 return $allowed->courses[$courseid];
3385 return $allowed->site;
3387 if (isset($allowed->groups[$groupid])) {
3388 return $allowed->groups[$groupid];
3398 * Update calendar subscriptions.
3402 function calendar_cron() {
3405 // In order to execute this we need bennu.
3406 require_once($CFG->libdir.'/bennu/bennu.inc.php');
3408 mtrace('Updating calendar subscriptions:');
3409 cron_trace_time_and_memory();
3412 $subscriptions = $DB->get_records_sql('SELECT * FROM {event_subscriptions} WHERE pollinterval > 0 AND lastupdated + pollinterval < ?', array($time));
3413 foreach ($subscriptions as $sub) {
3414 mtrace("Updating calendar subscription {$sub->name} in course {$sub->courseid}");
3416 $log = calendar_update_subscription_events($sub->id);
3417 mtrace(trim(strip_tags($log)));
3418 } catch (moodle_exception $ex) {
3419 mtrace('Error updating calendar subscription: ' . $ex->getMessage());
3423 mtrace('Finished updating calendar subscriptions.');
3429 * Helper function to determine the context of a calendar subscription.
3430 * Subscriptions can be created in two contexts COURSE, or USER.
3432 * @param stdClass $subscription
3433 * @return context instance
3435 function calendar_get_calendar_context($subscription) {
3437 // Determine context based on calendar type.
3438 if ($subscription->eventtype === 'site') {
3439 $context = context_course::instance(SITEID);
3440 } else if ($subscription->eventtype === 'group' || $subscription->eventtype === 'course') {
3441 $context = context_course::instance($subscription->courseid);
3443 $context = context_user::instance($subscription->userid);