MDL-47242 theme_bootstrapbase: Fixed whitespace (take2)
[moodle.git] / calendar / lib.php
blob2b30733bf8be2f712f211e324254882e4a530d0c
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 (!groups_course_module_visible($cm)) {
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 (!coursemodule_visible_for_user($cm)) {
575 continue;
578 if ($event->modulename == 'assignment'){
579 // create calendar_event to test edit_event capability
580 // this new event will also prevent double creation of calendar_event object
581 $checkevent = new calendar_event($event);
582 // TODO: rewrite this hack somehow
583 if (!calendar_edit_event_allowed($checkevent)){ // cannot manage entries, eg. student
584 if (!$assignment = $DB->get_record('assignment', array('id'=>$event->instance))) {
585 // print_error("invalidid", 'assignment');
586 continue;
588 // assign assignment to assignment object to use hidden_is_hidden method
589 require_once($CFG->dirroot.'/mod/assignment/lib.php');
591 if (!file_exists($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php')) {
592 continue;
594 require_once ($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
596 $assignmentclass = 'assignment_'.$assignment->assignmenttype;
597 $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm);
599 if ($assignmentinstance->description_is_hidden()){//force not to show description before availability
600 $event->description = get_string('notavailableyet', 'assignment');
606 if ($processed >= $display->maxevents) {
607 break;
610 $event->time = calendar_format_event_time($event, $now, $hrefparams);
611 $output[] = $event;
612 ++$processed;
615 return $output;
620 * Get a HTML link to a course.
622 * @param int $courseid the course id
623 * @return string a link to the course (as HTML); empty if the course id is invalid
625 function calendar_get_courselink($courseid) {
627 if (!$courseid) {
628 return '';
631 calendar_get_course_cached($coursecache, $courseid);
632 $context = context_course::instance($courseid);
633 $fullname = format_string($coursecache[$courseid]->fullname, true, array('context' => $context));
634 $url = new moodle_url('/course/view.php', array('id' => $courseid));
635 $link = html_writer::link($url, $fullname);
637 return $link;
642 * Add calendar event metadata
644 * @param stdClass $event event info
645 * @return stdClass $event metadata
647 function calendar_add_event_metadata($event) {
648 global $CFG, $OUTPUT;
650 //Support multilang in event->name
651 $event->name = format_string($event->name,true);
653 if(!empty($event->modulename)) { // Activity event
654 // The module name is set. I will assume that it has to be displayed, and
655 // also that it is an automatically-generated event. And of course that the
656 // fields for get_coursemodule_from_instance are set correctly.
657 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
659 if ($module === false) {
660 return;
663 $modulename = get_string('modulename', $event->modulename);
664 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
665 // will be used as alt text if the event icon
666 $eventtype = get_string($event->eventtype, $event->modulename);
667 } else {
668 $eventtype = '';
670 $icon = $OUTPUT->pix_url('icon', $event->modulename) . '';
672 $event->icon = '<img src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" class="icon" />';
673 $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
674 $event->courselink = calendar_get_courselink($module->course);
675 $event->cmid = $module->id;
677 } else if($event->courseid == SITEID) { // Site event
678 $event->icon = '<img src="'.$OUTPUT->pix_url('i/siteevent') . '" alt="'.get_string('globalevent', 'calendar').'" class="icon" />';
679 $event->cssclass = 'calendar_event_global';
680 } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
681 $event->icon = '<img src="'.$OUTPUT->pix_url('i/courseevent') . '" alt="'.get_string('courseevent', 'calendar').'" class="icon" />';
682 $event->courselink = calendar_get_courselink($event->courseid);
683 $event->cssclass = 'calendar_event_course';
684 } else if ($event->groupid) { // Group event
685 $event->icon = '<img src="'.$OUTPUT->pix_url('i/groupevent') . '" alt="'.get_string('groupevent', 'calendar').'" class="icon" />';
686 $event->courselink = calendar_get_courselink($event->courseid);
687 $event->cssclass = 'calendar_event_group';
688 } else if($event->userid) { // User event
689 $event->icon = '<img src="'.$OUTPUT->pix_url('i/userevent') . '" alt="'.get_string('userevent', 'calendar').'" class="icon" />';
690 $event->cssclass = 'calendar_event_user';
692 return $event;
696 * Get calendar events
698 * @param int $tstart Start time of time range for events
699 * @param int $tend End time of time range for events
700 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
701 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
702 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
703 * @param boolean $withduration whether only events starting within time range selected
704 * or events in progress/already started selected as well
705 * @param boolean $ignorehidden whether to select only visible events or all events
706 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
708 function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
709 global $DB;
711 $whereclause = '';
712 // Quick test
713 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
714 return array();
717 if(is_array($users) && !empty($users)) {
718 // Events from a number of users
719 if(!empty($whereclause)) $whereclause .= ' OR';
720 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
721 } else if(is_numeric($users)) {
722 // Events from one user
723 if(!empty($whereclause)) $whereclause .= ' OR';
724 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
725 } else if($users === true) {
726 // Events from ALL users
727 if(!empty($whereclause)) $whereclause .= ' OR';
728 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
729 } else if($users === false) {
730 // No user at all, do nothing
733 if(is_array($groups) && !empty($groups)) {
734 // Events from a number of groups
735 if(!empty($whereclause)) $whereclause .= ' OR';
736 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
737 } else if(is_numeric($groups)) {
738 // Events from one group
739 if(!empty($whereclause)) $whereclause .= ' OR ';
740 $whereclause .= ' groupid = '.$groups;
741 } else if($groups === true) {
742 // Events from ALL groups
743 if(!empty($whereclause)) $whereclause .= ' OR ';
744 $whereclause .= ' groupid != 0';
746 // boolean false (no groups at all): we don't need to do anything
748 if(is_array($courses) && !empty($courses)) {
749 if(!empty($whereclause)) {
750 $whereclause .= ' OR';
752 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
753 } else if(is_numeric($courses)) {
754 // One course
755 if(!empty($whereclause)) $whereclause .= ' OR';
756 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
757 } else if ($courses === true) {
758 // Events from ALL courses
759 if(!empty($whereclause)) $whereclause .= ' OR';
760 $whereclause .= ' (groupid = 0 AND courseid != 0)';
763 // Security check: if, by now, we have NOTHING in $whereclause, then it means
764 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
765 // events no matter what. Allowing the code to proceed might return a completely
766 // valid query with only time constraints, thus selecting ALL events in that time frame!
767 if(empty($whereclause)) {
768 return array();
771 if($withduration) {
772 $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
774 else {
775 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
777 if(!empty($whereclause)) {
778 // We have additional constraints
779 $whereclause = $timeclause.' AND ('.$whereclause.')';
781 else {
782 // Just basic time filtering
783 $whereclause = $timeclause;
786 if ($ignorehidden) {
787 $whereclause .= ' AND visible = 1';
790 $events = $DB->get_records_select('event', $whereclause, null, 'timestart');
791 if ($events === false) {
792 $events = array();
794 return $events;
797 /** Get calendar events by id
799 * @since Moodle 2.5
800 * @param array $eventids list of event ids
801 * @return array Array of event entries, empty array if nothing found
804 function calendar_get_events_by_id($eventids) {
805 global $DB;
807 if (!is_array($eventids) || empty($eventids)) {
808 return array();
810 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
811 $wheresql = "id $wheresql";
813 return $DB->get_records_select('event', $wheresql, $params);
817 * Get control options for Calendar
819 * @param string $type of calendar
820 * @param array $data calendar information
821 * @return string $content return available control for the calender in html
823 function calendar_top_controls($type, $data) {
824 global $PAGE, $OUTPUT;
826 // Get the calendar type we are using.
827 $calendartype = \core_calendar\type_factory::get_calendar_instance();
829 $content = '';
831 // Ensure course id passed if relevant.
832 $courseid = '';
833 if (!empty($data['id'])) {
834 $courseid = '&amp;course='.$data['id'];
837 // If we are passing a month and year then we need to convert this to a timestamp to
838 // support multiple calendars. No where in core should these be passed, this logic
839 // here is for third party plugins that may use this function.
840 if (!empty($data['m']) && !empty($date['y'])) {
841 if (!isset($data['d'])) {
842 $data['d'] = 1;
844 if (!checkdate($data['m'], $data['d'], $data['y'])) {
845 $time = time();
846 } else {
847 $time = make_timestamp($data['y'], $data['m'], $data['d']);
849 } else if (!empty($data['time'])) {
850 $time = $data['time'];
851 } else {
852 $time = time();
855 // Get the date for the calendar type.
856 $date = $calendartype->timestamp_to_date_array($time);
858 $urlbase = $PAGE->url;
860 // We need to get the previous and next months in certain cases.
861 if ($type == 'frontpage' || $type == 'course' || $type == 'month') {
862 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
863 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
864 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
865 $prevmonthtime['hour'], $prevmonthtime['minute']);
867 $nextmonth = calendar_add_month($date['mon'], $date['year']);
868 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
869 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
870 $nextmonthtime['hour'], $nextmonthtime['minute']);
873 switch ($type) {
874 case 'frontpage':
875 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false, true, $prevmonthtime);
876 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true, $nextmonthtime);
877 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view' => 'month')), false, false, false, $time);
879 if (!empty($data['id'])) {
880 $calendarlink->param('course', $data['id']);
883 if (right_to_left()) {
884 $left = $nextlink;
885 $right = $prevlink;
886 } else {
887 $left = $prevlink;
888 $right = $nextlink;
891 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
892 $content .= $left.'<span class="hide"> | </span>';
893 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
894 $content .= '<span class="hide"> | </span>'. $right;
895 $content .= "<span class=\"clearer\"><!-- --></span>\n";
896 $content .= html_writer::end_tag('div');
898 break;
899 case 'course':
900 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false, true, $prevmonthtime);
901 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true, $nextmonthtime);
902 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view' => 'month')), false, false, false, $time);
904 if (!empty($data['id'])) {
905 $calendarlink->param('course', $data['id']);
908 if (right_to_left()) {
909 $left = $nextlink;
910 $right = $prevlink;
911 } else {
912 $left = $prevlink;
913 $right = $nextlink;
916 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
917 $content .= $left.'<span class="hide"> | </span>';
918 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
919 $content .= '<span class="hide"> | </span>'. $right;
920 $content .= "<span class=\"clearer\"><!-- --></span>";
921 $content .= html_writer::end_tag('div');
922 break;
923 case 'upcoming':
924 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view' => 'upcoming')), false, false, false, $time);
925 if (!empty($data['id'])) {
926 $calendarlink->param('course', $data['id']);
928 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
929 $content .= html_writer::tag('div', $calendarlink, array('class'=>'centered'));
930 break;
931 case 'display':
932 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view' => 'month')), false, false, false, $time);
933 if (!empty($data['id'])) {
934 $calendarlink->param('course', $data['id']);
936 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
937 $content .= html_writer::tag('h3', $calendarlink);
938 break;
939 case 'month':
940 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', false, false, false, false, $prevmonthtime);
941 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', false, false, false, false, $nextmonthtime);
943 if (right_to_left()) {
944 $left = $nextlink;
945 $right = $prevlink;
946 } else {
947 $left = $prevlink;
948 $right = $nextlink;
951 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
952 $content .= $left . '<span class="hide"> | </span>';
953 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
954 $content .= '<span class="hide"> | </span>' . $right;
955 $content .= '<span class="clearer"><!-- --></span>';
956 $content .= html_writer::end_tag('div')."\n";
957 break;
958 case 'day':
959 $days = calendar_get_days();
961 $prevtimestamp = $time - DAYSECS;
962 $nexttimestamp = $time + DAYSECS;
964 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
965 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
967 $prevname = $days[$prevdate['wday']]['fullname'];
968 $nextname = $days[$nextdate['wday']]['fullname'];
969 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&amp;', false, false, false, false, $prevtimestamp);
970 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&amp;', false, false, false, false, $nexttimestamp);
972 if (right_to_left()) {
973 $left = $nextlink;
974 $right = $prevlink;
975 } else {
976 $left = $prevlink;
977 $right = $nextlink;
980 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
981 $content .= $left;
982 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimedaydate')).'</span>';
983 $content .= '<span class="hide"> | </span>'. $right;
984 $content .= "<span class=\"clearer\"><!-- --></span>";
985 $content .= html_writer::end_tag('div')."\n";
987 break;
989 return $content;
993 * Formats a filter control element.
995 * @param moodle_url $url of the filter
996 * @param int $type constant defining the type filter
997 * @return string html content of the element
999 function calendar_filter_controls_element(moodle_url $url, $type) {
1000 global $OUTPUT;
1001 switch ($type) {
1002 case CALENDAR_EVENT_GLOBAL:
1003 $typeforhumans = 'global';
1004 $class = 'calendar_event_global';
1005 break;
1006 case CALENDAR_EVENT_COURSE:
1007 $typeforhumans = 'course';
1008 $class = 'calendar_event_course';
1009 break;
1010 case CALENDAR_EVENT_GROUP:
1011 $typeforhumans = 'groups';
1012 $class = 'calendar_event_group';
1013 break;
1014 case CALENDAR_EVENT_USER:
1015 $typeforhumans = 'user';
1016 $class = 'calendar_event_user';
1017 break;
1019 if (calendar_show_event_type($type)) {
1020 $icon = $OUTPUT->pix_icon('t/hide', get_string('hide'));
1021 $str = get_string('hide'.$typeforhumans.'events', 'calendar');
1022 } else {
1023 $icon = $OUTPUT->pix_icon('t/show', get_string('show'));
1024 $str = get_string('show'.$typeforhumans.'events', 'calendar');
1026 $content = html_writer::start_tag('li', array('class' => 'calendar_event'));
1027 $content .= html_writer::start_tag('a', array('href' => $url));
1028 $content .= html_writer::tag('span', $icon, array('class' => $class));
1029 $content .= html_writer::tag('span', $str, array('class' => 'eventname'));
1030 $content .= html_writer::end_tag('a');
1031 $content .= html_writer::end_tag('li');
1032 return $content;
1036 * Get the controls filter for calendar.
1038 * Filter is used to hide calendar info from the display page
1040 * @param moodle_url $returnurl return-url for filter controls
1041 * @return string $content return filter controls in html
1043 function calendar_filter_controls(moodle_url $returnurl) {
1044 global $CFG, $USER, $OUTPUT;
1046 $groupevents = true;
1047 $id = optional_param( 'id',0,PARAM_INT );
1048 $seturl = new moodle_url('/calendar/set.php', array('return' => base64_encode($returnurl->out_as_local_url(false)), 'sesskey'=>sesskey()));
1049 $content = html_writer::start_tag('ul');
1051 $seturl->param('var', 'showglobal');
1052 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GLOBAL);
1054 $seturl->param('var', 'showcourses');
1055 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_COURSE);
1057 if (isloggedin() && !isguestuser()) {
1058 if ($groupevents) {
1059 // This course MIGHT have group events defined, so show the filter
1060 $seturl->param('var', 'showgroups');
1061 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GROUP);
1062 } else {
1063 // This course CANNOT have group events, so lose the filter
1065 $seturl->param('var', 'showuser');
1066 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_USER);
1068 $content .= html_writer::end_tag('ul');
1070 return $content;
1074 * Return the representation day
1076 * @param int $tstamp Timestamp in GMT
1077 * @param int $now current Unix timestamp
1078 * @param bool $usecommonwords
1079 * @return string the formatted date/time
1081 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1083 static $shortformat;
1084 if(empty($shortformat)) {
1085 $shortformat = get_string('strftimedayshort');
1088 if($now === false) {
1089 $now = time();
1092 // To have it in one place, if a change is needed
1093 $formal = userdate($tstamp, $shortformat);
1095 $datestamp = usergetdate($tstamp);
1096 $datenow = usergetdate($now);
1098 if($usecommonwords == false) {
1099 // We don't want words, just a date
1100 return $formal;
1102 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1103 // Today
1104 return get_string('today', 'calendar');
1106 else if(
1107 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1108 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
1110 // Yesterday
1111 return get_string('yesterday', 'calendar');
1113 else if(
1114 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1115 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
1117 // Tomorrow
1118 return get_string('tomorrow', 'calendar');
1120 else {
1121 return $formal;
1126 * return the formatted representation time
1128 * @param int $time the timestamp in UTC, as obtained from the database
1129 * @return string the formatted date/time
1131 function calendar_time_representation($time) {
1132 static $langtimeformat = NULL;
1133 if($langtimeformat === NULL) {
1134 $langtimeformat = get_string('strftimetime');
1136 $timeformat = get_user_preferences('calendar_timeformat');
1137 if(empty($timeformat)){
1138 $timeformat = get_config(NULL,'calendar_site_timeformat');
1140 // The ? is needed because the preference might be present, but empty
1141 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
1145 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1147 * @param string|moodle_url $linkbase
1148 * @param int $d The number of the day.
1149 * @param int $m The number of the month.
1150 * @param int $y The number of the year.
1151 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1152 * $m and $y are kept for backwards compatibility.
1153 * @return moodle_url|null $linkbase
1155 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1156 if (empty($linkbase)) {
1157 return '';
1159 if (!($linkbase instanceof moodle_url)) {
1160 $linkbase = new moodle_url($linkbase);
1163 // If a day, month and year were passed then convert it to a timestamp. If these were passed
1164 // then we can assume the day, month and year are passed as Gregorian, as no where in core
1165 // should we be passing these values rather than the time.
1166 if (!empty($d) && !empty($m) && !empty($y)) {
1167 if (checkdate($m, $d, $y)) {
1168 $time = make_timestamp($y, $m, $d);
1169 } else {
1170 $time = time();
1172 } else if (empty($time)) {
1173 $time = time();
1176 $linkbase->param('time', $time);
1178 return $linkbase;
1182 * Build and return a previous month HTML link, with an arrow.
1184 * @param string $text The text label.
1185 * @param string|moodle_url $linkbase The URL stub.
1186 * @param int $d The number of the date.
1187 * @param int $m The number of the month.
1188 * @param int $y year The number of the year.
1189 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1190 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1191 * $m and $y are kept for backwards compatibility.
1192 * @return string HTML string.
1194 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1195 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y, $time);
1196 if (empty($href)) {
1197 return $text;
1199 return link_arrow_left($text, (string)$href, $accesshide, 'previous');
1203 * Build and return a next month HTML link, with an arrow.
1205 * @param string $text The text label.
1206 * @param string|moodle_url $linkbase The URL stub.
1207 * @param int $d the number of the Day
1208 * @param int $m The number of the month.
1209 * @param int $y The number of the year.
1210 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1211 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1212 * $m and $y are kept for backwards compatibility.
1213 * @return string HTML string.
1215 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1216 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y, $time);
1217 if (empty($href)) {
1218 return $text;
1220 return link_arrow_right($text, (string)$href, $accesshide, 'next');
1224 * Return the name of the weekday
1226 * @param string $englishname
1227 * @return string of the weekeday
1229 function calendar_wday_name($englishname) {
1230 return get_string(strtolower($englishname), 'calendar');
1234 * Return the number of days in month
1236 * @param int $month the number of the month.
1237 * @param int $year the number of the year
1238 * @return int
1240 function calendar_days_in_month($month, $year) {
1241 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1242 return $calendartype->get_num_days_in_month($year, $month);
1246 * Get the upcoming event block
1248 * @param array $events list of events
1249 * @param moodle_url|string $linkhref link to event referer
1250 * @param boolean $showcourselink whether links to courses should be shown
1251 * @return string|null $content html block content
1253 function calendar_get_block_upcoming($events, $linkhref = NULL, $showcourselink = false) {
1254 $content = '';
1255 $lines = count($events);
1256 if (!$lines) {
1257 return $content;
1260 for ($i = 0; $i < $lines; ++$i) {
1261 if (!isset($events[$i]->time)) { // Just for robustness
1262 continue;
1264 $events[$i] = calendar_add_event_metadata($events[$i]);
1265 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span>';
1266 if (!empty($events[$i]->referer)) {
1267 // That's an activity event, so let's provide the hyperlink
1268 $content .= $events[$i]->referer;
1269 } else {
1270 if(!empty($linkhref)) {
1271 $href = calendar_get_link_href(new moodle_url(CALENDAR_URL . $linkhref), 0, 0, 0, $events[$i]->timestart);
1272 $href->set_anchor('event_'.$events[$i]->id);
1273 $content .= html_writer::link($href, $events[$i]->name);
1275 else {
1276 $content .= $events[$i]->name;
1279 $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
1280 if ($showcourselink && !empty($events[$i]->courselink)) {
1281 $content .= html_writer::div($events[$i]->courselink, 'course');
1283 $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
1284 if ($i < $lines - 1) $content .= '<hr />';
1287 return $content;
1291 * Get the next following month
1293 * @param int $month the number of the month.
1294 * @param int $year the number of the year.
1295 * @return array the following month
1297 function calendar_add_month($month, $year) {
1298 // Get the calendar type we are using.
1299 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1300 return $calendartype->get_next_month($year, $month);
1304 * Get the previous month.
1306 * @param int $month the number of the month.
1307 * @param int $year the number of the year.
1308 * @return array previous month
1310 function calendar_sub_month($month, $year) {
1311 // Get the calendar type we are using.
1312 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1313 return $calendartype->get_prev_month($year, $month);
1317 * Get per-day basis events
1319 * @param array $events list of events
1320 * @param int $month the number of the month
1321 * @param int $year the number of the year
1322 * @param array $eventsbyday event on specific day
1323 * @param array $durationbyday duration of the event in days
1324 * @param array $typesbyday event type (eg: global, course, user, or group)
1325 * @param array $courses list of courses
1326 * @return void
1328 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1329 // Get the calendar type we are using.
1330 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1332 $eventsbyday = array();
1333 $typesbyday = array();
1334 $durationbyday = array();
1336 if($events === false) {
1337 return;
1340 foreach ($events as $event) {
1341 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
1342 // Set end date = start date if no duration
1343 if ($event->timeduration) {
1344 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
1345 } else {
1346 $enddate = $startdate;
1349 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
1350 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1351 // Out of bounds
1352 continue;
1355 $eventdaystart = intval($startdate['mday']);
1357 if($startdate['mon'] == $month && $startdate['year'] == $year) {
1358 // Give the event to its day
1359 $eventsbyday[$eventdaystart][] = $event->id;
1361 // Mark the day as having such an event
1362 if($event->courseid == SITEID && $event->groupid == 0) {
1363 $typesbyday[$eventdaystart]['startglobal'] = true;
1364 // Set event class for global event
1365 $events[$event->id]->class = 'calendar_event_global';
1367 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1368 $typesbyday[$eventdaystart]['startcourse'] = true;
1369 // Set event class for course event
1370 $events[$event->id]->class = 'calendar_event_course';
1372 else if($event->groupid) {
1373 $typesbyday[$eventdaystart]['startgroup'] = true;
1374 // Set event class for group event
1375 $events[$event->id]->class = 'calendar_event_group';
1377 else if($event->userid) {
1378 $typesbyday[$eventdaystart]['startuser'] = true;
1379 // Set event class for user event
1380 $events[$event->id]->class = 'calendar_event_user';
1384 if($event->timeduration == 0) {
1385 // Proceed with the next
1386 continue;
1389 // The event starts on $month $year or before. So...
1390 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
1392 // Also, it ends on $month $year or later...
1393 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
1395 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1396 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
1397 $durationbyday[$i][] = $event->id;
1398 if($event->courseid == SITEID && $event->groupid == 0) {
1399 $typesbyday[$i]['durationglobal'] = true;
1401 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1402 $typesbyday[$i]['durationcourse'] = true;
1404 else if($event->groupid) {
1405 $typesbyday[$i]['durationgroup'] = true;
1407 else if($event->userid) {
1408 $typesbyday[$i]['durationuser'] = true;
1413 return;
1417 * Get current module cache
1419 * @param array $coursecache list of course cache
1420 * @param string $modulename name of the module
1421 * @param int $instance module instance number
1422 * @return stdClass|bool $module information
1424 function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1425 $module = get_coursemodule_from_instance($modulename, $instance);
1427 if($module === false) return false;
1428 if(!calendar_get_course_cached($coursecache, $module->course)) {
1429 return false;
1431 return $module;
1435 * Get current course cache
1437 * @param array $coursecache list of course cache
1438 * @param int $courseid id of the course
1439 * @return stdClass $coursecache[$courseid] return the specific course cache
1441 function calendar_get_course_cached(&$coursecache, $courseid) {
1442 if (!isset($coursecache[$courseid])) {
1443 $coursecache[$courseid] = get_course($courseid);
1445 return $coursecache[$courseid];
1449 * Returns the courses to load events for, the
1451 * @param array $courseeventsfrom An array of courses to load calendar events for
1452 * @param bool $ignorefilters specify the use of filters, false is set as default
1453 * @return array An array of courses, groups, and user to load calendar events for based upon filters
1455 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
1456 global $USER, $CFG, $DB;
1458 // For backwards compatability we have to check whether the courses array contains
1459 // just id's in which case we need to load course objects.
1460 $coursestoload = array();
1461 foreach ($courseeventsfrom as $id => $something) {
1462 if (!is_object($something)) {
1463 $coursestoload[] = $id;
1464 unset($courseeventsfrom[$id]);
1467 if (!empty($coursestoload)) {
1468 // TODO remove this in 2.2
1469 debugging('calendar_set_filters now preferes an array of course objects with preloaded contexts', DEBUG_DEVELOPER);
1470 $courseeventsfrom = array_merge($courseeventsfrom, $DB->get_records_list('course', 'id', $coursestoload));
1473 $courses = array();
1474 $user = false;
1475 $group = false;
1477 // capabilities that allow seeing group events from all groups
1478 // TODO: rewrite so that moodle/calendar:manageentries is not necessary here
1479 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
1481 $isloggedin = isloggedin();
1483 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
1484 $courses = array_keys($courseeventsfrom);
1486 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
1487 $courses[] = SITEID;
1489 $courses = array_unique($courses);
1490 sort($courses);
1492 if (!empty($courses) && in_array(SITEID, $courses)) {
1493 // Sort courses for consistent colour highlighting
1494 // Effectively ignoring SITEID as setting as last course id
1495 $key = array_search(SITEID, $courses);
1496 unset($courses[$key]);
1497 $courses[] = SITEID;
1500 if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
1501 $user = $USER->id;
1504 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
1506 if (count($courseeventsfrom)==1) {
1507 $course = reset($courseeventsfrom);
1508 if (has_any_capability($allgroupscaps, context_course::instance($course->id))) {
1509 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
1510 $group = array_keys($coursegroups);
1513 if ($group === false) {
1514 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, context_system::instance())) {
1515 $group = true;
1516 } else if ($isloggedin) {
1517 $groupids = array();
1519 // We already have the courses to examine in $courses
1520 // For each course...
1521 foreach ($courseeventsfrom as $courseid => $course) {
1522 // If the user is an editing teacher in there,
1523 if (!empty($USER->groupmember[$course->id])) {
1524 // We've already cached the users groups for this course so we can just use that
1525 $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
1526 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1527 // If this course has groups, show events from all of those related to the current user
1528 $coursegroups = groups_get_user_groups($course->id, $USER->id);
1529 $groupids = array_merge($groupids, $coursegroups['0']);
1532 if (!empty($groupids)) {
1533 $group = $groupids;
1538 if (empty($courses)) {
1539 $courses = false;
1542 return array($courses, $group, $user);
1546 * Return the capability for editing calendar event
1548 * @param calendar_event $event event object
1549 * @return bool capability to edit event
1551 function calendar_edit_event_allowed($event) {
1552 global $USER, $DB;
1554 // Must be logged in
1555 if (!isloggedin()) {
1556 return false;
1559 // can not be using guest account
1560 if (isguestuser()) {
1561 return false;
1564 // You cannot edit calendar subscription events presently.
1565 if (!empty($event->subscriptionid)) {
1566 return false;
1569 $sitecontext = context_system::instance();
1570 // if user has manageentries at site level, return true
1571 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1572 return true;
1575 // if groupid is set, it's definitely a group event
1576 if (!empty($event->groupid)) {
1577 // Allow users to add/edit group events if:
1578 // 1) They have manageentries (= entries for whole course)
1579 // 2) They have managegroupentries AND are in the group
1580 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1581 return $group && (
1582 has_capability('moodle/calendar:manageentries', $event->context) ||
1583 (has_capability('moodle/calendar:managegroupentries', $event->context)
1584 && groups_is_member($event->groupid)));
1585 } else if (!empty($event->courseid)) {
1586 // if groupid is not set, but course is set,
1587 // it's definiely a course event
1588 return has_capability('moodle/calendar:manageentries', $event->context);
1589 } else if (!empty($event->userid) && $event->userid == $USER->id) {
1590 // if course is not set, but userid id set, it's a user event
1591 return (has_capability('moodle/calendar:manageownentries', $event->context));
1592 } else if (!empty($event->userid)) {
1593 return (has_capability('moodle/calendar:manageentries', $event->context));
1595 return false;
1599 * Returns the default courses to display on the calendar when there isn't a specific
1600 * course to display.
1602 * @return array $courses Array of courses to display
1604 function calendar_get_default_courses() {
1605 global $CFG, $DB;
1607 if (!isloggedin()) {
1608 return array();
1611 $courses = array();
1612 if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', context_system::instance())) {
1613 $select = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1614 $join = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1615 $sql = "SELECT c.* $select
1616 FROM {course} c
1617 $join
1618 WHERE EXISTS (SELECT 1 FROM {event} e WHERE e.courseid = c.id)
1620 $courses = $DB->get_records_sql($sql, array('contextlevel' => CONTEXT_COURSE), 0, 20);
1621 foreach ($courses as $course) {
1622 context_helper::preload_from_record($course);
1624 return $courses;
1627 $courses = enrol_get_my_courses();
1629 return $courses;
1633 * Display calendar preference button
1635 * @param stdClass $course course object
1636 * @return string return preference button in html
1638 function calendar_preferences_button(stdClass $course) {
1639 global $OUTPUT;
1641 // Guests have no preferences
1642 if (!isloggedin() || isguestuser()) {
1643 return '';
1646 return $OUTPUT->single_button(new moodle_url('/calendar/preferences.php', array('course' => $course->id)), get_string("preferences", "calendar"));
1650 * Get event format time
1652 * @param calendar_event $event event object
1653 * @param int $now current time in gmt
1654 * @param array $linkparams list of params for event link
1655 * @param bool $usecommonwords the words as formatted date/time.
1656 * @param int $showtime determine the show time GMT timestamp
1657 * @return string $eventtime link/string for event time
1659 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
1660 $starttime = $event->timestart;
1661 $endtime = $event->timestart + $event->timeduration;
1663 if (empty($linkparams) || !is_array($linkparams)) {
1664 $linkparams = array();
1667 $linkparams['view'] = 'day';
1669 // OK, now to get a meaningful display...
1670 // Check if there is a duration for this event.
1671 if ($event->timeduration) {
1672 // Get the midnight of the day the event will start.
1673 $usermidnightstart = usergetmidnight($starttime);
1674 // Get the midnight of the day the event will end.
1675 $usermidnightend = usergetmidnight($endtime);
1676 // Check if we will still be on the same day.
1677 if ($usermidnightstart == $usermidnightend) {
1678 // Check if we are running all day.
1679 if ($event->timeduration == DAYSECS) {
1680 $time = get_string('allday', 'calendar');
1681 } else { // Specify the time we will be running this from.
1682 $datestart = calendar_time_representation($starttime);
1683 $dateend = calendar_time_representation($endtime);
1684 $time = $datestart . ' <strong>&raquo;</strong> ' . $dateend;
1687 // Set printable representation.
1688 if (!$showtime) {
1689 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1690 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
1691 $eventtime = html_writer::link($url, $day) . ', ' . $time;
1692 } else {
1693 $eventtime = $time;
1695 } else { // It must spans two or more days.
1696 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
1697 if ($showtime == $usermidnightstart) {
1698 $daystart = '';
1700 $timestart = calendar_time_representation($event->timestart);
1701 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
1702 if ($showtime == $usermidnightend) {
1703 $dayend = '';
1705 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1707 // Set printable representation.
1708 if ($now >= $usermidnightstart && $now < ($usermidnightstart + DAYSECS)) {
1709 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
1710 $eventtime = $timestart . ' <strong>&raquo;</strong> ' . html_writer::link($url, $dayend) . $timeend;
1711 } else {
1712 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
1713 $eventtime = html_writer::link($url, $daystart) . $timestart . ' <strong>&raquo;</strong> ';
1715 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
1716 $eventtime .= html_writer::link($url, $dayend) . $timeend;
1719 } else { // There is no time duration.
1720 $time = calendar_time_representation($event->timestart);
1721 // Set printable representation.
1722 if (!$showtime) {
1723 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1724 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
1725 $eventtime = html_writer::link($url, $day) . ', ' . trim($time);
1726 } else {
1727 $eventtime = $time;
1731 // Check if It has expired.
1732 if ($event->timestart + $event->timeduration < $now) {
1733 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
1736 return $eventtime;
1740 * Display month selector options
1742 * @param string $name for the select element
1743 * @param string|array $selected options for select elements
1745 function calendar_print_month_selector($name, $selected) {
1746 $months = array();
1747 for ($i=1; $i<=12; $i++) {
1748 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
1750 echo html_writer::label(get_string('months'), 'menu'. $name, false, array('class' => 'accesshide'));
1751 echo html_writer::select($months, $name, $selected, false);
1755 * Checks to see if the requested type of event should be shown for the given user.
1757 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
1758 * The type to check the display for (default is to display all)
1759 * @param stdClass|int|null $user The user to check for - by default the current user
1760 * @return bool True if the tyep should be displayed false otherwise
1762 function calendar_show_event_type($type, $user = null) {
1763 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1764 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
1765 global $SESSION;
1766 if (!isset($SESSION->calendarshoweventtype)) {
1767 $SESSION->calendarshoweventtype = $default;
1769 return $SESSION->calendarshoweventtype & $type;
1770 } else {
1771 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
1776 * Sets the display of the event type given $display.
1778 * If $display = true the event type will be shown.
1779 * If $display = false the event type will NOT be shown.
1780 * If $display = null the current value will be toggled and saved.
1782 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type object of CALENDAR_EVENT_XXX
1783 * @param bool $display option to display event type
1784 * @param stdClass|int $user moodle user object or id, null means current user
1786 function calendar_set_event_type_display($type, $display = null, $user = null) {
1787 $persist = get_user_preferences('calendar_persistflt', 0, $user);
1788 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1789 if ($persist === 0) {
1790 global $SESSION;
1791 if (!isset($SESSION->calendarshoweventtype)) {
1792 $SESSION->calendarshoweventtype = $default;
1794 $preference = $SESSION->calendarshoweventtype;
1795 } else {
1796 $preference = get_user_preferences('calendar_savedflt', $default, $user);
1798 $current = $preference & $type;
1799 if ($display === null) {
1800 $display = !$current;
1802 if ($display && !$current) {
1803 $preference += $type;
1804 } else if (!$display && $current) {
1805 $preference -= $type;
1807 if ($persist === 0) {
1808 $SESSION->calendarshoweventtype = $preference;
1809 } else {
1810 if ($preference == $default) {
1811 unset_user_preference('calendar_savedflt', $user);
1812 } else {
1813 set_user_preference('calendar_savedflt', $preference, $user);
1819 * Get calendar's allowed types
1821 * @param stdClass $allowed list of allowed edit for event type
1822 * @param stdClass|int $course object of a course or course id
1824 function calendar_get_allowed_types(&$allowed, $course = null) {
1825 global $USER, $CFG, $DB;
1826 $allowed = new stdClass();
1827 $allowed->user = has_capability('moodle/calendar:manageownentries', context_system::instance());
1828 $allowed->groups = false; // This may change just below
1829 $allowed->courses = false; // This may change just below
1830 $allowed->site = has_capability('moodle/calendar:manageentries', context_course::instance(SITEID));
1832 if (!empty($course)) {
1833 if (!is_object($course)) {
1834 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST);
1836 if ($course->id != SITEID) {
1837 $coursecontext = context_course::instance($course->id);
1838 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
1840 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
1841 $allowed->courses = array($course->id => 1);
1843 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1844 if (has_capability('moodle/site:accessallgroups', $coursecontext)) {
1845 $allowed->groups = groups_get_all_groups($course->id);
1846 } else {
1847 $allowed->groups = groups_get_all_groups($course->id, $USER->id);
1850 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
1851 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1852 if (has_capability('moodle/site:accessallgroups', $coursecontext)) {
1853 $allowed->groups = groups_get_all_groups($course->id);
1854 } else {
1855 $allowed->groups = groups_get_all_groups($course->id, $USER->id);
1864 * See if user can add calendar entries at all
1865 * used to print the "New Event" button
1867 * @param stdClass $course object of a course or course id
1868 * @return bool has the capability to add at least one event type
1870 function calendar_user_can_add_event($course) {
1871 if (!isloggedin() || isguestuser()) {
1872 return false;
1874 calendar_get_allowed_types($allowed, $course);
1875 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);
1879 * Check wether the current user is permitted to add events
1881 * @param stdClass $event object of event
1882 * @return bool has the capability to add event
1884 function calendar_add_event_allowed($event) {
1885 global $USER, $DB;
1887 // can not be using guest account
1888 if (!isloggedin() or isguestuser()) {
1889 return false;
1892 $sitecontext = context_system::instance();
1893 // if user has manageentries at site level, always return true
1894 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1895 return true;
1898 switch ($event->eventtype) {
1899 case 'course':
1900 return has_capability('moodle/calendar:manageentries', $event->context);
1902 case 'group':
1903 // Allow users to add/edit group events if:
1904 // 1) They have manageentries (= entries for whole course)
1905 // 2) They have managegroupentries AND are in the group
1906 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1907 return $group && (
1908 has_capability('moodle/calendar:manageentries', $event->context) ||
1909 (has_capability('moodle/calendar:managegroupentries', $event->context)
1910 && groups_is_member($event->groupid)));
1912 case 'user':
1913 if ($event->userid == $USER->id) {
1914 return (has_capability('moodle/calendar:manageownentries', $event->context));
1916 //there is no 'break;' intentionally
1918 case 'site':
1919 return has_capability('moodle/calendar:manageentries', $event->context);
1921 default:
1922 return has_capability('moodle/calendar:manageentries', $event->context);
1927 * Manage calendar events
1929 * This class provides the required functionality in order to manage calendar events.
1930 * It was introduced as part of Moodle 2.0 and was created in order to provide a
1931 * better framework for dealing with calendar events in particular regard to file
1932 * handling through the new file API
1934 * @package core_calendar
1935 * @category calendar
1936 * @copyright 2009 Sam Hemelryk
1937 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1939 * @property int $id The id within the event table
1940 * @property string $name The name of the event
1941 * @property string $description The description of the event
1942 * @property int $format The format of the description FORMAT_?
1943 * @property int $courseid The course the event is associated with (0 if none)
1944 * @property int $groupid The group the event is associated with (0 if none)
1945 * @property int $userid The user the event is associated with (0 if none)
1946 * @property int $repeatid If this is a repeated event this will be set to the
1947 * id of the original
1948 * @property string $modulename If added by a module this will be the module name
1949 * @property int $instance If added by a module this will be the module instance
1950 * @property string $eventtype The event type
1951 * @property int $timestart The start time as a timestamp
1952 * @property int $timeduration The duration of the event in seconds
1953 * @property int $visible 1 if the event is visible
1954 * @property int $uuid ?
1955 * @property int $sequence ?
1956 * @property int $timemodified The time last modified as a timestamp
1958 class calendar_event {
1960 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
1961 protected $properties = null;
1964 * @var string The converted event discription with file paths resolved. This gets populated when someone requests description for the first time */
1965 protected $_description = null;
1967 /** @var array The options to use with this description editor */
1968 protected $editoroptions = array(
1969 'subdirs'=>false,
1970 'forcehttps'=>false,
1971 'maxfiles'=>-1,
1972 'maxbytes'=>null,
1973 'trusttext'=>false);
1975 /** @var object The context to use with the description editor */
1976 protected $editorcontext = null;
1979 * Instantiates a new event and optionally populates its properties with the
1980 * data provided
1982 * @param stdClass $data Optional. An object containing the properties to for
1983 * an event
1985 public function __construct($data=null) {
1986 global $CFG, $USER;
1988 // First convert to object if it is not already (should either be object or assoc array)
1989 if (!is_object($data)) {
1990 $data = (object)$data;
1993 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
1995 $data->eventrepeats = 0;
1997 if (empty($data->id)) {
1998 $data->id = null;
2001 if (!empty($data->subscriptionid)) {
2002 $data->subscription = calendar_get_subscription($data->subscriptionid);
2005 // Default to a user event
2006 if (empty($data->eventtype)) {
2007 $data->eventtype = 'user';
2010 // Default to the current user
2011 if (empty($data->userid)) {
2012 $data->userid = $USER->id;
2015 if (!empty($data->timeduration) && is_array($data->timeduration)) {
2016 $data->timeduration = make_timestamp($data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'], $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
2018 if (!empty($data->description) && is_array($data->description)) {
2019 $data->format = $data->description['format'];
2020 $data->description = $data->description['text'];
2021 } else if (empty($data->description)) {
2022 $data->description = '';
2023 $data->format = editors_get_preferred_format();
2025 // Ensure form is defaulted correctly
2026 if (empty($data->format)) {
2027 $data->format = editors_get_preferred_format();
2030 if (empty($data->context)) {
2031 $data->context = $this->calculate_context($data);
2033 $this->properties = $data;
2037 * Magic property method
2039 * Attempts to call a set_$key method if one exists otherwise falls back
2040 * to simply set the property
2042 * @param string $key property name
2043 * @param mixed $value value of the property
2045 public function __set($key, $value) {
2046 if (method_exists($this, 'set_'.$key)) {
2047 $this->{'set_'.$key}($value);
2049 $this->properties->{$key} = $value;
2053 * Magic get method
2055 * Attempts to call a get_$key method to return the property and ralls over
2056 * to return the raw property
2058 * @param string $key property name
2059 * @return mixed property value
2061 public function __get($key) {
2062 if (method_exists($this, 'get_'.$key)) {
2063 return $this->{'get_'.$key}();
2065 if (!isset($this->properties->{$key})) {
2066 throw new coding_exception('Undefined property requested');
2068 return $this->properties->{$key};
2072 * Stupid PHP needs an isset magic method if you use the get magic method and
2073 * still want empty calls to work.... blah ~!
2075 * @param string $key $key property name
2076 * @return bool|mixed property value, false if property is not exist
2078 public function __isset($key) {
2079 return !empty($this->properties->{$key});
2083 * Calculate the context value needed for calendar_event.
2084 * Event's type can be determine by the available value store in $data
2085 * It is important to check for the existence of course/courseid to determine
2086 * the course event.
2087 * Default value is set to CONTEXT_USER
2089 * @param stdClass $data information about event
2090 * @return stdClass The context object.
2092 protected function calculate_context(stdClass $data) {
2093 global $USER, $DB;
2095 $context = null;
2096 if (isset($data->courseid) && $data->courseid > 0) {
2097 $context = context_course::instance($data->courseid);
2098 } else if (isset($data->course) && $data->course > 0) {
2099 $context = context_course::instance($data->course);
2100 } else if (isset($data->groupid) && $data->groupid > 0) {
2101 $group = $DB->get_record('groups', array('id'=>$data->groupid));
2102 $context = context_course::instance($group->courseid);
2103 } else if (isset($data->userid) && $data->userid > 0 && $data->userid == $USER->id) {
2104 $context = context_user::instance($data->userid);
2105 } else if (isset($data->userid) && $data->userid > 0 && $data->userid != $USER->id &&
2106 isset($data->instance) && $data->instance > 0) {
2107 $cm = get_coursemodule_from_instance($data->modulename, $data->instance, 0, false, MUST_EXIST);
2108 $context = context_course::instance($cm->course);
2109 } else {
2110 $context = context_user::instance($data->userid);
2113 return $context;
2117 * Returns an array of editoroptions for this event: Called by __get
2118 * Please use $blah = $event->editoroptions;
2120 * @return array event editor options
2122 protected function get_editoroptions() {
2123 return $this->editoroptions;
2127 * Returns an event description: Called by __get
2128 * Please use $blah = $event->description;
2130 * @return string event description
2132 protected function get_description() {
2133 global $CFG;
2135 require_once($CFG->libdir . '/filelib.php');
2137 if ($this->_description === null) {
2138 // Check if we have already resolved the context for this event
2139 if ($this->editorcontext === null) {
2140 // Switch on the event type to decide upon the appropriate context
2141 // to use for this event
2142 $this->editorcontext = $this->properties->context;
2143 if ($this->properties->eventtype != 'user' && $this->properties->eventtype != 'course'
2144 && $this->properties->eventtype != 'site' && $this->properties->eventtype != 'group') {
2145 return clean_text($this->properties->description, $this->properties->format);
2149 // Work out the item id for the editor, if this is a repeated event then the files will
2150 // be associated with the original
2151 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2152 $itemid = $this->properties->repeatid;
2153 } else {
2154 $itemid = $this->properties->id;
2157 // Convert file paths in the description so that things display correctly
2158 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php', $this->editorcontext->id, 'calendar', 'event_description', $itemid);
2159 // Clean the text so no nasties get through
2160 $this->_description = clean_text($this->_description, $this->properties->format);
2162 // Finally return the description
2163 return $this->_description;
2167 * Return the number of repeat events there are in this events series
2169 * @return int number of event repeated
2171 public function count_repeats() {
2172 global $DB;
2173 if (!empty($this->properties->repeatid)) {
2174 $this->properties->eventrepeats = $DB->count_records('event', array('repeatid'=>$this->properties->repeatid));
2175 // We don't want to count ourselves
2176 $this->properties->eventrepeats--;
2178 return $this->properties->eventrepeats;
2182 * Update or create an event within the database
2184 * Pass in a object containing the event properties and this function will
2185 * insert it into the database and deal with any associated files
2187 * @see add_event()
2188 * @see update_event()
2190 * @param stdClass $data object of event
2191 * @param bool $checkcapability if moodle should check calendar managing capability or not
2192 * @return bool event updated
2194 public function update($data, $checkcapability=true) {
2195 global $CFG, $DB, $USER;
2197 foreach ($data as $key=>$value) {
2198 $this->properties->$key = $value;
2201 $this->properties->timemodified = time();
2202 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
2204 if (empty($this->properties->id) || $this->properties->id < 1) {
2206 if ($checkcapability) {
2207 if (!calendar_add_event_allowed($this->properties)) {
2208 print_error('nopermissiontoupdatecalendar');
2212 if ($usingeditor) {
2213 switch ($this->properties->eventtype) {
2214 case 'user':
2215 $this->properties->courseid = 0;
2216 $this->properties->course = 0;
2217 $this->properties->groupid = 0;
2218 $this->properties->userid = $USER->id;
2219 break;
2220 case 'site':
2221 $this->properties->courseid = SITEID;
2222 $this->properties->course = SITEID;
2223 $this->properties->groupid = 0;
2224 $this->properties->userid = $USER->id;
2225 break;
2226 case 'course':
2227 $this->properties->groupid = 0;
2228 $this->properties->userid = $USER->id;
2229 break;
2230 case 'group':
2231 $this->properties->userid = $USER->id;
2232 break;
2233 default:
2234 // Ewww we should NEVER get here, but just incase we do lets
2235 // fail gracefully
2236 $usingeditor = false;
2237 break;
2240 // If we are actually using the editor, we recalculate the context because some default values
2241 // were set when calculate_context() was called from the constructor.
2242 if ($usingeditor) {
2243 $this->properties->context = $this->calculate_context($this->properties);
2244 $this->editorcontext = $this->properties->context;
2247 $editor = $this->properties->description;
2248 $this->properties->format = $this->properties->description['format'];
2249 $this->properties->description = $this->properties->description['text'];
2252 // Insert the event into the database
2253 $this->properties->id = $DB->insert_record('event', $this->properties);
2255 if ($usingeditor) {
2256 $this->properties->description = file_save_draft_area_files(
2257 $editor['itemid'],
2258 $this->editorcontext->id,
2259 'calendar',
2260 'event_description',
2261 $this->properties->id,
2262 $this->editoroptions,
2263 $editor['text'],
2264 $this->editoroptions['forcehttps']);
2265 $DB->set_field('event', 'description', $this->properties->description, array('id'=>$this->properties->id));
2268 // Log the event entry.
2269 add_to_log($this->properties->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2271 $repeatedids = array();
2273 if (!empty($this->properties->repeat)) {
2274 $this->properties->repeatid = $this->properties->id;
2275 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id'=>$this->properties->id));
2277 $eventcopy = clone($this->properties);
2278 unset($eventcopy->id);
2280 for($i = 1; $i < $eventcopy->repeats; $i++) {
2282 $eventcopy->timestart = ($eventcopy->timestart+WEEKSECS) + dst_offset_on($eventcopy->timestart) - dst_offset_on($eventcopy->timestart+WEEKSECS);
2284 // Get the event id for the log record.
2285 $eventcopyid = $DB->insert_record('event', $eventcopy);
2287 // If the context has been set delete all associated files
2288 if ($usingeditor) {
2289 $fs = get_file_storage();
2290 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
2291 foreach ($files as $file) {
2292 $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
2296 $repeatedids[] = $eventcopyid;
2297 // Log the event entry.
2298 add_to_log($eventcopy->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$eventcopyid, $eventcopy->name);
2302 // Hook for tracking added events
2303 self::calendar_event_hook('add_event', array($this->properties, $repeatedids));
2304 return true;
2305 } else {
2307 if ($checkcapability) {
2308 if(!calendar_edit_event_allowed($this->properties)) {
2309 print_error('nopermissiontoupdatecalendar');
2313 if ($usingeditor) {
2314 if ($this->editorcontext !== null) {
2315 $this->properties->description = file_save_draft_area_files(
2316 $this->properties->description['itemid'],
2317 $this->editorcontext->id,
2318 'calendar',
2319 'event_description',
2320 $this->properties->id,
2321 $this->editoroptions,
2322 $this->properties->description['text'],
2323 $this->editoroptions['forcehttps']);
2324 } else {
2325 $this->properties->format = $this->properties->description['format'];
2326 $this->properties->description = $this->properties->description['text'];
2330 $event = $DB->get_record('event', array('id'=>$this->properties->id));
2332 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
2334 if ($updaterepeated) {
2335 // Update all
2336 if ($this->properties->timestart != $event->timestart) {
2337 $timestartoffset = $this->properties->timestart - $event->timestart;
2338 $sql = "UPDATE {event}
2339 SET name = ?,
2340 description = ?,
2341 timestart = timestart + ?,
2342 timeduration = ?,
2343 timemodified = ?
2344 WHERE repeatid = ?";
2345 $params = array($this->properties->name, $this->properties->description, $timestartoffset, $this->properties->timeduration, time(), $event->repeatid);
2346 } else {
2347 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
2348 $params = array($this->properties->name, $this->properties->description, $this->properties->timeduration, time(), $event->repeatid);
2350 $DB->execute($sql, $params);
2352 // Log the event update.
2353 add_to_log($this->properties->courseid, 'calendar', 'edit all', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2354 } else {
2355 $DB->update_record('event', $this->properties);
2356 $event = calendar_event::load($this->properties->id);
2357 $this->properties = $event->properties();
2358 add_to_log($this->properties->courseid, 'calendar', 'edit', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
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;
2387 // Delete the event
2388 $DB->delete_records('event', array('id'=>$this->properties->id));
2390 // If we are deleting parent of a repeated event series, promote the next event in the series as parent
2391 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
2392 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC", array($this->properties->id), IGNORE_MULTIPLE);
2393 if (!empty($newparent)) {
2394 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?", array($newparent, $this->properties->id));
2395 // Get all records where the repeatid is the same as the event being removed
2396 $events = $DB->get_records('event', array('repeatid' => $newparent));
2397 // For each of the returned events trigger the event_update hook.
2398 foreach ($events as $event) {
2399 self::calendar_event_hook('update_event', array($event, false));
2404 // If the editor context hasn't already been set then set it now
2405 if ($this->editorcontext === null) {
2406 $this->editorcontext = $this->properties->context;
2409 // If the context has been set delete all associated files
2410 if ($this->editorcontext !== null) {
2411 $fs = get_file_storage();
2412 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
2413 foreach ($files as $file) {
2414 $file->delete();
2418 // Fire the event deleted hook
2419 self::calendar_event_hook('delete_event', array($this->properties->id, $deleterepeated));
2421 // If we need to delete repeated events then we will fetch them all and delete one by one
2422 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2423 // Get all records where the repeatid is the same as the event being removed
2424 $events = $DB->get_records('event', array('repeatid'=>$this->properties->repeatid));
2425 // For each of the returned events populate a calendar_event object and call delete
2426 // make sure the arg passed is false as we are already deleting all repeats
2427 foreach ($events as $event) {
2428 $event = new calendar_event($event);
2429 $event->delete(false);
2433 return true;
2437 * Fetch all event properties
2439 * This function returns all of the events properties as an object and optionally
2440 * can prepare an editor for the description field at the same time. This is
2441 * designed to work when the properties are going to be used to set the default
2442 * values of a moodle forms form.
2444 * @param bool $prepareeditor If set to true a editor is prepared for use with
2445 * the mforms editor element. (for description)
2446 * @return stdClass Object containing event properties
2448 public function properties($prepareeditor=false) {
2449 global $USER, $CFG, $DB;
2451 // First take a copy of the properties. We don't want to actually change the
2452 // properties or we'd forever be converting back and forwards between an
2453 // editor formatted description and not
2454 $properties = clone($this->properties);
2455 // Clean the description here
2456 $properties->description = clean_text($properties->description, $properties->format);
2458 // If set to true we need to prepare the properties for use with an editor
2459 // and prepare the file area
2460 if ($prepareeditor) {
2462 // We may or may not have a property id. If we do then we need to work
2463 // out the context so we can copy the existing files to the draft area
2464 if (!empty($properties->id)) {
2466 if ($properties->eventtype === 'site') {
2467 // Site context
2468 $this->editorcontext = $this->properties->context;
2469 } else if ($properties->eventtype === 'user') {
2470 // User context
2471 $this->editorcontext = $this->properties->context;
2472 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
2473 // First check the course is valid
2474 $course = $DB->get_record('course', array('id'=>$properties->courseid));
2475 if (!$course) {
2476 print_error('invalidcourse');
2478 // Course context
2479 $this->editorcontext = $this->properties->context;
2480 // We have a course and are within the course context so we had
2481 // better use the courses max bytes value
2482 $this->editoroptions['maxbytes'] = $course->maxbytes;
2483 } else {
2484 // If we get here we have a custom event type as used by some
2485 // modules. In this case the event will have been added by
2486 // code and we won't need the editor
2487 $this->editoroptions['maxbytes'] = 0;
2488 $this->editoroptions['maxfiles'] = 0;
2491 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
2492 $contextid = false;
2493 } else {
2494 // Get the context id that is what we really want
2495 $contextid = $this->editorcontext->id;
2497 } else {
2499 // If we get here then this is a new event in which case we don't need a
2500 // context as there is no existing files to copy to the draft area.
2501 $contextid = null;
2504 // If the contextid === false we don't support files so no preparing
2505 // a draft area
2506 if ($contextid !== false) {
2507 // Just encase it has already been submitted
2508 $draftiddescription = file_get_submitted_draft_itemid('description');
2509 // Prepare the draft area, this copies existing files to the draft area as well
2510 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar', 'event_description', $properties->id, $this->editoroptions, $properties->description);
2511 } else {
2512 $draftiddescription = 0;
2515 // Structure the description field as the editor requires
2516 $properties->description = array('text'=>$properties->description, 'format'=>$properties->format, 'itemid'=>$draftiddescription);
2519 // Finally return the properties
2520 return $properties;
2524 * Toggles the visibility of an event
2526 * @param null|bool $force If it is left null the events visibility is flipped,
2527 * If it is false the event is made hidden, if it is true it
2528 * is made visible.
2529 * @return bool if event is successfully updated, toggle will be visible
2531 public function toggle_visibility($force=null) {
2532 global $CFG, $DB;
2534 // Set visible to the default if it is not already set
2535 if (empty($this->properties->visible)) {
2536 $this->properties->visible = 1;
2539 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
2540 // Make this event visible
2541 $this->properties->visible = 1;
2542 // Fire the hook
2543 self::calendar_event_hook('show_event', array($this->properties));
2544 } else {
2545 // Make this event hidden
2546 $this->properties->visible = 0;
2547 // Fire the hook
2548 self::calendar_event_hook('hide_event', array($this->properties));
2551 // Update the database to reflect this change
2552 return $DB->set_field('event', 'visible', $this->properties->visible, array('id'=>$this->properties->id));
2556 * Attempts to call the hook for the specified action should a calendar type
2557 * by set $CFG->calendar, and the appopriate function defined
2559 * @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
2560 * @param array $args The args to pass to the hook, usually the event is the first element
2561 * @return bool attempts to call event hook
2563 public static function calendar_event_hook($action, array $args) {
2564 global $CFG;
2565 static $extcalendarinc;
2566 if ($extcalendarinc === null) {
2567 if (!empty($CFG->calendar)) {
2568 if (is_readable($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
2569 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
2570 $extcalendarinc = true;
2571 } else {
2572 debugging("Calendar lib file missing or not readable at /calendar/{$CFG->calendar}/lib.php.",
2573 DEBUG_DEVELOPER);
2574 $extcalendarinc = false;
2576 } else {
2577 $extcalendarinc = false;
2580 if($extcalendarinc === false) {
2581 return false;
2583 $hook = $CFG->calendar .'_'.$action;
2584 if (function_exists($hook)) {
2585 call_user_func_array($hook, $args);
2586 return true;
2588 return false;
2592 * Returns a calendar_event object when provided with an event id
2594 * This function makes use of MUST_EXIST, if the event id passed in is invalid
2595 * it will result in an exception being thrown
2597 * @param int|object $param event object or event id
2598 * @return calendar_event|false status for loading calendar_event
2600 public static function load($param) {
2601 global $DB;
2602 if (is_object($param)) {
2603 $event = new calendar_event($param);
2604 } else {
2605 $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST);
2606 $event = new calendar_event($event);
2608 return $event;
2612 * Creates a new event and returns a calendar_event object
2614 * @param object|array $properties An object containing event properties
2615 * @return calendar_event|false The event object or false if it failed
2617 public static function create($properties) {
2618 if (is_array($properties)) {
2619 $properties = (object)$properties;
2621 if (!is_object($properties)) {
2622 throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2624 $event = new calendar_event($properties);
2625 if ($event->update($properties)) {
2626 return $event;
2627 } else {
2628 return false;
2634 * Calendar information class
2636 * This class is used simply to organise the information pertaining to a calendar
2637 * and is used primarily to make information easily available.
2639 * @package core_calendar
2640 * @category calendar
2641 * @copyright 2010 Sam Hemelryk
2642 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2644 class calendar_information {
2647 * @var int The timestamp
2649 * Rather than setting the day, month and year we will set a timestamp which will be able
2650 * to be used by multiple calendars.
2652 public $time;
2654 /** @var int A course id */
2655 public $courseid = null;
2657 /** @var array An array of courses */
2658 public $courses = array();
2660 /** @var array An array of groups */
2661 public $groups = array();
2663 /** @var array An array of users */
2664 public $users = array();
2667 * Creates a new instance
2669 * @param int $day the number of the day
2670 * @param int $month the number of the month
2671 * @param int $year the number of the year
2672 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
2673 * and $calyear to support multiple calendars
2675 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
2676 // If a day, month and year were passed then convert it to a timestamp. If these were passed
2677 // then we can assume the day, month and year are passed as Gregorian, as no where in core
2678 // should we be passing these values rather than the time. This is done for BC.
2679 if (!empty($day) || !empty($month) || !empty($year)) {
2680 $date = usergetdate(time());
2681 if (empty($day)) {
2682 $day = $date['mday'];
2684 if (empty($month)) {
2685 $month = $date['mon'];
2687 if (empty($year)) {
2688 $year = $date['year'];
2690 if (checkdate($month, $day, $year)) {
2691 $this->time = make_timestamp($year, $month, $day);
2692 } else {
2693 $this->time = time();
2695 } else if (!empty($time)) {
2696 $this->time = $time;
2697 } else {
2698 $this->time = time();
2703 * Initialize calendar information
2705 * @param stdClass $course object
2706 * @param array $coursestoload An array of courses [$course->id => $course]
2707 * @param bool $ignorefilters options to use filter
2709 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
2710 $this->courseid = $course->id;
2711 $this->course = $course;
2712 list($courses, $group, $user) = calendar_set_filters($coursestoload, $ignorefilters);
2713 $this->courses = $courses;
2714 $this->groups = $group;
2715 $this->users = $user;
2719 * Ensures the date for the calendar is correct and either sets it to now
2720 * or throws a moodle_exception if not
2722 * @param bool $defaultonow use current time
2723 * @throws moodle_exception
2724 * @return bool validation of checkdate
2726 public function checkdate($defaultonow = true) {
2727 if (!checkdate($this->month, $this->day, $this->year)) {
2728 if ($defaultonow) {
2729 $now = usergetdate(time());
2730 $this->day = intval($now['mday']);
2731 $this->month = intval($now['mon']);
2732 $this->year = intval($now['year']);
2733 return true;
2734 } else {
2735 throw new moodle_exception('invaliddate');
2738 return true;
2742 * Gets todays timestamp for the calendar
2744 * @return int today timestamp
2746 public function timestamp_today() {
2747 return $this->time;
2750 * Gets tomorrows timestamp for the calendar
2752 * @return int tomorrow timestamp
2754 public function timestamp_tomorrow() {
2755 return $this->time + DAYSECS;
2758 * Adds the pretend blocks for the calendar
2760 * @param core_calendar_renderer $renderer
2761 * @param bool $showfilters display filters, false is set as default
2762 * @param string|null $view preference view options (eg: day, month, upcoming)
2764 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
2765 if ($showfilters) {
2766 $filters = new block_contents();
2767 $filters->content = $renderer->fake_block_filters($this->courseid, 0, 0, 0, $view, $this->courses);
2768 $filters->footer = '';
2769 $filters->title = get_string('eventskey', 'calendar');
2770 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
2772 $block = new block_contents;
2773 $block->content = $renderer->fake_block_threemonths($this);
2774 $block->footer = '';
2775 $block->title = get_string('monthlyview', 'calendar');
2776 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
2781 * Returns option list for the poll interval setting.
2783 * @return array An array of poll interval options. Interval => description.
2785 function calendar_get_pollinterval_choices() {
2786 return array(
2787 '0' => new lang_string('never', 'calendar'),
2788 '3600' => new lang_string('hourly', 'calendar'),
2789 '86400' => new lang_string('daily', 'calendar'),
2790 '604800' => new lang_string('weekly', 'calendar'),
2791 '2628000' => new lang_string('monthly', 'calendar'),
2792 '31536000' => new lang_string('annually', 'calendar')
2797 * Returns option list of available options for the calendar event type, given the current user and course.
2799 * @param int $courseid The id of the course
2800 * @return array An array containing the event types the user can create.
2802 function calendar_get_eventtype_choices($courseid) {
2803 $choices = array();
2804 $allowed = new stdClass;
2805 calendar_get_allowed_types($allowed, $courseid);
2807 if ($allowed->user) {
2808 $choices['user'] = get_string('userevents', 'calendar');
2810 if ($allowed->site) {
2811 $choices['site'] = get_string('siteevents', 'calendar');
2813 if (!empty($allowed->courses)) {
2814 $choices['course'] = get_string('courseevents', 'calendar');
2816 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2817 $choices['group'] = get_string('group');
2820 return array($choices, $allowed->groups);
2824 * Add an iCalendar subscription to the database.
2826 * @param stdClass $sub The subscription object (e.g. from the form)
2827 * @return int The insert ID, if any.
2829 function calendar_add_subscription($sub) {
2830 global $DB, $USER, $SITE;
2832 if ($sub->eventtype === 'site') {
2833 $sub->courseid = $SITE->id;
2834 } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
2835 $sub->courseid = $sub->course;
2836 } else {
2837 // User events.
2838 $sub->courseid = 0;
2840 $sub->userid = $USER->id;
2842 // File subscriptions never update.
2843 if (empty($sub->url)) {
2844 $sub->pollinterval = 0;
2847 if (!empty($sub->name)) {
2848 if (empty($sub->id)) {
2849 $id = $DB->insert_record('event_subscriptions', $sub);
2850 // we cannot cache the data here because $sub is not complete.
2851 return $id;
2852 } else {
2853 // Why are we doing an update here?
2854 calendar_update_subscription($sub);
2855 return $sub->id;
2857 } else {
2858 print_error('errorbadsubscription', 'importcalendar');
2863 * Add an iCalendar event to the Moodle calendar.
2865 * @param object $event The RFC-2445 iCalendar event
2866 * @param int $courseid The course ID
2867 * @param int $subscriptionid The iCalendar subscription ID
2868 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2869 * @return int Code: 1=updated, 2=inserted, 0=error
2871 function calendar_add_icalendar_event($event, $courseid, $subscriptionid) {
2872 global $DB, $USER;
2874 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2875 if (empty($event->properties['SUMMARY'])) {
2876 return 0;
2879 $name = $event->properties['SUMMARY'][0]->value;
2880 $name = str_replace('\n', '<br />', $name);
2881 $name = str_replace('\\', '', $name);
2882 $name = preg_replace('/\s+/', ' ', $name);
2884 $eventrecord = new stdClass;
2885 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
2887 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2888 $description = '';
2889 } else {
2890 $description = $event->properties['DESCRIPTION'][0]->value;
2891 $description = str_replace('\n', '<br />', $description);
2892 $description = str_replace('\\', '', $description);
2893 $description = preg_replace('/\s+/', ' ', $description);
2895 $eventrecord->description = clean_param($description, PARAM_NOTAGS);
2897 // Probably a repeating event with RRULE etc. TODO: skip for now.
2898 if (empty($event->properties['DTSTART'][0]->value)) {
2899 return 0;
2902 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value);
2903 if (empty($event->properties['DTEND'])) {
2904 $eventrecord->timeduration = 3600; // one hour if no end time specified
2905 } else {
2906 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value) - $eventrecord->timestart;
2908 $eventrecord->uuid = $event->properties['UID'][0]->value;
2909 $eventrecord->timemodified = time();
2911 // Add the iCal subscription details if required.
2912 // We should never do anything with an event without a subscription reference.
2913 $sub = calendar_get_subscription($subscriptionid);
2914 $eventrecord->subscriptionid = $subscriptionid;
2915 $eventrecord->userid = $sub->userid;
2916 $eventrecord->groupid = $sub->groupid;
2917 $eventrecord->courseid = $sub->courseid;
2918 $eventrecord->eventtype = $sub->eventtype;
2920 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid))) {
2921 $eventrecord->id = $updaterecord->id;
2922 if ($DB->update_record('event', $eventrecord)) {
2923 return CALENDAR_IMPORT_EVENT_UPDATED;
2924 } else {
2925 return 0;
2927 } else {
2928 if ($DB->insert_record('event', $eventrecord)) {
2929 return CALENDAR_IMPORT_EVENT_INSERTED;
2930 } else {
2931 return 0;
2937 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2939 * @param int $subscriptionid The ID of the subscription we are acting upon.
2940 * @param int $pollinterval The poll interval to use.
2941 * @param int $action The action to be performed. One of update or remove.
2942 * @throws dml_exception if invalid subscriptionid is provided
2943 * @return string A log of the import progress, including errors
2945 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2947 // Fetch the subscription from the database making sure it exists.
2948 $sub = calendar_get_subscription($subscriptionid);
2950 // Update or remove the subscription, based on action.
2951 switch ($action) {
2952 case CALENDAR_SUBSCRIPTION_UPDATE:
2953 // Skip updating file subscriptions.
2954 if (empty($sub->url)) {
2955 break;
2957 $sub->pollinterval = $pollinterval;
2958 calendar_update_subscription($sub);
2960 // Update the events.
2961 return "<p>".get_string('subscriptionupdated', 'calendar', $sub->name)."</p>" . calendar_update_subscription_events($subscriptionid);
2963 case CALENDAR_SUBSCRIPTION_REMOVE:
2964 calendar_delete_subscription($subscriptionid);
2965 return get_string('subscriptionremoved', 'calendar', $sub->name);
2966 break;
2968 default:
2969 break;
2971 return '';
2975 * Delete subscription and all related events.
2977 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
2979 function calendar_delete_subscription($subscription) {
2980 global $DB;
2982 if (is_object($subscription)) {
2983 $subscription = $subscription->id;
2985 // Delete subscription and related events.
2986 $DB->delete_records('event', array('subscriptionid' => $subscription));
2987 $DB->delete_records('event_subscriptions', array('id' => $subscription));
2988 cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription));
2991 * From a URL, fetch the calendar and return an iCalendar object.
2993 * @param string $url The iCalendar URL
2994 * @return stdClass The iCalendar object
2996 function calendar_get_icalendar($url) {
2997 global $CFG;
2999 require_once($CFG->libdir.'/filelib.php');
3001 $curl = new curl();
3002 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
3003 $calendar = $curl->get($url);
3004 // Http code validation should actually be the job of curl class.
3005 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
3006 throw new moodle_exception('errorinvalidicalurl', 'calendar');
3009 $ical = new iCalendar();
3010 $ical->unserialize($calendar);
3011 return $ical;
3015 * Import events from an iCalendar object into a course calendar.
3017 * @param stdClass $ical The iCalendar object.
3018 * @param int $courseid The course ID for the calendar.
3019 * @param int $subscriptionid The subscription ID.
3020 * @return string A log of the import progress, including errors.
3022 function calendar_import_icalendar_events($ical, $courseid, $subscriptionid = null) {
3023 global $DB;
3024 $return = '';
3025 $eventcount = 0;
3026 $updatecount = 0;
3028 // Large calendars take a while...
3029 set_time_limit(300);
3031 // Mark all events in a subscription with a zero timestamp.
3032 if (!empty($subscriptionid)) {
3033 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
3034 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3036 foreach ($ical->components['VEVENT'] as $event) {
3037 $res = calendar_add_icalendar_event($event, $courseid, $subscriptionid);
3038 switch ($res) {
3039 case CALENDAR_IMPORT_EVENT_UPDATED:
3040 $updatecount++;
3041 break;
3042 case CALENDAR_IMPORT_EVENT_INSERTED:
3043 $eventcount++;
3044 break;
3045 case 0:
3046 $return .= '<p>'.get_string('erroraddingevent', 'calendar').': '.(empty($event->properties['SUMMARY'])?'('.get_string('notitle', 'calendar').')':$event->properties['SUMMARY'][0]->value)." </p>\n";
3047 break;
3050 $return .= "<p> ".get_string('eventsimported', 'calendar', $eventcount)."</p>";
3051 $return .= "<p> ".get_string('eventsupdated', 'calendar', $updatecount)."</p>";
3053 // Delete remaining zero-marked events since they're not in remote calendar.
3054 if (!empty($subscriptionid)) {
3055 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3056 if (!empty($deletecount)) {
3057 $sql = "DELETE FROM {event} WHERE timemodified = :time AND subscriptionid = :id";
3058 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3059 $return .= "<p> ".get_string('eventsdeleted', 'calendar').": {$deletecount} </p>\n";
3063 return $return;
3067 * Fetch a calendar subscription and update the events in the calendar.
3069 * @param int $subscriptionid The course ID for the calendar.
3070 * @return string A log of the import progress, including errors.
3072 function calendar_update_subscription_events($subscriptionid) {
3073 global $DB;
3075 $sub = calendar_get_subscription($subscriptionid);
3076 // Don't update a file subscription. TODO: Update from a new uploaded file.
3077 if (empty($sub->url)) {
3078 return 'File subscription not updated.';
3080 $ical = calendar_get_icalendar($sub->url);
3081 $return = calendar_import_icalendar_events($ical, $sub->courseid, $subscriptionid);
3082 $sub->lastupdated = time();
3083 calendar_update_subscription($sub);
3084 return $return;
3088 * Update a calendar subscription. Also updates the associated cache.
3090 * @param stdClass|array $subscription Subscription record.
3091 * @throws coding_exception If something goes wrong
3092 * @since Moodle 2.5
3094 function calendar_update_subscription($subscription) {
3095 global $DB;
3097 if (is_array($subscription)) {
3098 $subscription = (object)$subscription;
3100 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
3101 throw new coding_exception('Cannot update a subscription without a valid id');
3104 $DB->update_record('event_subscriptions', $subscription);
3105 // Update cache.
3106 $cache = cache::make('core', 'calendar_subscriptions');
3107 $cache->set($subscription->id, $subscription);
3111 * Checks to see if the user can edit a given subscription feed.
3113 * @param mixed $subscriptionorid Subscription object or id
3114 * @return bool true if current user can edit the subscription else false
3116 function calendar_can_edit_subscription($subscriptionorid) {
3117 global $DB;
3119 if (is_array($subscriptionorid)) {
3120 $subscription = (object)$subscriptionorid;
3121 } else if (is_object($subscriptionorid)) {
3122 $subscription = $subscriptionorid;
3123 } else {
3124 $subscription = calendar_get_subscription($subscriptionorid);
3126 $allowed = new stdClass;
3127 $courseid = $subscription->courseid;
3128 $groupid = $subscription->groupid;
3129 calendar_get_allowed_types($allowed, $courseid);
3130 switch ($subscription->eventtype) {
3131 case 'user':
3132 return $allowed->user;
3133 case 'course':
3134 if (isset($allowed->courses[$courseid])) {
3135 return $allowed->courses[$courseid];
3136 } else {
3137 return false;
3139 case 'site':
3140 return $allowed->site;
3141 case 'group':
3142 if (isset($allowed->groups[$groupid])) {
3143 return $allowed->groups[$groupid];
3144 } else {
3145 return false;
3147 default:
3148 return false;
3153 * Update calendar subscriptions.
3155 * @return bool
3157 function calendar_cron() {
3158 global $CFG, $DB;
3160 // In order to execute this we need bennu.
3161 require_once($CFG->libdir.'/bennu/bennu.inc.php');
3163 mtrace('Updating calendar subscriptions:');
3164 cron_trace_time_and_memory();
3166 $time = time();
3167 $subscriptions = $DB->get_records_sql('SELECT * FROM {event_subscriptions} WHERE pollinterval > 0 AND lastupdated + pollinterval < ?', array($time));
3168 foreach ($subscriptions as $sub) {
3169 mtrace("Updating calendar subscription {$sub->name} in course {$sub->courseid}");
3170 try {
3171 $log = calendar_update_subscription_events($sub->id);
3172 mtrace(trim(strip_tags($log)));
3173 } catch (moodle_exception $ex) {
3174 mtrace('Error updating calendar subscription: ' . $ex->getMessage());
3178 mtrace('Finished updating calendar subscriptions.');
3180 return true;