Merge branch 'MDL-45296' of git://github.com/stronk7/moodle
[moodle.git] / calendar / lib.php
blobed35b6bd84516f340acf5af36bf20dcb82b02a85
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
17 /**
18 * Calendar extension
20 * @package core_calendar
21 * @copyright 2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
22 * Avgoustos Tsinakos
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
30 /**
31 * These are read by the administration component to provide default values
34 /**
35 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
37 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
39 /**
40 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
42 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
44 /**
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
52 /**
53 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
55 define('CALENDAR_DEFAULT_WEEKEND', 65);
57 /**
58 * CALENDAR_URL - path to calendar's folder
60 define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
62 /**
63 * CALENDAR_TF_24 - Calendar time in 24 hours format
65 define('CALENDAR_TF_24', '%H:%M');
67 /**
68 * CALENDAR_TF_12 - Calendar time in 12 hours format
70 define('CALENDAR_TF_12', '%I:%M %p');
72 /**
73 * CALENDAR_EVENT_GLOBAL - Global calendar event types
75 define('CALENDAR_EVENT_GLOBAL', 1);
77 /**
78 * CALENDAR_EVENT_COURSE - Course calendar event types
80 define('CALENDAR_EVENT_COURSE', 2);
82 /**
83 * CALENDAR_EVENT_GROUP - group calendar event types
85 define('CALENDAR_EVENT_GROUP', 4);
87 /**
88 * CALENDAR_EVENT_USER - user calendar event types
90 define('CALENDAR_EVENT_USER', 8);
93 /**
94 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
96 define('CALENDAR_IMPORT_FROM_FILE', 0);
98 /**
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 * Return the days of the week
126 * @return array array of days
128 function calendar_get_days() {
129 $calendartype = \core_calendar\type_factory::get_calendar_instance();
130 return $calendartype->get_weekdays();
134 * Get the subscription from a given id
136 * @since Moodle 2.5
137 * @param int $id id of the subscription
138 * @return stdClass Subscription record from DB
139 * @throws moodle_exception for an invalid id
141 function calendar_get_subscription($id) {
142 global $DB;
144 $cache = cache::make('core', 'calendar_subscriptions');
145 $subscription = $cache->get($id);
146 if (empty($subscription)) {
147 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
148 // cache the data.
149 $cache->set($id, $subscription);
151 return $subscription;
155 * Gets the first day of the week
157 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
159 * @return int
161 function calendar_get_starting_weekday() {
162 $calendartype = \core_calendar\type_factory::get_calendar_instance();
163 return $calendartype->get_starting_weekday();
167 * Generates the HTML for a miniature calendar
169 * @param array $courses list of course to list events from
170 * @param array $groups list of group
171 * @param array $users user's info
172 * @param int|bool $calmonth calendar month in numeric, default is set to false
173 * @param int|bool $calyear calendar month in numeric, default is set to false
174 * @param string|bool $placement the place/page the calendar is set to appear - passed on the the controls function
175 * @param int|bool $courseid id of the course the calendar is displayed on - passed on the the controls function
176 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
177 * and $calyear to support multiple calendars
178 * @return string $content return html table for mini calendar
180 function calendar_get_mini($courses, $groups, $users, $calmonth = false, $calyear = false, $placement = false,
181 $courseid = false, $time = 0) {
182 global $CFG, $OUTPUT;
184 // Get the calendar type we are using.
185 $calendartype = \core_calendar\type_factory::get_calendar_instance();
187 $display = new stdClass;
189 // Assume we are not displaying this month for now.
190 $display->thismonth = false;
192 $content = '';
194 // Do this check for backwards compatibility. The core should be passing a timestamp rather than month and year.
195 // If a month and year are passed they will be in Gregorian.
196 if (!empty($calmonth) && !empty($calyear)) {
197 // Ensure it is a valid date, else we will just set it to the current timestamp.
198 if (checkdate($calmonth, 1, $calyear)) {
199 $time = make_timestamp($calyear, $calmonth, 1);
200 } else {
201 $time = time();
203 $date = usergetdate($time);
204 if ($calmonth == $date['mon'] && $calyear == $date['year']) {
205 $display->thismonth = true;
207 // We can overwrite date now with the date used by the calendar type, if it is not Gregorian, otherwise
208 // there is no need as it is already in Gregorian.
209 if ($calendartype->get_name() != 'gregorian') {
210 $date = $calendartype->timestamp_to_date_array($time);
212 } else if (!empty($time)) {
213 // Get the specified date in the calendar type being used.
214 $date = $calendartype->timestamp_to_date_array($time);
215 $thisdate = $calendartype->timestamp_to_date_array(time());
216 if ($date['month'] == $thisdate['month'] && $date['year'] == $thisdate['year']) {
217 $display->thismonth = true;
218 // If we are the current month we want to set the date to the current date, not the start of the month.
219 $date = $thisdate;
221 } else {
222 // Get the current date in the calendar type being used.
223 $time = time();
224 $date = $calendartype->timestamp_to_date_array($time);
225 $display->thismonth = true;
228 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display.
230 // Get Gregorian date for the start of the month.
231 $gregoriandate = $calendartype->convert_to_gregorian($date['year'], $date['mon'], 1);
233 // Store the gregorian date values to be used later.
234 list($gy, $gm, $gd, $gh, $gmin) = array($gregoriandate['year'], $gregoriandate['month'], $gregoriandate['day'],
235 $gregoriandate['hour'], $gregoriandate['minute']);
237 // Get the max number of days in this month for this calendar type.
238 $display->maxdays = calendar_days_in_month($m, $y);
239 // Get the starting week day for this month.
240 $startwday = dayofweek(1, $m, $y);
241 // Get the days in a week.
242 $daynames = calendar_get_days();
243 // Store the number of days in a week.
244 $numberofdaysinweek = $calendartype->get_num_weekdays();
246 // Set the min and max weekday.
247 $display->minwday = calendar_get_starting_weekday();
248 $display->maxwday = $display->minwday + ($numberofdaysinweek - 1);
250 // These are used for DB queries, so we want unixtime, so we need to use Gregorian dates.
251 $display->tstart = make_timestamp($gy, $gm, $gd, $gh, $gmin, 0);
252 $display->tend = $display->tstart + ($display->maxdays * DAYSECS) - 1;
254 // Align the starting weekday to fall in our display range
255 // This is simple, not foolproof.
256 if ($startwday < $display->minwday) {
257 $startwday += $numberofdaysinweek;
260 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
261 $events = calendar_get_events($display->tstart, $display->tend, $users, $groups, $courses);
263 // Set event course class for course events
264 if (!empty($events)) {
265 foreach ($events as $eventid => $event) {
266 if (!empty($event->modulename)) {
267 $cm = get_coursemodule_from_instance($event->modulename, $event->instance);
268 if (!\core_availability\info_module::is_user_visible($cm, 0, false)) {
269 unset($events[$eventid]);
275 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
276 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
277 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
278 // arguments to this function.
279 $hrefparams = array();
280 if(!empty($courses)) {
281 $courses = array_diff($courses, array(SITEID));
282 if(count($courses) == 1) {
283 $hrefparams['course'] = reset($courses);
287 // We want to have easy access by day, since the display is on a per-day basis.
288 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
290 // Accessibility: added summary and <abbr> elements.
291 $summary = get_string('calendarheading', 'calendar', userdate($display->tstart, get_string('strftimemonthyear')));
292 $content .= '<table class="minicalendar calendartable" summary="'.$summary.'">'; // Begin table.
293 if (($placement !== false) && ($courseid !== false)) {
294 $content .= '<caption>'. calendar_top_controls($placement, array('id' => $courseid, 'time' => $time)) .'</caption>';
296 $content .= '<tr class="weekdays">'; // Header row: day names
298 // Print out the names of the weekdays.
299 for ($i = $display->minwday; $i <= $display->maxwday; ++$i) {
300 $pos = $i % $numberofdaysinweek;
301 $content .= '<th scope="col"><abbr title="'. $daynames[$pos]['fullname'] .'">'.
302 $daynames[$pos]['shortname'] ."</abbr></th>\n";
305 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
307 // For the table display. $week is the row; $dayweek is the column.
308 $dayweek = $startwday;
310 // Paddding (the first week may have blank days in the beginning)
311 for($i = $display->minwday; $i < $startwday; ++$i) {
312 $content .= '<td class="dayblank">&nbsp;</td>'."\n";
315 $weekend = CALENDAR_DEFAULT_WEEKEND;
316 if (isset($CFG->calendar_weekend)) {
317 $weekend = intval($CFG->calendar_weekend);
320 // Now display all the calendar
321 $daytime = $display->tstart - DAYSECS;
322 for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
323 $daytime += DAYSECS;
324 if($dayweek > $display->maxwday) {
325 // We need to change week (table row)
326 $content .= '</tr><tr>';
327 $dayweek = $display->minwday;
330 // Reset vars.
331 if ($weekend & (1 << ($dayweek % $numberofdaysinweek))) {
332 // Weekend. This is true no matter what the exact range is.
333 $class = 'weekend day';
334 } else {
335 // Normal working day.
336 $class = 'day';
339 // Special visual fx if an event is defined
340 if(isset($eventsbyday[$day])) {
342 $class .= ' hasevent';
343 $hrefparams['view'] = 'day';
344 $dayhref = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $hrefparams), 0, 0, 0, $daytime);
346 $popupcontent = '';
347 foreach($eventsbyday[$day] as $eventid) {
348 if (!isset($events[$eventid])) {
349 continue;
351 $event = new calendar_event($events[$eventid]);
352 $popupalt = '';
353 $component = 'moodle';
354 if (!empty($event->modulename)) {
355 $popupicon = 'icon';
356 $popupalt = $event->modulename;
357 $component = $event->modulename;
358 } else if ($event->courseid == SITEID) { // Site event.
359 $popupicon = 'i/siteevent';
360 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event.
361 $popupicon = 'i/courseevent';
362 } else if ($event->groupid) { // Group event.
363 $popupicon = 'i/groupevent';
364 } else { // Must be a user event.
365 $popupicon = 'i/userevent';
368 $dayhref->set_anchor('event_'.$event->id);
370 $popupcontent .= html_writer::start_tag('div');
371 $popupcontent .= $OUTPUT->pix_icon($popupicon, $popupalt, $component);
372 $name = format_string($event->name, true);
373 // Show ical source if needed.
374 if (!empty($event->subscription) && $CFG->calendar_showicalsource) {
375 $a = new stdClass();
376 $a->name = $name;
377 $a->source = $event->subscription->name;
378 $name = get_string('namewithsource', 'calendar', $a);
380 $popupcontent .= html_writer::link($dayhref, $name);
381 $popupcontent .= html_writer::end_tag('div');
384 //Accessibility: functionality moved to calendar_get_popup.
385 if($display->thismonth && $day == $d) {
386 $popupid = calendar_get_popup(true, $events[$eventid]->timestart, $popupcontent);
387 } else {
388 $popupid = calendar_get_popup(false, $events[$eventid]->timestart, $popupcontent);
391 // Class and cell content
392 if(isset($typesbyday[$day]['startglobal'])) {
393 $class .= ' calendar_event_global';
394 } else if(isset($typesbyday[$day]['startcourse'])) {
395 $class .= ' calendar_event_course';
396 } else if(isset($typesbyday[$day]['startgroup'])) {
397 $class .= ' calendar_event_group';
398 } else if(isset($typesbyday[$day]['startuser'])) {
399 $class .= ' calendar_event_user';
401 $cell = html_writer::link($dayhref, $day, array('id' => $popupid));
402 } else {
403 $cell = $day;
406 $durationclass = false;
407 if (isset($typesbyday[$day]['durationglobal'])) {
408 $durationclass = ' duration_global';
409 } else if(isset($typesbyday[$day]['durationcourse'])) {
410 $durationclass = ' duration_course';
411 } else if(isset($typesbyday[$day]['durationgroup'])) {
412 $durationclass = ' duration_group';
413 } else if(isset($typesbyday[$day]['durationuser'])) {
414 $durationclass = ' duration_user';
416 if ($durationclass) {
417 $class .= ' duration '.$durationclass;
420 // If event has a class set then add it to the table day <td> tag
421 // Note: only one colour for minicalendar
422 if(isset($eventsbyday[$day])) {
423 foreach($eventsbyday[$day] as $eventid) {
424 if (!isset($events[$eventid])) {
425 continue;
427 $event = $events[$eventid];
428 if (!empty($event->class)) {
429 $class .= ' '.$event->class;
431 break;
435 // Special visual fx for today
436 //Accessibility: hidden text for today, and popup.
437 if($display->thismonth && $day == $d) {
438 $class .= ' today';
439 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
441 if(! isset($eventsbyday[$day])) {
442 $class .= ' eventnone';
443 $popupid = calendar_get_popup(true, false);
444 $cell = html_writer::link('#', $day, array('id' => $popupid));
446 $cell = get_accesshide($today.' ').$cell;
449 // Just display it
450 if(!empty($class)) {
451 $class = ' class="'.$class.'"';
453 $content .= '<td'.$class.'>'.$cell."</td>\n";
456 // Paddding (the last week may have blank days at the end)
457 for($i = $dayweek; $i <= $display->maxwday; ++$i) {
458 $content .= '<td class="dayblank">&nbsp;</td>';
460 $content .= '</tr>'; // Last row ends
462 $content .= '</table>'; // Tabular display of days ends
464 return $content;
468 * Gets the calendar popup
470 * It called at multiple points in from calendar_get_mini.
471 * Copied and modified from calendar_get_mini.
473 * @param bool $is_today false except when called on the current day.
474 * @param mixed $event_timestart $events[$eventid]->timestart, OR false if there are no events.
475 * @param string $popupcontent content for the popup window/layout.
476 * @return string eventid for the calendar_tooltip popup window/layout.
478 function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
479 global $PAGE;
480 static $popupcount;
481 if ($popupcount === null) {
482 $popupcount = 1;
484 $popupcaption = '';
485 if($is_today) {
486 $popupcaption = get_string('today', 'calendar').' ';
488 if (false === $event_timestart) {
489 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
490 $popupcontent = get_string('eventnone', 'calendar');
492 } else {
493 $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
495 $id = 'calendar_tooltip_'.$popupcount;
496 $PAGE->requires->yui_module('moodle-calendar-eventmanager', 'M.core_calendar.add_event', array(array('eventId'=>$id,'title'=>$popupcaption, 'content'=>$popupcontent)));
498 $popupcount++;
499 return $id;
503 * Gets the calendar upcoming event
505 * @param array $courses array of courses
506 * @param array|int|bool $groups array of groups, group id or boolean for all/no group events
507 * @param array|int|bool $users array of users, user id or boolean for all/no user events
508 * @param int $daysinfuture number of days in the future we 'll look
509 * @param int $maxevents maximum number of events
510 * @param int $fromtime start time
511 * @return array $output array of upcoming events
513 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
514 global $CFG, $COURSE, $DB;
516 $display = new stdClass;
517 $display->range = $daysinfuture; // How many days in the future we 'll look
518 $display->maxevents = $maxevents;
520 $output = array();
522 // Prepare "course caching", since it may save us a lot of queries
523 $coursecache = array();
525 $processed = 0;
526 $now = time(); // We 'll need this later
527 $usermidnighttoday = usergetmidnight($now);
529 if ($fromtime) {
530 $display->tstart = $fromtime;
531 } else {
532 $display->tstart = $usermidnighttoday;
535 // This works correctly with respect to the user's DST, but it is accurate
536 // only because $fromtime is always the exact midnight of some day!
537 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
539 // Get the events matching our criteria
540 $events = calendar_get_events($display->tstart, $display->tend, $users, $groups, $courses);
542 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
543 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
544 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
545 // arguments to this function.
547 $hrefparams = array();
548 if(!empty($courses)) {
549 $courses = array_diff($courses, array(SITEID));
550 if(count($courses) == 1) {
551 $hrefparams['course'] = reset($courses);
555 if ($events !== false) {
557 $modinfo = get_fast_modinfo($COURSE);
559 foreach($events as $event) {
562 if (!empty($event->modulename)) {
563 if ($event->courseid == $COURSE->id) {
564 if (isset($modinfo->instances[$event->modulename][$event->instance])) {
565 $cm = $modinfo->instances[$event->modulename][$event->instance];
566 if (!$cm->uservisible) {
567 continue;
570 } else {
571 if (!$cm = get_coursemodule_from_instance($event->modulename, $event->instance)) {
572 continue;
574 if (!\core_availability\info_module::is_user_visible($cm, 0, false)) {
575 continue;
580 if ($processed >= $display->maxevents) {
581 break;
584 $event->time = calendar_format_event_time($event, $now, $hrefparams);
585 $output[] = $event;
586 ++$processed;
589 return $output;
594 * Get a HTML link to a course.
596 * @param int $courseid the course id
597 * @return string a link to the course (as HTML); empty if the course id is invalid
599 function calendar_get_courselink($courseid) {
601 if (!$courseid) {
602 return '';
605 calendar_get_course_cached($coursecache, $courseid);
606 $context = context_course::instance($courseid);
607 $fullname = format_string($coursecache[$courseid]->fullname, true, array('context' => $context));
608 $url = new moodle_url('/course/view.php', array('id' => $courseid));
609 $link = html_writer::link($url, $fullname);
611 return $link;
616 * Add calendar event metadata
618 * @param stdClass $event event info
619 * @return stdClass $event metadata
621 function calendar_add_event_metadata($event) {
622 global $CFG, $OUTPUT;
624 //Support multilang in event->name
625 $event->name = format_string($event->name,true);
627 if(!empty($event->modulename)) { // Activity event
628 // The module name is set. I will assume that it has to be displayed, and
629 // also that it is an automatically-generated event. And of course that the
630 // fields for get_coursemodule_from_instance are set correctly.
631 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
633 if ($module === false) {
634 return;
637 $modulename = get_string('modulename', $event->modulename);
638 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
639 // will be used as alt text if the event icon
640 $eventtype = get_string($event->eventtype, $event->modulename);
641 } else {
642 $eventtype = '';
644 $icon = $OUTPUT->pix_url('icon', $event->modulename) . '';
646 $event->icon = '<img src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" class="icon" />';
647 $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
648 $event->courselink = calendar_get_courselink($module->course);
649 $event->cmid = $module->id;
651 } else if($event->courseid == SITEID) { // Site event
652 $event->icon = '<img src="'.$OUTPUT->pix_url('i/siteevent') . '" alt="'.get_string('globalevent', 'calendar').'" class="icon" />';
653 $event->cssclass = 'calendar_event_global';
654 } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
655 $event->icon = '<img src="'.$OUTPUT->pix_url('i/courseevent') . '" alt="'.get_string('courseevent', 'calendar').'" class="icon" />';
656 $event->courselink = calendar_get_courselink($event->courseid);
657 $event->cssclass = 'calendar_event_course';
658 } else if ($event->groupid) { // Group event
659 $event->icon = '<img src="'.$OUTPUT->pix_url('i/groupevent') . '" alt="'.get_string('groupevent', 'calendar').'" class="icon" />';
660 $event->courselink = calendar_get_courselink($event->courseid);
661 $event->cssclass = 'calendar_event_group';
662 } else if($event->userid) { // User event
663 $event->icon = '<img src="'.$OUTPUT->pix_url('i/userevent') . '" alt="'.get_string('userevent', 'calendar').'" class="icon" />';
664 $event->cssclass = 'calendar_event_user';
666 return $event;
670 * Get calendar events
672 * @param int $tstart Start time of time range for events
673 * @param int $tend End time of time range for events
674 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
675 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
676 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
677 * @param boolean $withduration whether only events starting within time range selected
678 * or events in progress/already started selected as well
679 * @param boolean $ignorehidden whether to select only visible events or all events
680 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
682 function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
683 global $DB;
685 $whereclause = '';
686 // Quick test
687 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
688 return array();
691 if(is_array($users) && !empty($users)) {
692 // Events from a number of users
693 if(!empty($whereclause)) $whereclause .= ' OR';
694 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
695 } else if(is_numeric($users)) {
696 // Events from one user
697 if(!empty($whereclause)) $whereclause .= ' OR';
698 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
699 } else if($users === true) {
700 // Events from ALL users
701 if(!empty($whereclause)) $whereclause .= ' OR';
702 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
703 } else if($users === false) {
704 // No user at all, do nothing
707 if(is_array($groups) && !empty($groups)) {
708 // Events from a number of groups
709 if(!empty($whereclause)) $whereclause .= ' OR';
710 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
711 } else if(is_numeric($groups)) {
712 // Events from one group
713 if(!empty($whereclause)) $whereclause .= ' OR ';
714 $whereclause .= ' groupid = '.$groups;
715 } else if($groups === true) {
716 // Events from ALL groups
717 if(!empty($whereclause)) $whereclause .= ' OR ';
718 $whereclause .= ' groupid != 0';
720 // boolean false (no groups at all): we don't need to do anything
722 if(is_array($courses) && !empty($courses)) {
723 if(!empty($whereclause)) {
724 $whereclause .= ' OR';
726 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
727 } else if(is_numeric($courses)) {
728 // One course
729 if(!empty($whereclause)) $whereclause .= ' OR';
730 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
731 } else if ($courses === true) {
732 // Events from ALL courses
733 if(!empty($whereclause)) $whereclause .= ' OR';
734 $whereclause .= ' (groupid = 0 AND courseid != 0)';
737 // Security check: if, by now, we have NOTHING in $whereclause, then it means
738 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
739 // events no matter what. Allowing the code to proceed might return a completely
740 // valid query with only time constraints, thus selecting ALL events in that time frame!
741 if(empty($whereclause)) {
742 return array();
745 if($withduration) {
746 $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
748 else {
749 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
751 if(!empty($whereclause)) {
752 // We have additional constraints
753 $whereclause = $timeclause.' AND ('.$whereclause.')';
755 else {
756 // Just basic time filtering
757 $whereclause = $timeclause;
760 if ($ignorehidden) {
761 $whereclause .= ' AND visible = 1';
764 $events = $DB->get_records_select('event', $whereclause, null, 'timestart');
765 if ($events === false) {
766 $events = array();
768 return $events;
771 /** Get calendar events by id
773 * @since Moodle 2.5
774 * @param array $eventids list of event ids
775 * @return array Array of event entries, empty array if nothing found
778 function calendar_get_events_by_id($eventids) {
779 global $DB;
781 if (!is_array($eventids) || empty($eventids)) {
782 return array();
784 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
785 $wheresql = "id $wheresql";
787 return $DB->get_records_select('event', $wheresql, $params);
791 * Get control options for Calendar
793 * @param string $type of calendar
794 * @param array $data calendar information
795 * @return string $content return available control for the calender in html
797 function calendar_top_controls($type, $data) {
798 global $PAGE;
800 // Get the calendar type we are using.
801 $calendartype = \core_calendar\type_factory::get_calendar_instance();
803 $content = '';
805 // Ensure course id passed if relevant.
806 $courseid = '';
807 if (!empty($data['id'])) {
808 $courseid = '&amp;course='.$data['id'];
811 // If we are passing a month and year then we need to convert this to a timestamp to
812 // support multiple calendars. No where in core should these be passed, this logic
813 // here is for third party plugins that may use this function.
814 if (!empty($data['m']) && !empty($date['y'])) {
815 if (!isset($data['d'])) {
816 $data['d'] = 1;
818 if (!checkdate($data['m'], $data['d'], $data['y'])) {
819 $time = time();
820 } else {
821 $time = make_timestamp($data['y'], $data['m'], $data['d']);
823 } else if (!empty($data['time'])) {
824 $time = $data['time'];
825 } else {
826 $time = time();
829 // Get the date for the calendar type.
830 $date = $calendartype->timestamp_to_date_array($time);
832 $urlbase = $PAGE->url;
834 // We need to get the previous and next months in certain cases.
835 if ($type == 'frontpage' || $type == 'course' || $type == 'month') {
836 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
837 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
838 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
839 $prevmonthtime['hour'], $prevmonthtime['minute']);
841 $nextmonth = calendar_add_month($date['mon'], $date['year']);
842 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
843 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
844 $nextmonthtime['hour'], $nextmonthtime['minute']);
847 switch ($type) {
848 case 'frontpage':
849 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false, true, $prevmonthtime);
850 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true, $nextmonthtime);
851 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view' => 'month')), false, false, false, $time);
853 if (!empty($data['id'])) {
854 $calendarlink->param('course', $data['id']);
857 if (right_to_left()) {
858 $left = $nextlink;
859 $right = $prevlink;
860 } else {
861 $left = $prevlink;
862 $right = $nextlink;
865 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
866 $content .= $left.'<span class="hide"> | </span>';
867 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
868 $content .= '<span class="hide"> | </span>'. $right;
869 $content .= "<span class=\"clearer\"><!-- --></span>\n";
870 $content .= html_writer::end_tag('div');
872 break;
873 case 'course':
874 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false, true, $prevmonthtime);
875 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true, $nextmonthtime);
876 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view' => 'month')), false, false, false, $time);
878 if (!empty($data['id'])) {
879 $calendarlink->param('course', $data['id']);
882 if (right_to_left()) {
883 $left = $nextlink;
884 $right = $prevlink;
885 } else {
886 $left = $prevlink;
887 $right = $nextlink;
890 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
891 $content .= $left.'<span class="hide"> | </span>';
892 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
893 $content .= '<span class="hide"> | </span>'. $right;
894 $content .= "<span class=\"clearer\"><!-- --></span>";
895 $content .= html_writer::end_tag('div');
896 break;
897 case 'upcoming':
898 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view' => 'upcoming')), false, false, false, $time);
899 if (!empty($data['id'])) {
900 $calendarlink->param('course', $data['id']);
902 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
903 $content .= html_writer::tag('div', $calendarlink, array('class'=>'centered'));
904 break;
905 case 'display':
906 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view' => 'month')), false, false, false, $time);
907 if (!empty($data['id'])) {
908 $calendarlink->param('course', $data['id']);
910 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
911 $content .= html_writer::tag('h3', $calendarlink);
912 break;
913 case 'month':
914 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', false, false, false, false, $prevmonthtime);
915 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', false, false, false, false, $nextmonthtime);
917 if (right_to_left()) {
918 $left = $nextlink;
919 $right = $prevlink;
920 } else {
921 $left = $prevlink;
922 $right = $nextlink;
925 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
926 $content .= $left . '<span class="hide"> | </span><h1 class="current">'.userdate($time, get_string('strftimemonthyear'))."</h1>";
927 $content .= '<span class="hide"> | </span>' . $right;
928 $content .= '<span class="clearer"><!-- --></span>';
929 $content .= html_writer::end_tag('div')."\n";
930 break;
931 case 'day':
932 $days = calendar_get_days();
934 $prevtimestamp = $time - DAYSECS;
935 $nexttimestamp = $time + DAYSECS;
937 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
938 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
940 $prevname = $days[$prevdate['wday']]['fullname'];
941 $nextname = $days[$nextdate['wday']]['fullname'];
942 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&amp;', false, false, false, false, $prevtimestamp);
943 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&amp;', false, false, false, false, $nexttimestamp);
945 if (right_to_left()) {
946 $left = $nextlink;
947 $right = $prevlink;
948 } else {
949 $left = $prevlink;
950 $right = $nextlink;
953 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
954 $content .= $left;
955 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimedaydate')).'</span>';
956 $content .= '<span class="hide"> | </span>'. $right;
957 $content .= "<span class=\"clearer\"><!-- --></span>";
958 $content .= html_writer::end_tag('div')."\n";
960 break;
962 return $content;
966 * Formats a filter control element.
968 * @param moodle_url $url of the filter
969 * @param int $type constant defining the type filter
970 * @return string html content of the element
972 function calendar_filter_controls_element(moodle_url $url, $type) {
973 global $OUTPUT;
974 switch ($type) {
975 case CALENDAR_EVENT_GLOBAL:
976 $typeforhumans = 'global';
977 $class = 'calendar_event_global';
978 break;
979 case CALENDAR_EVENT_COURSE:
980 $typeforhumans = 'course';
981 $class = 'calendar_event_course';
982 break;
983 case CALENDAR_EVENT_GROUP:
984 $typeforhumans = 'groups';
985 $class = 'calendar_event_group';
986 break;
987 case CALENDAR_EVENT_USER:
988 $typeforhumans = 'user';
989 $class = 'calendar_event_user';
990 break;
992 if (calendar_show_event_type($type)) {
993 $icon = $OUTPUT->pix_icon('t/hide', get_string('hide'));
994 $str = get_string('hide'.$typeforhumans.'events', 'calendar');
995 } else {
996 $icon = $OUTPUT->pix_icon('t/show', get_string('show'));
997 $str = get_string('show'.$typeforhumans.'events', 'calendar');
999 $content = html_writer::start_tag('li', array('class' => 'calendar_event'));
1000 $content .= html_writer::start_tag('a', array('href' => $url));
1001 $content .= html_writer::tag('span', $icon, array('class' => $class));
1002 $content .= html_writer::tag('span', $str, array('class' => 'eventname'));
1003 $content .= html_writer::end_tag('a');
1004 $content .= html_writer::end_tag('li');
1005 return $content;
1009 * Get the controls filter for calendar.
1011 * Filter is used to hide calendar info from the display page
1013 * @param moodle_url $returnurl return-url for filter controls
1014 * @return string $content return filter controls in html
1016 function calendar_filter_controls(moodle_url $returnurl) {
1017 global $CFG, $USER, $OUTPUT;
1019 $groupevents = true;
1020 $id = optional_param( 'id',0,PARAM_INT );
1021 $seturl = new moodle_url('/calendar/set.php', array('return' => base64_encode($returnurl->out(false)), 'sesskey'=>sesskey()));
1022 $content = html_writer::start_tag('ul');
1024 $seturl->param('var', 'showglobal');
1025 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GLOBAL);
1027 $seturl->param('var', 'showcourses');
1028 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_COURSE);
1030 if (isloggedin() && !isguestuser()) {
1031 if ($groupevents) {
1032 // This course MIGHT have group events defined, so show the filter
1033 $seturl->param('var', 'showgroups');
1034 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GROUP);
1035 } else {
1036 // This course CANNOT have group events, so lose the filter
1038 $seturl->param('var', 'showuser');
1039 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_USER);
1041 $content .= html_writer::end_tag('ul');
1043 return $content;
1047 * Return the representation day
1049 * @param int $tstamp Timestamp in GMT
1050 * @param int $now current Unix timestamp
1051 * @param bool $usecommonwords
1052 * @return string the formatted date/time
1054 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1056 static $shortformat;
1057 if(empty($shortformat)) {
1058 $shortformat = get_string('strftimedayshort');
1061 if($now === false) {
1062 $now = time();
1065 // To have it in one place, if a change is needed
1066 $formal = userdate($tstamp, $shortformat);
1068 $datestamp = usergetdate($tstamp);
1069 $datenow = usergetdate($now);
1071 if($usecommonwords == false) {
1072 // We don't want words, just a date
1073 return $formal;
1075 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1076 // Today
1077 return get_string('today', 'calendar');
1079 else if(
1080 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1081 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
1083 // Yesterday
1084 return get_string('yesterday', 'calendar');
1086 else if(
1087 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1088 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
1090 // Tomorrow
1091 return get_string('tomorrow', 'calendar');
1093 else {
1094 return $formal;
1099 * return the formatted representation time
1101 * @param int $time the timestamp in UTC, as obtained from the database
1102 * @return string the formatted date/time
1104 function calendar_time_representation($time) {
1105 static $langtimeformat = NULL;
1106 if($langtimeformat === NULL) {
1107 $langtimeformat = get_string('strftimetime');
1109 $timeformat = get_user_preferences('calendar_timeformat');
1110 if(empty($timeformat)){
1111 $timeformat = get_config(NULL,'calendar_site_timeformat');
1113 // The ? is needed because the preference might be present, but empty
1114 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
1118 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1120 * @param string|moodle_url $linkbase
1121 * @param int $d The number of the day.
1122 * @param int $m The number of the month.
1123 * @param int $y The number of the year.
1124 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1125 * $m and $y are kept for backwards compatibility.
1126 * @return moodle_url|null $linkbase
1128 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1129 if (empty($linkbase)) {
1130 return '';
1132 if (!($linkbase instanceof moodle_url)) {
1133 $linkbase = new moodle_url($linkbase);
1136 // If a day, month and year were passed then convert it to a timestamp. If these were passed
1137 // then we can assume the day, month and year are passed as Gregorian, as no where in core
1138 // should we be passing these values rather than the time.
1139 if (!empty($d) && !empty($m) && !empty($y)) {
1140 if (checkdate($m, $d, $y)) {
1141 $time = make_timestamp($y, $m, $d);
1142 } else {
1143 $time = time();
1145 } else if (empty($time)) {
1146 $time = time();
1149 $linkbase->param('time', $time);
1151 return $linkbase;
1155 * Build and return a previous month HTML link, with an arrow.
1157 * @param string $text The text label.
1158 * @param string|moodle_url $linkbase The URL stub.
1159 * @param int $d The number of the date.
1160 * @param int $m The number of the month.
1161 * @param int $y year The number of the year.
1162 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1163 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1164 * $m and $y are kept for backwards compatibility.
1165 * @return string HTML string.
1167 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1168 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y, $time);
1169 if (empty($href)) {
1170 return $text;
1172 return link_arrow_left($text, (string)$href, $accesshide, 'previous');
1176 * Build and return a next month HTML link, with an arrow.
1178 * @param string $text The text label.
1179 * @param string|moodle_url $linkbase The URL stub.
1180 * @param int $d the number of the Day
1181 * @param int $m The number of the month.
1182 * @param int $y The number of the year.
1183 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1184 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1185 * $m and $y are kept for backwards compatibility.
1186 * @return string HTML string.
1188 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1189 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y, $time);
1190 if (empty($href)) {
1191 return $text;
1193 return link_arrow_right($text, (string)$href, $accesshide, 'next');
1197 * Return the name of the weekday
1199 * @param string $englishname
1200 * @return string of the weekeday
1202 function calendar_wday_name($englishname) {
1203 return get_string(strtolower($englishname), 'calendar');
1207 * Return the number of days in month
1209 * @param int $month the number of the month.
1210 * @param int $year the number of the year
1211 * @return int
1213 function calendar_days_in_month($month, $year) {
1214 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1215 return $calendartype->get_num_days_in_month($year, $month);
1219 * Get the upcoming event block
1221 * @param array $events list of events
1222 * @param moodle_url|string $linkhref link to event referer
1223 * @param boolean $showcourselink whether links to courses should be shown
1224 * @return string|null $content html block content
1226 function calendar_get_block_upcoming($events, $linkhref = NULL, $showcourselink = false) {
1227 $content = '';
1228 $lines = count($events);
1229 if (!$lines) {
1230 return $content;
1233 for ($i = 0; $i < $lines; ++$i) {
1234 if (!isset($events[$i]->time)) { // Just for robustness
1235 continue;
1237 $events[$i] = calendar_add_event_metadata($events[$i]);
1238 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span>';
1239 if (!empty($events[$i]->referer)) {
1240 // That's an activity event, so let's provide the hyperlink
1241 $content .= $events[$i]->referer;
1242 } else {
1243 if(!empty($linkhref)) {
1244 $href = calendar_get_link_href(new moodle_url(CALENDAR_URL . $linkhref), 0, 0, 0, $events[$i]->timestart);
1245 $href->set_anchor('event_'.$events[$i]->id);
1246 $content .= html_writer::link($href, $events[$i]->name);
1248 else {
1249 $content .= $events[$i]->name;
1252 $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
1253 if ($showcourselink && !empty($events[$i]->courselink)) {
1254 $content .= html_writer::div($events[$i]->courselink, 'course');
1256 $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
1257 if ($i < $lines - 1) $content .= '<hr />';
1260 return $content;
1264 * Get the next following month
1266 * @param int $month the number of the month.
1267 * @param int $year the number of the year.
1268 * @return array the following month
1270 function calendar_add_month($month, $year) {
1271 // Get the calendar type we are using.
1272 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1273 return $calendartype->get_next_month($year, $month);
1277 * Get the previous month.
1279 * @param int $month the number of the month.
1280 * @param int $year the number of the year.
1281 * @return array previous month
1283 function calendar_sub_month($month, $year) {
1284 // Get the calendar type we are using.
1285 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1286 return $calendartype->get_prev_month($year, $month);
1290 * Get per-day basis events
1292 * @param array $events list of events
1293 * @param int $month the number of the month
1294 * @param int $year the number of the year
1295 * @param array $eventsbyday event on specific day
1296 * @param array $durationbyday duration of the event in days
1297 * @param array $typesbyday event type (eg: global, course, user, or group)
1298 * @param array $courses list of courses
1299 * @return void
1301 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1302 // Get the calendar type we are using.
1303 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1305 $eventsbyday = array();
1306 $typesbyday = array();
1307 $durationbyday = array();
1309 if($events === false) {
1310 return;
1313 foreach ($events as $event) {
1314 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
1315 // Set end date = start date if no duration
1316 if ($event->timeduration) {
1317 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
1318 } else {
1319 $enddate = $startdate;
1322 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
1323 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1324 // Out of bounds
1325 continue;
1328 $eventdaystart = intval($startdate['mday']);
1330 if($startdate['mon'] == $month && $startdate['year'] == $year) {
1331 // Give the event to its day
1332 $eventsbyday[$eventdaystart][] = $event->id;
1334 // Mark the day as having such an event
1335 if($event->courseid == SITEID && $event->groupid == 0) {
1336 $typesbyday[$eventdaystart]['startglobal'] = true;
1337 // Set event class for global event
1338 $events[$event->id]->class = 'calendar_event_global';
1340 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1341 $typesbyday[$eventdaystart]['startcourse'] = true;
1342 // Set event class for course event
1343 $events[$event->id]->class = 'calendar_event_course';
1345 else if($event->groupid) {
1346 $typesbyday[$eventdaystart]['startgroup'] = true;
1347 // Set event class for group event
1348 $events[$event->id]->class = 'calendar_event_group';
1350 else if($event->userid) {
1351 $typesbyday[$eventdaystart]['startuser'] = true;
1352 // Set event class for user event
1353 $events[$event->id]->class = 'calendar_event_user';
1357 if($event->timeduration == 0) {
1358 // Proceed with the next
1359 continue;
1362 // The event starts on $month $year or before. So...
1363 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
1365 // Also, it ends on $month $year or later...
1366 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
1368 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1369 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
1370 $durationbyday[$i][] = $event->id;
1371 if($event->courseid == SITEID && $event->groupid == 0) {
1372 $typesbyday[$i]['durationglobal'] = true;
1374 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1375 $typesbyday[$i]['durationcourse'] = true;
1377 else if($event->groupid) {
1378 $typesbyday[$i]['durationgroup'] = true;
1380 else if($event->userid) {
1381 $typesbyday[$i]['durationuser'] = true;
1386 return;
1390 * Get current module cache
1392 * @param array $coursecache list of course cache
1393 * @param string $modulename name of the module
1394 * @param int $instance module instance number
1395 * @return stdClass|bool $module information
1397 function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1398 $module = get_coursemodule_from_instance($modulename, $instance);
1400 if($module === false) return false;
1401 if(!calendar_get_course_cached($coursecache, $module->course)) {
1402 return false;
1404 return $module;
1408 * Get current course cache
1410 * @param array $coursecache list of course cache
1411 * @param int $courseid id of the course
1412 * @return stdClass $coursecache[$courseid] return the specific course cache
1414 function calendar_get_course_cached(&$coursecache, $courseid) {
1415 if (!isset($coursecache[$courseid])) {
1416 $coursecache[$courseid] = get_course($courseid);
1418 return $coursecache[$courseid];
1422 * Returns the courses to load events for, the
1424 * @param array $courseeventsfrom An array of courses to load calendar events for
1425 * @param bool $ignorefilters specify the use of filters, false is set as default
1426 * @return array An array of courses, groups, and user to load calendar events for based upon filters
1428 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
1429 global $USER, $CFG, $DB;
1431 // For backwards compatability we have to check whether the courses array contains
1432 // just id's in which case we need to load course objects.
1433 $coursestoload = array();
1434 foreach ($courseeventsfrom as $id => $something) {
1435 if (!is_object($something)) {
1436 $coursestoload[] = $id;
1437 unset($courseeventsfrom[$id]);
1440 if (!empty($coursestoload)) {
1441 // TODO remove this in 2.2
1442 debugging('calendar_set_filters now preferes an array of course objects with preloaded contexts', DEBUG_DEVELOPER);
1443 $courseeventsfrom = array_merge($courseeventsfrom, $DB->get_records_list('course', 'id', $coursestoload));
1446 $courses = array();
1447 $user = false;
1448 $group = false;
1450 // capabilities that allow seeing group events from all groups
1451 // TODO: rewrite so that moodle/calendar:manageentries is not necessary here
1452 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
1454 $isloggedin = isloggedin();
1456 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
1457 $courses = array_keys($courseeventsfrom);
1459 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
1460 $courses[] = SITEID;
1462 $courses = array_unique($courses);
1463 sort($courses);
1465 if (!empty($courses) && in_array(SITEID, $courses)) {
1466 // Sort courses for consistent colour highlighting
1467 // Effectively ignoring SITEID as setting as last course id
1468 $key = array_search(SITEID, $courses);
1469 unset($courses[$key]);
1470 $courses[] = SITEID;
1473 if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
1474 $user = $USER->id;
1477 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
1479 if (count($courseeventsfrom)==1) {
1480 $course = reset($courseeventsfrom);
1481 if (has_any_capability($allgroupscaps, context_course::instance($course->id))) {
1482 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
1483 $group = array_keys($coursegroups);
1486 if ($group === false) {
1487 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, context_system::instance())) {
1488 $group = true;
1489 } else if ($isloggedin) {
1490 $groupids = array();
1492 // We already have the courses to examine in $courses
1493 // For each course...
1494 foreach ($courseeventsfrom as $courseid => $course) {
1495 // If the user is an editing teacher in there,
1496 if (!empty($USER->groupmember[$course->id])) {
1497 // We've already cached the users groups for this course so we can just use that
1498 $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
1499 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1500 // If this course has groups, show events from all of those related to the current user
1501 $coursegroups = groups_get_user_groups($course->id, $USER->id);
1502 $groupids = array_merge($groupids, $coursegroups['0']);
1505 if (!empty($groupids)) {
1506 $group = $groupids;
1511 if (empty($courses)) {
1512 $courses = false;
1515 return array($courses, $group, $user);
1519 * Return the capability for editing calendar event
1521 * @param calendar_event $event event object
1522 * @return bool capability to edit event
1524 function calendar_edit_event_allowed($event) {
1525 global $USER, $DB;
1527 // Must be logged in
1528 if (!isloggedin()) {
1529 return false;
1532 // can not be using guest account
1533 if (isguestuser()) {
1534 return false;
1537 // You cannot edit calendar subscription events presently.
1538 if (!empty($event->subscriptionid)) {
1539 return false;
1542 $sitecontext = context_system::instance();
1543 // if user has manageentries at site level, return true
1544 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1545 return true;
1548 // if groupid is set, it's definitely a group event
1549 if (!empty($event->groupid)) {
1550 // Allow users to add/edit group events if:
1551 // 1) They have manageentries (= entries for whole course)
1552 // 2) They have managegroupentries AND are in the group
1553 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1554 return $group && (
1555 has_capability('moodle/calendar:manageentries', $event->context) ||
1556 (has_capability('moodle/calendar:managegroupentries', $event->context)
1557 && groups_is_member($event->groupid)));
1558 } else if (!empty($event->courseid)) {
1559 // if groupid is not set, but course is set,
1560 // it's definiely a course event
1561 return has_capability('moodle/calendar:manageentries', $event->context);
1562 } else if (!empty($event->userid) && $event->userid == $USER->id) {
1563 // if course is not set, but userid id set, it's a user event
1564 return (has_capability('moodle/calendar:manageownentries', $event->context));
1565 } else if (!empty($event->userid)) {
1566 return (has_capability('moodle/calendar:manageentries', $event->context));
1568 return false;
1572 * Returns the default courses to display on the calendar when there isn't a specific
1573 * course to display.
1575 * @return array $courses Array of courses to display
1577 function calendar_get_default_courses() {
1578 global $CFG, $DB;
1580 if (!isloggedin()) {
1581 return array();
1584 $courses = array();
1585 if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', context_system::instance())) {
1586 $select = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1587 $join = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1588 $sql = "SELECT c.* $select
1589 FROM {course} c
1590 $join
1591 WHERE EXISTS (SELECT 1 FROM {event} e WHERE e.courseid = c.id)
1593 $courses = $DB->get_records_sql($sql, array('contextlevel' => CONTEXT_COURSE), 0, 20);
1594 foreach ($courses as $course) {
1595 context_helper::preload_from_record($course);
1597 return $courses;
1600 $courses = enrol_get_my_courses();
1602 return $courses;
1606 * Display calendar preference button
1608 * @param stdClass $course course object
1609 * @return string return preference button in html
1611 function calendar_preferences_button(stdClass $course) {
1612 global $OUTPUT;
1614 // Guests have no preferences
1615 if (!isloggedin() || isguestuser()) {
1616 return '';
1619 return $OUTPUT->single_button(new moodle_url('/calendar/preferences.php', array('course' => $course->id)), get_string("preferences", "calendar"));
1623 * Get event format time
1625 * @param calendar_event $event event object
1626 * @param int $now current time in gmt
1627 * @param array $linkparams list of params for event link
1628 * @param bool $usecommonwords the words as formatted date/time.
1629 * @param int $showtime determine the show time GMT timestamp
1630 * @return string $eventtime link/string for event time
1632 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
1633 $starttime = $event->timestart;
1634 $endtime = $event->timestart + $event->timeduration;
1636 if (empty($linkparams) || !is_array($linkparams)) {
1637 $linkparams = array();
1640 $linkparams['view'] = 'day';
1642 // OK, now to get a meaningful display...
1643 // Check if there is a duration for this event.
1644 if ($event->timeduration) {
1645 // Get the midnight of the day the event will start.
1646 $usermidnightstart = usergetmidnight($starttime);
1647 // Get the midnight of the day the event will end.
1648 $usermidnightend = usergetmidnight($endtime);
1649 // Check if we will still be on the same day.
1650 if ($usermidnightstart == $usermidnightend) {
1651 // Check if we are running all day.
1652 if ($event->timeduration == DAYSECS) {
1653 $time = get_string('allday', 'calendar');
1654 } else { // Specify the time we will be running this from.
1655 $datestart = calendar_time_representation($starttime);
1656 $dateend = calendar_time_representation($endtime);
1657 $time = $datestart . ' <strong>&raquo;</strong> ' . $dateend;
1660 // Set printable representation.
1661 if (!$showtime) {
1662 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1663 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
1664 $eventtime = html_writer::link($url, $day) . ', ' . $time;
1665 } else {
1666 $eventtime = $time;
1668 } else { // It must spans two or more days.
1669 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
1670 if ($showtime == $usermidnightstart) {
1671 $daystart = '';
1673 $timestart = calendar_time_representation($event->timestart);
1674 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
1675 if ($showtime == $usermidnightend) {
1676 $dayend = '';
1678 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1680 // Set printable representation.
1681 if ($now >= $usermidnightstart && $now < ($usermidnightstart + DAYSECS)) {
1682 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
1683 $eventtime = $timestart . ' <strong>&raquo;</strong> ' . html_writer::link($url, $dayend) . $timeend;
1684 } else {
1685 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
1686 $eventtime = html_writer::link($url, $daystart) . $timestart . ' <strong>&raquo;</strong> ';
1688 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
1689 $eventtime .= html_writer::link($url, $dayend) . $timeend;
1692 } else { // There is no time duration.
1693 $time = calendar_time_representation($event->timestart);
1694 // Set printable representation.
1695 if (!$showtime) {
1696 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1697 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
1698 $eventtime = html_writer::link($url, $day) . ', ' . trim($time);
1699 } else {
1700 $eventtime = $time;
1704 // Check if It has expired.
1705 if ($event->timestart + $event->timeduration < $now) {
1706 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
1709 return $eventtime;
1713 * Display month selector options
1715 * @param string $name for the select element
1716 * @param string|array $selected options for select elements
1718 function calendar_print_month_selector($name, $selected) {
1719 $months = array();
1720 for ($i=1; $i<=12; $i++) {
1721 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
1723 echo html_writer::label(get_string('months'), 'menu'. $name, false, array('class' => 'accesshide'));
1724 echo html_writer::select($months, $name, $selected, false);
1728 * Checks to see if the requested type of event should be shown for the given user.
1730 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
1731 * The type to check the display for (default is to display all)
1732 * @param stdClass|int|null $user The user to check for - by default the current user
1733 * @return bool True if the tyep should be displayed false otherwise
1735 function calendar_show_event_type($type, $user = null) {
1736 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1737 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
1738 global $SESSION;
1739 if (!isset($SESSION->calendarshoweventtype)) {
1740 $SESSION->calendarshoweventtype = $default;
1742 return $SESSION->calendarshoweventtype & $type;
1743 } else {
1744 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
1749 * Sets the display of the event type given $display.
1751 * If $display = true the event type will be shown.
1752 * If $display = false the event type will NOT be shown.
1753 * If $display = null the current value will be toggled and saved.
1755 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type object of CALENDAR_EVENT_XXX
1756 * @param bool $display option to display event type
1757 * @param stdClass|int $user moodle user object or id, null means current user
1759 function calendar_set_event_type_display($type, $display = null, $user = null) {
1760 $persist = get_user_preferences('calendar_persistflt', 0, $user);
1761 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1762 if ($persist === 0) {
1763 global $SESSION;
1764 if (!isset($SESSION->calendarshoweventtype)) {
1765 $SESSION->calendarshoweventtype = $default;
1767 $preference = $SESSION->calendarshoweventtype;
1768 } else {
1769 $preference = get_user_preferences('calendar_savedflt', $default, $user);
1771 $current = $preference & $type;
1772 if ($display === null) {
1773 $display = !$current;
1775 if ($display && !$current) {
1776 $preference += $type;
1777 } else if (!$display && $current) {
1778 $preference -= $type;
1780 if ($persist === 0) {
1781 $SESSION->calendarshoweventtype = $preference;
1782 } else {
1783 if ($preference == $default) {
1784 unset_user_preference('calendar_savedflt', $user);
1785 } else {
1786 set_user_preference('calendar_savedflt', $preference, $user);
1792 * Get calendar's allowed types
1794 * @param stdClass $allowed list of allowed edit for event type
1795 * @param stdClass|int $course object of a course or course id
1797 function calendar_get_allowed_types(&$allowed, $course = null) {
1798 global $USER, $CFG, $DB;
1799 $allowed = new stdClass();
1800 $allowed->user = has_capability('moodle/calendar:manageownentries', context_system::instance());
1801 $allowed->groups = false; // This may change just below
1802 $allowed->courses = false; // This may change just below
1803 $allowed->site = has_capability('moodle/calendar:manageentries', context_course::instance(SITEID));
1805 if (!empty($course)) {
1806 if (!is_object($course)) {
1807 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST);
1809 if ($course->id != SITEID) {
1810 $coursecontext = context_course::instance($course->id);
1811 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
1813 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
1814 $allowed->courses = array($course->id => 1);
1816 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1817 if (has_capability('moodle/site:accessallgroups', $coursecontext)) {
1818 $allowed->groups = groups_get_all_groups($course->id);
1819 } else {
1820 $allowed->groups = groups_get_all_groups($course->id, $USER->id);
1823 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
1824 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1825 if (has_capability('moodle/site:accessallgroups', $coursecontext)) {
1826 $allowed->groups = groups_get_all_groups($course->id);
1827 } else {
1828 $allowed->groups = groups_get_all_groups($course->id, $USER->id);
1837 * See if user can add calendar entries at all
1838 * used to print the "New Event" button
1840 * @param stdClass $course object of a course or course id
1841 * @return bool has the capability to add at least one event type
1843 function calendar_user_can_add_event($course) {
1844 if (!isloggedin() || isguestuser()) {
1845 return false;
1847 calendar_get_allowed_types($allowed, $course);
1848 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);
1852 * Check wether the current user is permitted to add events
1854 * @param stdClass $event object of event
1855 * @return bool has the capability to add event
1857 function calendar_add_event_allowed($event) {
1858 global $USER, $DB;
1860 // can not be using guest account
1861 if (!isloggedin() or isguestuser()) {
1862 return false;
1865 $sitecontext = context_system::instance();
1866 // if user has manageentries at site level, always return true
1867 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1868 return true;
1871 switch ($event->eventtype) {
1872 case 'course':
1873 return has_capability('moodle/calendar:manageentries', $event->context);
1875 case 'group':
1876 // Allow users to add/edit group events if:
1877 // 1) They have manageentries (= entries for whole course)
1878 // 2) They have managegroupentries AND are in the group
1879 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1880 return $group && (
1881 has_capability('moodle/calendar:manageentries', $event->context) ||
1882 (has_capability('moodle/calendar:managegroupentries', $event->context)
1883 && groups_is_member($event->groupid)));
1885 case 'user':
1886 if ($event->userid == $USER->id) {
1887 return (has_capability('moodle/calendar:manageownentries', $event->context));
1889 //there is no 'break;' intentionally
1891 case 'site':
1892 return has_capability('moodle/calendar:manageentries', $event->context);
1894 default:
1895 return has_capability('moodle/calendar:manageentries', $event->context);
1900 * Manage calendar events
1902 * This class provides the required functionality in order to manage calendar events.
1903 * It was introduced as part of Moodle 2.0 and was created in order to provide a
1904 * better framework for dealing with calendar events in particular regard to file
1905 * handling through the new file API
1907 * @package core_calendar
1908 * @category calendar
1909 * @copyright 2009 Sam Hemelryk
1910 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1912 * @property int $id The id within the event table
1913 * @property string $name The name of the event
1914 * @property string $description The description of the event
1915 * @property int $format The format of the description FORMAT_?
1916 * @property int $courseid The course the event is associated with (0 if none)
1917 * @property int $groupid The group the event is associated with (0 if none)
1918 * @property int $userid The user the event is associated with (0 if none)
1919 * @property int $repeatid If this is a repeated event this will be set to the
1920 * id of the original
1921 * @property string $modulename If added by a module this will be the module name
1922 * @property int $instance If added by a module this will be the module instance
1923 * @property string $eventtype The event type
1924 * @property int $timestart The start time as a timestamp
1925 * @property int $timeduration The duration of the event in seconds
1926 * @property int $visible 1 if the event is visible
1927 * @property int $uuid ?
1928 * @property int $sequence ?
1929 * @property int $timemodified The time last modified as a timestamp
1931 class calendar_event {
1933 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
1934 protected $properties = null;
1937 * @var string The converted event discription with file paths resolved. This gets populated when someone requests description for the first time */
1938 protected $_description = null;
1940 /** @var array The options to use with this description editor */
1941 protected $editoroptions = array(
1942 'subdirs'=>false,
1943 'forcehttps'=>false,
1944 'maxfiles'=>-1,
1945 'maxbytes'=>null,
1946 'trusttext'=>false);
1948 /** @var object The context to use with the description editor */
1949 protected $editorcontext = null;
1952 * Instantiates a new event and optionally populates its properties with the
1953 * data provided
1955 * @param stdClass $data Optional. An object containing the properties to for
1956 * an event
1958 public function __construct($data=null) {
1959 global $CFG, $USER;
1961 // First convert to object if it is not already (should either be object or assoc array)
1962 if (!is_object($data)) {
1963 $data = (object)$data;
1966 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
1968 $data->eventrepeats = 0;
1970 if (empty($data->id)) {
1971 $data->id = null;
1974 if (!empty($data->subscriptionid)) {
1975 $data->subscription = calendar_get_subscription($data->subscriptionid);
1978 // Default to a user event
1979 if (empty($data->eventtype)) {
1980 $data->eventtype = 'user';
1983 // Default to the current user
1984 if (empty($data->userid)) {
1985 $data->userid = $USER->id;
1988 if (!empty($data->timeduration) && is_array($data->timeduration)) {
1989 $data->timeduration = make_timestamp($data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'], $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
1991 if (!empty($data->description) && is_array($data->description)) {
1992 $data->format = $data->description['format'];
1993 $data->description = $data->description['text'];
1994 } else if (empty($data->description)) {
1995 $data->description = '';
1996 $data->format = editors_get_preferred_format();
1998 // Ensure form is defaulted correctly
1999 if (empty($data->format)) {
2000 $data->format = editors_get_preferred_format();
2003 if (empty($data->context)) {
2004 $data->context = $this->calculate_context($data);
2006 $this->properties = $data;
2010 * Magic property method
2012 * Attempts to call a set_$key method if one exists otherwise falls back
2013 * to simply set the property
2015 * @param string $key property name
2016 * @param mixed $value value of the property
2018 public function __set($key, $value) {
2019 if (method_exists($this, 'set_'.$key)) {
2020 $this->{'set_'.$key}($value);
2022 $this->properties->{$key} = $value;
2026 * Magic get method
2028 * Attempts to call a get_$key method to return the property and ralls over
2029 * to return the raw property
2031 * @param string $key property name
2032 * @return mixed property value
2034 public function __get($key) {
2035 if (method_exists($this, 'get_'.$key)) {
2036 return $this->{'get_'.$key}();
2038 if (!isset($this->properties->{$key})) {
2039 throw new coding_exception('Undefined property requested');
2041 return $this->properties->{$key};
2045 * Stupid PHP needs an isset magic method if you use the get magic method and
2046 * still want empty calls to work.... blah ~!
2048 * @param string $key $key property name
2049 * @return bool|mixed property value, false if property is not exist
2051 public function __isset($key) {
2052 return !empty($this->properties->{$key});
2056 * Calculate the context value needed for calendar_event.
2057 * Event's type can be determine by the available value store in $data
2058 * It is important to check for the existence of course/courseid to determine
2059 * the course event.
2060 * Default value is set to CONTEXT_USER
2062 * @param stdClass $data information about event
2063 * @return stdClass The context object.
2065 protected function calculate_context(stdClass $data) {
2066 global $USER, $DB;
2068 $context = null;
2069 if (isset($data->courseid) && $data->courseid > 0) {
2070 $context = context_course::instance($data->courseid);
2071 } else if (isset($data->course) && $data->course > 0) {
2072 $context = context_course::instance($data->course);
2073 } else if (isset($data->groupid) && $data->groupid > 0) {
2074 $group = $DB->get_record('groups', array('id'=>$data->groupid));
2075 $context = context_course::instance($group->courseid);
2076 } else if (isset($data->userid) && $data->userid > 0 && $data->userid == $USER->id) {
2077 $context = context_user::instance($data->userid);
2078 } else if (isset($data->userid) && $data->userid > 0 && $data->userid != $USER->id &&
2079 isset($data->instance) && $data->instance > 0) {
2080 $cm = get_coursemodule_from_instance($data->modulename, $data->instance, 0, false, MUST_EXIST);
2081 $context = context_course::instance($cm->course);
2082 } else {
2083 $context = context_user::instance($data->userid);
2086 return $context;
2090 * Returns an array of editoroptions for this event: Called by __get
2091 * Please use $blah = $event->editoroptions;
2093 * @return array event editor options
2095 protected function get_editoroptions() {
2096 return $this->editoroptions;
2100 * Returns an event description: Called by __get
2101 * Please use $blah = $event->description;
2103 * @return string event description
2105 protected function get_description() {
2106 global $CFG;
2108 require_once($CFG->libdir . '/filelib.php');
2110 if ($this->_description === null) {
2111 // Check if we have already resolved the context for this event
2112 if ($this->editorcontext === null) {
2113 // Switch on the event type to decide upon the appropriate context
2114 // to use for this event
2115 $this->editorcontext = $this->properties->context;
2116 if ($this->properties->eventtype != 'user' && $this->properties->eventtype != 'course'
2117 && $this->properties->eventtype != 'site' && $this->properties->eventtype != 'group') {
2118 return clean_text($this->properties->description, $this->properties->format);
2122 // Work out the item id for the editor, if this is a repeated event then the files will
2123 // be associated with the original
2124 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2125 $itemid = $this->properties->repeatid;
2126 } else {
2127 $itemid = $this->properties->id;
2130 // Convert file paths in the description so that things display correctly
2131 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php', $this->editorcontext->id, 'calendar', 'event_description', $itemid);
2132 // Clean the text so no nasties get through
2133 $this->_description = clean_text($this->_description, $this->properties->format);
2135 // Finally return the description
2136 return $this->_description;
2140 * Return the number of repeat events there are in this events series
2142 * @return int number of event repeated
2144 public function count_repeats() {
2145 global $DB;
2146 if (!empty($this->properties->repeatid)) {
2147 $this->properties->eventrepeats = $DB->count_records('event', array('repeatid'=>$this->properties->repeatid));
2148 // We don't want to count ourselves
2149 $this->properties->eventrepeats--;
2151 return $this->properties->eventrepeats;
2155 * Update or create an event within the database
2157 * Pass in a object containing the event properties and this function will
2158 * insert it into the database and deal with any associated files
2160 * @see add_event()
2161 * @see update_event()
2163 * @param stdClass $data object of event
2164 * @param bool $checkcapability if moodle should check calendar managing capability or not
2165 * @return bool event updated
2167 public function update($data, $checkcapability=true) {
2168 global $DB, $USER;
2170 foreach ($data as $key=>$value) {
2171 $this->properties->$key = $value;
2174 $this->properties->timemodified = time();
2175 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
2177 // Prepare event data.
2178 $eventargs = array(
2179 'context' => $this->properties->context,
2180 'objectid' => $this->properties->id,
2181 'other' => array(
2182 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
2183 'timestart' => $this->properties->timestart,
2184 'name' => $this->properties->name
2188 if (empty($this->properties->id) || $this->properties->id < 1) {
2190 if ($checkcapability) {
2191 if (!calendar_add_event_allowed($this->properties)) {
2192 print_error('nopermissiontoupdatecalendar');
2196 if ($usingeditor) {
2197 switch ($this->properties->eventtype) {
2198 case 'user':
2199 $this->properties->courseid = 0;
2200 $this->properties->course = 0;
2201 $this->properties->groupid = 0;
2202 $this->properties->userid = $USER->id;
2203 break;
2204 case 'site':
2205 $this->properties->courseid = SITEID;
2206 $this->properties->course = SITEID;
2207 $this->properties->groupid = 0;
2208 $this->properties->userid = $USER->id;
2209 break;
2210 case 'course':
2211 $this->properties->groupid = 0;
2212 $this->properties->userid = $USER->id;
2213 break;
2214 case 'group':
2215 $this->properties->userid = $USER->id;
2216 break;
2217 default:
2218 // Ewww we should NEVER get here, but just incase we do lets
2219 // fail gracefully
2220 $usingeditor = false;
2221 break;
2224 // If we are actually using the editor, we recalculate the context because some default values
2225 // were set when calculate_context() was called from the constructor.
2226 if ($usingeditor) {
2227 $this->properties->context = $this->calculate_context($this->properties);
2228 $this->editorcontext = $this->properties->context;
2231 $editor = $this->properties->description;
2232 $this->properties->format = $this->properties->description['format'];
2233 $this->properties->description = $this->properties->description['text'];
2236 // Insert the event into the database
2237 $this->properties->id = $DB->insert_record('event', $this->properties);
2239 if ($usingeditor) {
2240 $this->properties->description = file_save_draft_area_files(
2241 $editor['itemid'],
2242 $this->editorcontext->id,
2243 'calendar',
2244 'event_description',
2245 $this->properties->id,
2246 $this->editoroptions,
2247 $editor['text'],
2248 $this->editoroptions['forcehttps']);
2249 $DB->set_field('event', 'description', $this->properties->description, array('id'=>$this->properties->id));
2252 // Log the event entry.
2253 $eventargs['objectid'] = $this->properties->id;
2254 $eventargs['context'] = $this->properties->context;
2255 $event = \core\event\calendar_event_created::create($eventargs);
2256 $event->trigger();
2258 $repeatedids = array();
2260 if (!empty($this->properties->repeat)) {
2261 $this->properties->repeatid = $this->properties->id;
2262 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id'=>$this->properties->id));
2264 $eventcopy = clone($this->properties);
2265 unset($eventcopy->id);
2267 for($i = 1; $i < $eventcopy->repeats; $i++) {
2269 $eventcopy->timestart = ($eventcopy->timestart+WEEKSECS) + dst_offset_on($eventcopy->timestart) - dst_offset_on($eventcopy->timestart+WEEKSECS);
2271 // Get the event id for the log record.
2272 $eventcopyid = $DB->insert_record('event', $eventcopy);
2274 // If the context has been set delete all associated files
2275 if ($usingeditor) {
2276 $fs = get_file_storage();
2277 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
2278 foreach ($files as $file) {
2279 $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
2283 $repeatedids[] = $eventcopyid;
2285 // Trigger an event.
2286 $eventargs['objectid'] = $eventcopyid;
2287 $eventargs['other']['timestart'] = $eventcopy->timestart;
2288 $event = \core\event\calendar_event_created::create($eventargs);
2289 $event->trigger();
2293 // Hook for tracking added events
2294 self::calendar_event_hook('add_event', array($this->properties, $repeatedids));
2295 return true;
2296 } else {
2298 if ($checkcapability) {
2299 if(!calendar_edit_event_allowed($this->properties)) {
2300 print_error('nopermissiontoupdatecalendar');
2304 if ($usingeditor) {
2305 if ($this->editorcontext !== null) {
2306 $this->properties->description = file_save_draft_area_files(
2307 $this->properties->description['itemid'],
2308 $this->editorcontext->id,
2309 'calendar',
2310 'event_description',
2311 $this->properties->id,
2312 $this->editoroptions,
2313 $this->properties->description['text'],
2314 $this->editoroptions['forcehttps']);
2315 } else {
2316 $this->properties->format = $this->properties->description['format'];
2317 $this->properties->description = $this->properties->description['text'];
2321 $event = $DB->get_record('event', array('id'=>$this->properties->id));
2323 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
2325 if ($updaterepeated) {
2326 // Update all
2327 if ($this->properties->timestart != $event->timestart) {
2328 $timestartoffset = $this->properties->timestart - $event->timestart;
2329 $sql = "UPDATE {event}
2330 SET name = ?,
2331 description = ?,
2332 timestart = timestart + ?,
2333 timeduration = ?,
2334 timemodified = ?
2335 WHERE repeatid = ?";
2336 $params = array($this->properties->name, $this->properties->description, $timestartoffset, $this->properties->timeduration, time(), $event->repeatid);
2337 } else {
2338 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
2339 $params = array($this->properties->name, $this->properties->description, $this->properties->timeduration, time(), $event->repeatid);
2341 $DB->execute($sql, $params);
2343 // Trigger an update event for each of the calendar event.
2344 $events = $DB->get_records('event', array('repeatid' => $event->repeatid), '', 'id,timestart');
2345 foreach ($events as $event) {
2346 $eventargs['objectid'] = $event->id;
2347 $eventargs['other']['timestart'] = $event->timestart;
2348 $event = \core\event\calendar_event_updated::create($eventargs);
2349 $event->trigger();
2351 } else {
2352 $DB->update_record('event', $this->properties);
2353 $event = calendar_event::load($this->properties->id);
2354 $this->properties = $event->properties();
2356 // Trigger an update event.
2357 $event = \core\event\calendar_event_updated::create($eventargs);
2358 $event->trigger();
2361 // Hook for tracking event updates
2362 self::calendar_event_hook('update_event', array($this->properties, $updaterepeated));
2363 return true;
2368 * Deletes an event and if selected an repeated events in the same series
2370 * This function deletes an event, any associated events if $deleterepeated=true,
2371 * and cleans up any files associated with the events.
2373 * @see delete_event()
2375 * @param bool $deleterepeated delete event repeatedly
2376 * @return bool succession of deleting event
2378 public function delete($deleterepeated=false) {
2379 global $DB;
2381 // If $this->properties->id is not set then something is wrong
2382 if (empty($this->properties->id)) {
2383 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
2384 return false;
2386 $calevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
2387 // Delete the event
2388 $DB->delete_records('event', array('id'=>$this->properties->id));
2390 // Trigger an event for the delete action.
2391 $eventargs = array(
2392 'context' => $this->properties->context,
2393 'objectid' => $this->properties->id,
2394 'other' => array(
2395 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
2396 'timestart' => $this->properties->timestart,
2397 'name' => $this->properties->name
2399 $event = \core\event\calendar_event_deleted::create($eventargs);
2400 $event->add_record_snapshot('event', $calevent);
2401 $event->trigger();
2403 // If we are deleting parent of a repeated event series, promote the next event in the series as parent
2404 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
2405 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC", array($this->properties->id), IGNORE_MULTIPLE);
2406 if (!empty($newparent)) {
2407 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?", array($newparent, $this->properties->id));
2408 // Get all records where the repeatid is the same as the event being removed
2409 $events = $DB->get_records('event', array('repeatid' => $newparent));
2410 // For each of the returned events trigger the event_update hook and an update event.
2411 foreach ($events as $event) {
2412 // Trigger an event for the update.
2413 $eventargs['objectid'] = $event->id;
2414 $eventargs['other']['timestart'] = $event->timestart;
2415 $event = \core\event\calendar_event_updated::create($eventargs);
2416 $event->trigger();
2418 self::calendar_event_hook('update_event', array($event, false));
2423 // If the editor context hasn't already been set then set it now
2424 if ($this->editorcontext === null) {
2425 $this->editorcontext = $this->properties->context;
2428 // If the context has been set delete all associated files
2429 if ($this->editorcontext !== null) {
2430 $fs = get_file_storage();
2431 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
2432 foreach ($files as $file) {
2433 $file->delete();
2437 // Fire the event deleted hook
2438 self::calendar_event_hook('delete_event', array($this->properties->id, $deleterepeated));
2440 // If we need to delete repeated events then we will fetch them all and delete one by one
2441 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2442 // Get all records where the repeatid is the same as the event being removed
2443 $events = $DB->get_records('event', array('repeatid'=>$this->properties->repeatid));
2444 // For each of the returned events populate a calendar_event object and call delete
2445 // make sure the arg passed is false as we are already deleting all repeats
2446 foreach ($events as $event) {
2447 $event = new calendar_event($event);
2448 $event->delete(false);
2452 return true;
2456 * Fetch all event properties
2458 * This function returns all of the events properties as an object and optionally
2459 * can prepare an editor for the description field at the same time. This is
2460 * designed to work when the properties are going to be used to set the default
2461 * values of a moodle forms form.
2463 * @param bool $prepareeditor If set to true a editor is prepared for use with
2464 * the mforms editor element. (for description)
2465 * @return stdClass Object containing event properties
2467 public function properties($prepareeditor=false) {
2468 global $USER, $CFG, $DB;
2470 // First take a copy of the properties. We don't want to actually change the
2471 // properties or we'd forever be converting back and forwards between an
2472 // editor formatted description and not
2473 $properties = clone($this->properties);
2474 // Clean the description here
2475 $properties->description = clean_text($properties->description, $properties->format);
2477 // If set to true we need to prepare the properties for use with an editor
2478 // and prepare the file area
2479 if ($prepareeditor) {
2481 // We may or may not have a property id. If we do then we need to work
2482 // out the context so we can copy the existing files to the draft area
2483 if (!empty($properties->id)) {
2485 if ($properties->eventtype === 'site') {
2486 // Site context
2487 $this->editorcontext = $this->properties->context;
2488 } else if ($properties->eventtype === 'user') {
2489 // User context
2490 $this->editorcontext = $this->properties->context;
2491 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
2492 // First check the course is valid
2493 $course = $DB->get_record('course', array('id'=>$properties->courseid));
2494 if (!$course) {
2495 print_error('invalidcourse');
2497 // Course context
2498 $this->editorcontext = $this->properties->context;
2499 // We have a course and are within the course context so we had
2500 // better use the courses max bytes value
2501 $this->editoroptions['maxbytes'] = $course->maxbytes;
2502 } else {
2503 // If we get here we have a custom event type as used by some
2504 // modules. In this case the event will have been added by
2505 // code and we won't need the editor
2506 $this->editoroptions['maxbytes'] = 0;
2507 $this->editoroptions['maxfiles'] = 0;
2510 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
2511 $contextid = false;
2512 } else {
2513 // Get the context id that is what we really want
2514 $contextid = $this->editorcontext->id;
2516 } else {
2518 // If we get here then this is a new event in which case we don't need a
2519 // context as there is no existing files to copy to the draft area.
2520 $contextid = null;
2523 // If the contextid === false we don't support files so no preparing
2524 // a draft area
2525 if ($contextid !== false) {
2526 // Just encase it has already been submitted
2527 $draftiddescription = file_get_submitted_draft_itemid('description');
2528 // Prepare the draft area, this copies existing files to the draft area as well
2529 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar', 'event_description', $properties->id, $this->editoroptions, $properties->description);
2530 } else {
2531 $draftiddescription = 0;
2534 // Structure the description field as the editor requires
2535 $properties->description = array('text'=>$properties->description, 'format'=>$properties->format, 'itemid'=>$draftiddescription);
2538 // Finally return the properties
2539 return $properties;
2543 * Toggles the visibility of an event
2545 * @param null|bool $force If it is left null the events visibility is flipped,
2546 * If it is false the event is made hidden, if it is true it
2547 * is made visible.
2548 * @return bool if event is successfully updated, toggle will be visible
2550 public function toggle_visibility($force=null) {
2551 global $CFG, $DB;
2553 // Set visible to the default if it is not already set
2554 if (empty($this->properties->visible)) {
2555 $this->properties->visible = 1;
2558 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
2559 // Make this event visible
2560 $this->properties->visible = 1;
2561 // Fire the hook
2562 self::calendar_event_hook('show_event', array($this->properties));
2563 } else {
2564 // Make this event hidden
2565 $this->properties->visible = 0;
2566 // Fire the hook
2567 self::calendar_event_hook('hide_event', array($this->properties));
2570 // Update the database to reflect this change
2571 return $DB->set_field('event', 'visible', $this->properties->visible, array('id'=>$this->properties->id));
2575 * Attempts to call the hook for the specified action should a calendar type
2576 * by set $CFG->calendar, and the appopriate function defined
2578 * @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
2579 * @param array $args The args to pass to the hook, usually the event is the first element
2580 * @return bool attempts to call event hook
2582 public static function calendar_event_hook($action, array $args) {
2583 global $CFG;
2584 static $extcalendarinc;
2585 if ($extcalendarinc === null) {
2586 if (!empty($CFG->calendar)) {
2587 if (is_readable($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
2588 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
2589 $extcalendarinc = true;
2590 } else {
2591 debugging("Calendar lib file missing or not readable at /calendar/{$CFG->calendar}/lib.php.",
2592 DEBUG_DEVELOPER);
2593 $extcalendarinc = false;
2595 } else {
2596 $extcalendarinc = false;
2599 if($extcalendarinc === false) {
2600 return false;
2602 $hook = $CFG->calendar .'_'.$action;
2603 if (function_exists($hook)) {
2604 call_user_func_array($hook, $args);
2605 return true;
2607 return false;
2611 * Returns a calendar_event object when provided with an event id
2613 * This function makes use of MUST_EXIST, if the event id passed in is invalid
2614 * it will result in an exception being thrown
2616 * @param int|object $param event object or event id
2617 * @return calendar_event|false status for loading calendar_event
2619 public static function load($param) {
2620 global $DB;
2621 if (is_object($param)) {
2622 $event = new calendar_event($param);
2623 } else {
2624 $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST);
2625 $event = new calendar_event($event);
2627 return $event;
2631 * Creates a new event and returns a calendar_event object
2633 * @param stdClass|array $properties An object containing event properties
2634 * @param bool $checkcapability Check caps or not
2635 * @throws coding_exception
2637 * @return calendar_event|bool The event object or false if it failed
2639 public static function create($properties, $checkcapability = true) {
2640 if (is_array($properties)) {
2641 $properties = (object)$properties;
2643 if (!is_object($properties)) {
2644 throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2646 $event = new calendar_event($properties);
2647 if ($event->update($properties, $checkcapability)) {
2648 return $event;
2649 } else {
2650 return false;
2656 * Calendar information class
2658 * This class is used simply to organise the information pertaining to a calendar
2659 * and is used primarily to make information easily available.
2661 * @package core_calendar
2662 * @category calendar
2663 * @copyright 2010 Sam Hemelryk
2664 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2666 class calendar_information {
2669 * @var int The timestamp
2671 * Rather than setting the day, month and year we will set a timestamp which will be able
2672 * to be used by multiple calendars.
2674 public $time;
2676 /** @var int A course id */
2677 public $courseid = null;
2679 /** @var array An array of courses */
2680 public $courses = array();
2682 /** @var array An array of groups */
2683 public $groups = array();
2685 /** @var array An array of users */
2686 public $users = array();
2689 * Creates a new instance
2691 * @param int $day the number of the day
2692 * @param int $month the number of the month
2693 * @param int $year the number of the year
2694 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
2695 * and $calyear to support multiple calendars
2697 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
2698 // If a day, month and year were passed then convert it to a timestamp. If these were passed
2699 // then we can assume the day, month and year are passed as Gregorian, as no where in core
2700 // should we be passing these values rather than the time. This is done for BC.
2701 if (!empty($day) || !empty($month) || !empty($year)) {
2702 $date = usergetdate(time());
2703 if (empty($day)) {
2704 $day = $date['mday'];
2706 if (empty($month)) {
2707 $month = $date['mon'];
2709 if (empty($year)) {
2710 $year = $date['year'];
2712 if (checkdate($month, $day, $year)) {
2713 $this->time = make_timestamp($year, $month, $day);
2714 } else {
2715 $this->time = time();
2717 } else if (!empty($time)) {
2718 $this->time = $time;
2719 } else {
2720 $this->time = time();
2725 * Initialize calendar information
2727 * @param stdClass $course object
2728 * @param array $coursestoload An array of courses [$course->id => $course]
2729 * @param bool $ignorefilters options to use filter
2731 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
2732 $this->courseid = $course->id;
2733 $this->course = $course;
2734 list($courses, $group, $user) = calendar_set_filters($coursestoload, $ignorefilters);
2735 $this->courses = $courses;
2736 $this->groups = $group;
2737 $this->users = $user;
2741 * Ensures the date for the calendar is correct and either sets it to now
2742 * or throws a moodle_exception if not
2744 * @param bool $defaultonow use current time
2745 * @throws moodle_exception
2746 * @return bool validation of checkdate
2748 public function checkdate($defaultonow = true) {
2749 if (!checkdate($this->month, $this->day, $this->year)) {
2750 if ($defaultonow) {
2751 $now = usergetdate(time());
2752 $this->day = intval($now['mday']);
2753 $this->month = intval($now['mon']);
2754 $this->year = intval($now['year']);
2755 return true;
2756 } else {
2757 throw new moodle_exception('invaliddate');
2760 return true;
2764 * Gets todays timestamp for the calendar
2766 * @return int today timestamp
2768 public function timestamp_today() {
2769 return $this->time;
2772 * Gets tomorrows timestamp for the calendar
2774 * @return int tomorrow timestamp
2776 public function timestamp_tomorrow() {
2777 return $this->time + DAYSECS;
2780 * Adds the pretend blocks for the calendar
2782 * @param core_calendar_renderer $renderer
2783 * @param bool $showfilters display filters, false is set as default
2784 * @param string|null $view preference view options (eg: day, month, upcoming)
2786 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
2787 if ($showfilters) {
2788 $filters = new block_contents();
2789 $filters->content = $renderer->fake_block_filters($this->courseid, 0, 0, 0, $view, $this->courses);
2790 $filters->footer = '';
2791 $filters->title = get_string('eventskey', 'calendar');
2792 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
2794 $block = new block_contents;
2795 $block->content = $renderer->fake_block_threemonths($this);
2796 $block->footer = '';
2797 $block->title = get_string('monthlyview', 'calendar');
2798 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
2803 * Returns option list for the poll interval setting.
2805 * @return array An array of poll interval options. Interval => description.
2807 function calendar_get_pollinterval_choices() {
2808 return array(
2809 '0' => new lang_string('never', 'calendar'),
2810 HOURSECS => new lang_string('hourly', 'calendar'),
2811 DAYSECS => new lang_string('daily', 'calendar'),
2812 WEEKSECS => new lang_string('weekly', 'calendar'),
2813 '2628000' => new lang_string('monthly', 'calendar'),
2814 YEARSECS => new lang_string('annually', 'calendar')
2819 * Returns option list of available options for the calendar event type, given the current user and course.
2821 * @param int $courseid The id of the course
2822 * @return array An array containing the event types the user can create.
2824 function calendar_get_eventtype_choices($courseid) {
2825 $choices = array();
2826 $allowed = new stdClass;
2827 calendar_get_allowed_types($allowed, $courseid);
2829 if ($allowed->user) {
2830 $choices['user'] = get_string('userevents', 'calendar');
2832 if ($allowed->site) {
2833 $choices['site'] = get_string('siteevents', 'calendar');
2835 if (!empty($allowed->courses)) {
2836 $choices['course'] = get_string('courseevents', 'calendar');
2838 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2839 $choices['group'] = get_string('group');
2842 return array($choices, $allowed->groups);
2846 * Add an iCalendar subscription to the database.
2848 * @param stdClass $sub The subscription object (e.g. from the form)
2849 * @return int The insert ID, if any.
2851 function calendar_add_subscription($sub) {
2852 global $DB, $USER, $SITE;
2854 if ($sub->eventtype === 'site') {
2855 $sub->courseid = $SITE->id;
2856 } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
2857 $sub->courseid = $sub->course;
2858 } else {
2859 // User events.
2860 $sub->courseid = 0;
2862 $sub->userid = $USER->id;
2864 // File subscriptions never update.
2865 if (empty($sub->url)) {
2866 $sub->pollinterval = 0;
2869 if (!empty($sub->name)) {
2870 if (empty($sub->id)) {
2871 $id = $DB->insert_record('event_subscriptions', $sub);
2872 // we cannot cache the data here because $sub is not complete.
2873 return $id;
2874 } else {
2875 // Why are we doing an update here?
2876 calendar_update_subscription($sub);
2877 return $sub->id;
2879 } else {
2880 print_error('errorbadsubscription', 'importcalendar');
2885 * Add an iCalendar event to the Moodle calendar.
2887 * @param stdClass $event The RFC-2445 iCalendar event
2888 * @param int $courseid The course ID
2889 * @param int $subscriptionid The iCalendar subscription ID
2890 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2891 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2893 function calendar_add_icalendar_event($event, $courseid, $subscriptionid) {
2894 global $DB;
2896 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2897 if (empty($event->properties['SUMMARY'])) {
2898 return 0;
2901 $name = $event->properties['SUMMARY'][0]->value;
2902 $name = str_replace('\n', '<br />', $name);
2903 $name = str_replace('\\', '', $name);
2904 $name = preg_replace('/\s+/', ' ', $name);
2906 $eventrecord = new stdClass;
2907 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
2909 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2910 $description = '';
2911 } else {
2912 $description = $event->properties['DESCRIPTION'][0]->value;
2913 $description = str_replace('\n', '<br />', $description);
2914 $description = str_replace('\\', '', $description);
2915 $description = preg_replace('/\s+/', ' ', $description);
2917 $eventrecord->description = clean_param($description, PARAM_NOTAGS);
2919 // Probably a repeating event with RRULE etc. TODO: skip for now.
2920 if (empty($event->properties['DTSTART'][0]->value)) {
2921 return 0;
2924 $defaulttz = date_default_timezone_get();
2925 $tz = isset($event->properties['DTSTART'][0]->parameters['TZID']) ? $event->properties['DTSTART'][0]->parameters['TZID'] :
2926 'UTC';
2927 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value . ' ' . $tz);
2928 if (empty($event->properties['DTEND'])) {
2929 $eventrecord->timeduration = 3600; // one hour if no end time specified
2930 } else {
2931 $endtz = isset($event->properties['DTEND'][0]->parameters['TZID']) ? $event->properties['DTEND'][0]->parameters['TZID'] :
2932 'UTC';
2933 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value . ' ' . $endtz) - $eventrecord->timestart;
2935 $eventrecord->uuid = $event->properties['UID'][0]->value;
2936 $eventrecord->timemodified = time();
2938 // Add the iCal subscription details if required.
2939 // We should never do anything with an event without a subscription reference.
2940 $sub = calendar_get_subscription($subscriptionid);
2941 $eventrecord->subscriptionid = $subscriptionid;
2942 $eventrecord->userid = $sub->userid;
2943 $eventrecord->groupid = $sub->groupid;
2944 $eventrecord->courseid = $sub->courseid;
2945 $eventrecord->eventtype = $sub->eventtype;
2947 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid))) {
2948 $eventrecord->id = $updaterecord->id;
2949 $return = CALENDAR_IMPORT_EVENT_UPDATED; // Update.
2950 } else {
2951 $return = CALENDAR_IMPORT_EVENT_INSERTED; // Insert.
2953 if ($createdevent = calendar_event::create($eventrecord, false)) {
2954 if (!empty($event->properties['RRULE'])) {
2955 // Repeating events.
2956 date_default_timezone_set($tz); // Change time zone to parse all events.
2957 $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
2958 $rrule->parse_rrule();
2959 $rrule->create_events($createdevent);
2960 date_default_timezone_set($defaulttz); // Change time zone back to what it was.
2962 return $return;
2963 } else {
2964 return 0;
2969 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2971 * @param int $subscriptionid The ID of the subscription we are acting upon.
2972 * @param int $pollinterval The poll interval to use.
2973 * @param int $action The action to be performed. One of update or remove.
2974 * @throws dml_exception if invalid subscriptionid is provided
2975 * @return string A log of the import progress, including errors
2977 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2979 // Fetch the subscription from the database making sure it exists.
2980 $sub = calendar_get_subscription($subscriptionid);
2982 // Update or remove the subscription, based on action.
2983 switch ($action) {
2984 case CALENDAR_SUBSCRIPTION_UPDATE:
2985 // Skip updating file subscriptions.
2986 if (empty($sub->url)) {
2987 break;
2989 $sub->pollinterval = $pollinterval;
2990 calendar_update_subscription($sub);
2992 // Update the events.
2993 return "<p>".get_string('subscriptionupdated', 'calendar', $sub->name)."</p>" . calendar_update_subscription_events($subscriptionid);
2995 case CALENDAR_SUBSCRIPTION_REMOVE:
2996 calendar_delete_subscription($subscriptionid);
2997 return get_string('subscriptionremoved', 'calendar', $sub->name);
2998 break;
3000 default:
3001 break;
3003 return '';
3007 * Delete subscription and all related events.
3009 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
3011 function calendar_delete_subscription($subscription) {
3012 global $DB;
3014 if (is_object($subscription)) {
3015 $subscription = $subscription->id;
3017 // Delete subscription and related events.
3018 $DB->delete_records('event', array('subscriptionid' => $subscription));
3019 $DB->delete_records('event_subscriptions', array('id' => $subscription));
3020 cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription));
3023 * From a URL, fetch the calendar and return an iCalendar object.
3025 * @param string $url The iCalendar URL
3026 * @return stdClass The iCalendar object
3028 function calendar_get_icalendar($url) {
3029 global $CFG;
3031 require_once($CFG->libdir.'/filelib.php');
3033 $curl = new curl();
3034 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
3035 $calendar = $curl->get($url);
3036 // Http code validation should actually be the job of curl class.
3037 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
3038 throw new moodle_exception('errorinvalidicalurl', 'calendar');
3041 $ical = new iCalendar();
3042 $ical->unserialize($calendar);
3043 return $ical;
3047 * Import events from an iCalendar object into a course calendar.
3049 * @param stdClass $ical The iCalendar object.
3050 * @param int $courseid The course ID for the calendar.
3051 * @param int $subscriptionid The subscription ID.
3052 * @return string A log of the import progress, including errors.
3054 function calendar_import_icalendar_events($ical, $courseid, $subscriptionid = null) {
3055 global $DB;
3056 $return = '';
3057 $eventcount = 0;
3058 $updatecount = 0;
3060 // Large calendars take a while...
3061 core_php_time_limit::raise(300);
3063 // Mark all events in a subscription with a zero timestamp.
3064 if (!empty($subscriptionid)) {
3065 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
3066 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3068 foreach ($ical->components['VEVENT'] as $event) {
3069 $res = calendar_add_icalendar_event($event, $courseid, $subscriptionid);
3070 switch ($res) {
3071 case CALENDAR_IMPORT_EVENT_UPDATED:
3072 $updatecount++;
3073 break;
3074 case CALENDAR_IMPORT_EVENT_INSERTED:
3075 $eventcount++;
3076 break;
3077 case 0:
3078 $return .= '<p>'.get_string('erroraddingevent', 'calendar').': '.(empty($event->properties['SUMMARY'])?'('.get_string('notitle', 'calendar').')':$event->properties['SUMMARY'][0]->value)." </p>\n";
3079 break;
3082 $return .= "<p> ".get_string('eventsimported', 'calendar', $eventcount)."</p>";
3083 $return .= "<p> ".get_string('eventsupdated', 'calendar', $updatecount)."</p>";
3085 // Delete remaining zero-marked events since they're not in remote calendar.
3086 if (!empty($subscriptionid)) {
3087 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3088 if (!empty($deletecount)) {
3089 $sql = "DELETE FROM {event} WHERE timemodified = :time AND subscriptionid = :id";
3090 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3091 $return .= "<p> ".get_string('eventsdeleted', 'calendar').": {$deletecount} </p>\n";
3095 return $return;
3099 * Fetch a calendar subscription and update the events in the calendar.
3101 * @param int $subscriptionid The course ID for the calendar.
3102 * @return string A log of the import progress, including errors.
3104 function calendar_update_subscription_events($subscriptionid) {
3105 global $DB;
3107 $sub = calendar_get_subscription($subscriptionid);
3108 // Don't update a file subscription. TODO: Update from a new uploaded file.
3109 if (empty($sub->url)) {
3110 return 'File subscription not updated.';
3112 $ical = calendar_get_icalendar($sub->url);
3113 $return = calendar_import_icalendar_events($ical, $sub->courseid, $subscriptionid);
3114 $sub->lastupdated = time();
3115 calendar_update_subscription($sub);
3116 return $return;
3120 * Update a calendar subscription. Also updates the associated cache.
3122 * @param stdClass|array $subscription Subscription record.
3123 * @throws coding_exception If something goes wrong
3124 * @since Moodle 2.5
3126 function calendar_update_subscription($subscription) {
3127 global $DB;
3129 if (is_array($subscription)) {
3130 $subscription = (object)$subscription;
3132 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
3133 throw new coding_exception('Cannot update a subscription without a valid id');
3136 $DB->update_record('event_subscriptions', $subscription);
3137 // Update cache.
3138 $cache = cache::make('core', 'calendar_subscriptions');
3139 $cache->set($subscription->id, $subscription);
3143 * Checks to see if the user can edit a given subscription feed.
3145 * @param mixed $subscriptionorid Subscription object or id
3146 * @return bool true if current user can edit the subscription else false
3148 function calendar_can_edit_subscription($subscriptionorid) {
3149 global $DB;
3151 if (is_array($subscriptionorid)) {
3152 $subscription = (object)$subscriptionorid;
3153 } else if (is_object($subscriptionorid)) {
3154 $subscription = $subscriptionorid;
3155 } else {
3156 $subscription = calendar_get_subscription($subscriptionorid);
3158 $allowed = new stdClass;
3159 $courseid = $subscription->courseid;
3160 $groupid = $subscription->groupid;
3161 calendar_get_allowed_types($allowed, $courseid);
3162 switch ($subscription->eventtype) {
3163 case 'user':
3164 return $allowed->user;
3165 case 'course':
3166 if (isset($allowed->courses[$courseid])) {
3167 return $allowed->courses[$courseid];
3168 } else {
3169 return false;
3171 case 'site':
3172 return $allowed->site;
3173 case 'group':
3174 if (isset($allowed->groups[$groupid])) {
3175 return $allowed->groups[$groupid];
3176 } else {
3177 return false;
3179 default:
3180 return false;
3185 * Update calendar subscriptions.
3187 * @return bool
3189 function calendar_cron() {
3190 global $CFG, $DB;
3192 // In order to execute this we need bennu.
3193 require_once($CFG->libdir.'/bennu/bennu.inc.php');
3195 mtrace('Updating calendar subscriptions:');
3196 cron_trace_time_and_memory();
3198 $time = time();
3199 $subscriptions = $DB->get_records_sql('SELECT * FROM {event_subscriptions} WHERE pollinterval > 0 AND lastupdated + pollinterval < ?', array($time));
3200 foreach ($subscriptions as $sub) {
3201 mtrace("Updating calendar subscription {$sub->name} in course {$sub->courseid}");
3202 try {
3203 $log = calendar_update_subscription_events($sub->id);
3204 } catch (moodle_exception $ex) {
3207 mtrace(trim(strip_tags($log)));
3210 mtrace('Finished updating calendar subscriptions.');
3212 return true;