MDL-40903 cache: renamed persistcache to staticacceleration
[moodle.git] / calendar / lib.php
blobede82803316b56caaecc501a8aa24cc39f44f071
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 return array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
133 * Get the subscription from a given id
135 * @since Moodle 2.5
136 * @param int $id id of the subscription
137 * @return stdClass Subscription record from DB
138 * @throws moodle_exception for an invalid id
140 function calendar_get_subscription($id) {
141 global $DB;
143 $cache = cache::make('core', 'calendar_subscriptions');
144 $subscription = $cache->get($id);
145 if (empty($subscription)) {
146 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
147 // cache the data.
148 $cache->set($id, $subscription);
150 return $subscription;
154 * Gets the first day of the week
156 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
158 * @return int
160 function calendar_get_starting_weekday() {
161 global $CFG;
163 if (isset($CFG->calendar_startwday)) {
164 $firstday = $CFG->calendar_startwday;
165 } else {
166 $firstday = get_string('firstdayofweek', 'langconfig');
169 if(!is_numeric($firstday)) {
170 return CALENDAR_DEFAULT_STARTING_WEEKDAY;
171 } else {
172 return intval($firstday) % 7;
177 * Generates the HTML for a miniature calendar
179 * @param array $courses list of course to list events from
180 * @param array $groups list of group
181 * @param array $users user's info
182 * @param int $cal_month calendar month in numeric, default is set to false
183 * @param int $cal_year calendar month in numeric, default is set to false
184 * @param string $placement the place/page the calendar is set to appear - passed on the the controls function
185 * @param int $courseid id of the course the calendar is displayed on - passed on the the controls function
186 * @return string $content return html table for mini calendar
188 function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_year = false, $placement = false, $courseid = false ) {
189 global $CFG, $USER, $OUTPUT;
191 $display = new stdClass;
192 $display->minwday = get_user_preferences('calendar_startwday', calendar_get_starting_weekday());
193 $display->maxwday = $display->minwday + 6;
195 $content = '';
197 if(!empty($cal_month) && !empty($cal_year)) {
198 $thisdate = usergetdate(time()); // Date and time the user sees at his location
199 if($cal_month == $thisdate['mon'] && $cal_year == $thisdate['year']) {
200 // Navigated to this month
201 $date = $thisdate;
202 $display->thismonth = true;
203 } else {
204 // Navigated to other month, let's do a nice trick and save us a lot of work...
205 if(!checkdate($cal_month, 1, $cal_year)) {
206 $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']);
207 $display->thismonth = true;
208 } else {
209 $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year);
210 $display->thismonth = false;
213 } else {
214 $date = usergetdate(time()); // Date and time the user sees at his location
215 $display->thismonth = true;
218 // Fill in the variables we 're going to use, nice and tidy
219 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display
220 $display->maxdays = calendar_days_in_month($m, $y);
222 if (get_user_timezone_offset() < 99) {
223 // We 'll keep these values as GMT here, and offset them when the time comes to query the db
224 $display->tstart = gmmktime(0, 0, 0, $m, 1, $y); // This is GMT
225 $display->tend = gmmktime(23, 59, 59, $m, $display->maxdays, $y); // GMT
226 } else {
227 // no timezone info specified
228 $display->tstart = mktime(0, 0, 0, $m, 1, $y);
229 $display->tend = mktime(23, 59, 59, $m, $display->maxdays, $y);
232 $startwday = dayofweek(1, $m, $y);
234 // Align the starting weekday to fall in our display range
235 // This is simple, not foolproof.
236 if($startwday < $display->minwday) {
237 $startwday += 7;
240 // TODO: THIS IS TEMPORARY CODE!
241 // [pj] I was just reading through this and realized that I when writing this code I was probably
242 // asking for trouble, as all these time manipulations seem to be unnecessary and a simple
243 // make_timestamp would accomplish the same thing. So here goes a test:
244 //$test_start = make_timestamp($y, $m, 1);
245 //$test_end = make_timestamp($y, $m, $display->maxdays, 23, 59, 59);
246 //if($test_start != usertime($display->tstart) - dst_offset_on($display->tstart)) {
247 //notify('Failed assertion in calendar/lib.php line 126; display->tstart = '.$display->tstart.', dst_offset = '.dst_offset_on($display->tstart).', usertime = '.usertime($display->tstart).', make_t = '.$test_start);
249 //if($test_end != usertime($display->tend) - dst_offset_on($display->tend)) {
250 //notify('Failed assertion in calendar/lib.php line 130; display->tend = '.$display->tend.', dst_offset = '.dst_offset_on($display->tend).', usertime = '.usertime($display->tend).', make_t = '.$test_end);
254 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
255 $events = calendar_get_events(
256 usertime($display->tstart) - dst_offset_on($display->tstart),
257 usertime($display->tend) - dst_offset_on($display->tend),
258 $users, $groups, $courses);
260 // Set event course class for course events
261 if (!empty($events)) {
262 foreach ($events as $eventid => $event) {
263 if (!empty($event->modulename)) {
264 $cm = get_coursemodule_from_instance($event->modulename, $event->instance);
265 if (!groups_course_module_visible($cm)) {
266 unset($events[$eventid]);
272 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
273 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
274 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
275 // arguments to this function.
277 $hrefparams = array();
278 if(!empty($courses)) {
279 $courses = array_diff($courses, array(SITEID));
280 if(count($courses) == 1) {
281 $hrefparams['course'] = reset($courses);
285 // We want to have easy access by day, since the display is on a per-day basis.
286 // Arguments passed by reference.
287 //calendar_events_by_day($events, $display->tstart, $eventsbyday, $durationbyday, $typesbyday);
288 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
290 //Accessibility: added summary and <abbr> elements.
291 $days_title = calendar_get_days();
293 $summary = get_string('calendarheading', 'calendar', userdate(make_timestamp($y, $m), get_string('strftimemonthyear')));
294 $content .= '<table class="minicalendar calendartable" summary="'.$summary.'">'; // Begin table
295 if (($placement !== false) && ($courseid !== false)) {
296 $content .= '<caption>'. calendar_top_controls($placement, array('id' => $courseid, 'm' => $m, 'y' => $y)) .'</caption>';
298 $content .= '<tr class="weekdays">'; // Header row: day names
300 // Print out the names of the weekdays
301 $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
302 for($i = $display->minwday; $i <= $display->maxwday; ++$i) {
303 // This uses the % operator to get the correct weekday no matter what shift we have
304 // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
305 $content .= '<th scope="col"><abbr title="'. get_string($days_title[$i % 7], 'calendar') .'">'.
306 get_string($days[$i % 7], 'calendar') ."</abbr></th>\n";
309 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
311 // For the table display. $week is the row; $dayweek is the column.
312 $dayweek = $startwday;
314 // Paddding (the first week may have blank days in the beginning)
315 for($i = $display->minwday; $i < $startwday; ++$i) {
316 $content .= '<td class="dayblank">&nbsp;</td>'."\n";
319 $weekend = CALENDAR_DEFAULT_WEEKEND;
320 if (isset($CFG->calendar_weekend)) {
321 $weekend = intval($CFG->calendar_weekend);
324 // Now display all the calendar
325 for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
326 if($dayweek > $display->maxwday) {
327 // We need to change week (table row)
328 $content .= '</tr><tr>';
329 $dayweek = $display->minwday;
332 // Reset vars
333 $cell = '';
334 if ($weekend & (1 << ($dayweek % 7))) {
335 // Weekend. This is true no matter what the exact range is.
336 $class = 'weekend day';
337 } else {
338 // Normal working day.
339 $class = 'day';
342 // Special visual fx if an event is defined
343 if(isset($eventsbyday[$day])) {
344 $class .= ' hasevent';
345 $hrefparams['view'] = 'day';
346 $dayhref = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $hrefparams), $day, $m, $y);
348 $popupcontent = '';
349 foreach($eventsbyday[$day] as $eventid) {
350 if (!isset($events[$eventid])) {
351 continue;
353 $event = new calendar_event($events[$eventid]);
354 $popupalt = '';
355 $component = 'moodle';
356 if(!empty($event->modulename)) {
357 $popupicon = 'icon';
358 $popupalt = $event->modulename;
359 $component = $event->modulename;
360 } else if ($event->courseid == SITEID) { // Site event
361 $popupicon = 'i/siteevent';
362 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
363 $popupicon = 'i/courseevent';
364 } else if ($event->groupid) { // Group event
365 $popupicon = 'i/groupevent';
366 } else if ($event->userid) { // User event
367 $popupicon = 'i/userevent';
370 $dayhref->set_anchor('event_'.$event->id);
372 $popupcontent .= html_writer::start_tag('div');
373 $popupcontent .= $OUTPUT->pix_icon($popupicon, $popupalt, $component);
374 $name = format_string($event->name, true);
375 // Show ical source if needed.
376 if (!empty($event->subscription) && $CFG->calendar_showicalsource) {
377 $a = new stdClass();
378 $a->name = $name;
379 $a->source = $event->subscription->name;
380 $name = get_string('namewithsource', 'calendar', $a);
382 $popupcontent .= html_writer::link($dayhref, $name);
383 $popupcontent .= html_writer::end_tag('div');
386 //Accessibility: functionality moved to calendar_get_popup.
387 if($display->thismonth && $day == $d) {
388 $popupid = calendar_get_popup(true, $events[$eventid]->timestart, $popupcontent);
389 } else {
390 $popupid = calendar_get_popup(false, $events[$eventid]->timestart, $popupcontent);
393 // Class and cell content
394 if(isset($typesbyday[$day]['startglobal'])) {
395 $class .= ' calendar_event_global';
396 } else if(isset($typesbyday[$day]['startcourse'])) {
397 $class .= ' calendar_event_course';
398 } else if(isset($typesbyday[$day]['startgroup'])) {
399 $class .= ' calendar_event_group';
400 } else if(isset($typesbyday[$day]['startuser'])) {
401 $class .= ' calendar_event_user';
403 $cell = html_writer::link($dayhref, $day, array('aria-controls' => $popupid.'_panel', 'id' => $popupid));
404 } else {
405 $cell = $day;
408 $durationclass = false;
409 if (isset($typesbyday[$day]['durationglobal'])) {
410 $durationclass = ' duration_global';
411 } else if(isset($typesbyday[$day]['durationcourse'])) {
412 $durationclass = ' duration_course';
413 } else if(isset($typesbyday[$day]['durationgroup'])) {
414 $durationclass = ' duration_group';
415 } else if(isset($typesbyday[$day]['durationuser'])) {
416 $durationclass = ' duration_user';
418 if ($durationclass) {
419 $class .= ' duration '.$durationclass;
422 // If event has a class set then add it to the table day <td> tag
423 // Note: only one colour for minicalendar
424 if(isset($eventsbyday[$day])) {
425 foreach($eventsbyday[$day] as $eventid) {
426 if (!isset($events[$eventid])) {
427 continue;
429 $event = $events[$eventid];
430 if (!empty($event->class)) {
431 $class .= ' '.$event->class;
433 break;
437 // Special visual fx for today
438 //Accessibility: hidden text for today, and popup.
439 if($display->thismonth && $day == $d) {
440 $class .= ' today';
441 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
443 if(! isset($eventsbyday[$day])) {
444 $class .= ' eventnone';
445 $popupid = calendar_get_popup(true, false);
446 $cell = html_writer::link('#', $day, array('aria-controls' => $popupid.'_panel', 'id' => $popupid));
448 $cell = get_accesshide($today.' ').$cell;
451 // Just display it
452 if(!empty($class)) {
453 $class = ' class="'.$class.'"';
455 $content .= '<td'.$class.'>'.$cell."</td>\n";
458 // Paddding (the last week may have blank days at the end)
459 for($i = $dayweek; $i <= $display->maxwday; ++$i) {
460 $content .= '<td class="dayblank">&nbsp;</td>';
462 $content .= '</tr>'; // Last row ends
464 $content .= '</table>'; // Tabular display of days ends
466 return $content;
470 * Gets the calendar popup
472 * It called at multiple points in from calendar_get_mini.
473 * Copied and modified from calendar_get_mini.
475 * @param bool $is_today false except when called on the current day.
476 * @param mixed $event_timestart $events[$eventid]->timestart, OR false if there are no events.
477 * @param string $popupcontent content for the popup window/layout.
478 * @return string eventid for the calendar_tooltip popup window/layout.
480 function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
481 global $PAGE;
482 static $popupcount;
483 if ($popupcount === null) {
484 $popupcount = 1;
486 $popupcaption = '';
487 if($is_today) {
488 $popupcaption = get_string('today', 'calendar').' ';
490 if (false === $event_timestart) {
491 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
492 $popupcontent = get_string('eventnone', 'calendar');
494 } else {
495 $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
497 $id = 'calendar_tooltip_'.$popupcount;
498 $PAGE->requires->yui_module('moodle-calendar-eventmanager', 'M.core_calendar.add_event', array(array('eventId'=>$id,'title'=>$popupcaption, 'content'=>$popupcontent)));
500 $popupcount++;
501 return $id;
505 * Gets the calendar upcoming event
507 * @param array $courses array of courses
508 * @param array|int|bool $groups array of groups, group id or boolean for all/no group events
509 * @param array|int|bool $users array of users, user id or boolean for all/no user events
510 * @param int $daysinfuture number of days in the future we 'll look
511 * @param int $maxevents maximum number of events
512 * @param int $fromtime start time
513 * @return array $output array of upcoming events
515 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
516 global $CFG, $COURSE, $DB;
518 $display = new stdClass;
519 $display->range = $daysinfuture; // How many days in the future we 'll look
520 $display->maxevents = $maxevents;
522 $output = array();
524 // Prepare "course caching", since it may save us a lot of queries
525 $coursecache = array();
527 $processed = 0;
528 $now = time(); // We 'll need this later
529 $usermidnighttoday = usergetmidnight($now);
531 if ($fromtime) {
532 $display->tstart = $fromtime;
533 } else {
534 $display->tstart = $usermidnighttoday;
537 // This works correctly with respect to the user's DST, but it is accurate
538 // only because $fromtime is always the exact midnight of some day!
539 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
541 // Get the events matching our criteria
542 $events = calendar_get_events($display->tstart, $display->tend, $users, $groups, $courses);
544 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
545 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
546 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
547 // arguments to this function.
549 $hrefparams = array();
550 if(!empty($courses)) {
551 $courses = array_diff($courses, array(SITEID));
552 if(count($courses) == 1) {
553 $hrefparams['course'] = reset($courses);
557 if ($events !== false) {
559 $modinfo = get_fast_modinfo($COURSE);
561 foreach($events as $event) {
564 if (!empty($event->modulename)) {
565 if ($event->courseid == $COURSE->id) {
566 if (isset($modinfo->instances[$event->modulename][$event->instance])) {
567 $cm = $modinfo->instances[$event->modulename][$event->instance];
568 if (!$cm->uservisible) {
569 continue;
572 } else {
573 if (!$cm = get_coursemodule_from_instance($event->modulename, $event->instance)) {
574 continue;
576 if (!coursemodule_visible_for_user($cm)) {
577 continue;
580 if ($event->modulename == 'assignment'){
581 // create calendar_event to test edit_event capability
582 // this new event will also prevent double creation of calendar_event object
583 $checkevent = new calendar_event($event);
584 // TODO: rewrite this hack somehow
585 if (!calendar_edit_event_allowed($checkevent)){ // cannot manage entries, eg. student
586 if (!$assignment = $DB->get_record('assignment', array('id'=>$event->instance))) {
587 // print_error("invalidid", 'assignment');
588 continue;
590 // assign assignment to assignment object to use hidden_is_hidden method
591 require_once($CFG->dirroot.'/mod/assignment/lib.php');
593 if (!file_exists($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php')) {
594 continue;
596 require_once ($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
598 $assignmentclass = 'assignment_'.$assignment->assignmenttype;
599 $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm);
601 if ($assignmentinstance->description_is_hidden()){//force not to show description before availability
602 $event->description = get_string('notavailableyet', 'assignment');
608 if ($processed >= $display->maxevents) {
609 break;
612 $event->time = calendar_format_event_time($event, $now, $hrefparams);
613 $output[] = $event;
614 ++$processed;
617 return $output;
622 * Get a HTML link to a course.
624 * @param int $courseid the course id
625 * @return string a link to the course (as HTML); empty if the course id is invalid
627 function calendar_get_courselink($courseid) {
629 if (!$courseid) {
630 return '';
633 calendar_get_course_cached($coursecache, $courseid);
634 $context = context_course::instance($courseid);
635 $fullname = format_string($coursecache[$courseid]->fullname, true, array('context' => $context));
636 $url = new moodle_url('/course/view.php', array('id' => $courseid));
637 $link = html_writer::link($url, $fullname);
639 return $link;
644 * Add calendar event metadata
646 * @param stdClass $event event info
647 * @return stdClass $event metadata
649 function calendar_add_event_metadata($event) {
650 global $CFG, $OUTPUT;
652 //Support multilang in event->name
653 $event->name = format_string($event->name,true);
655 if(!empty($event->modulename)) { // Activity event
656 // The module name is set. I will assume that it has to be displayed, and
657 // also that it is an automatically-generated event. And of course that the
658 // fields for get_coursemodule_from_instance are set correctly.
659 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
661 if ($module === false) {
662 return;
665 $modulename = get_string('modulename', $event->modulename);
666 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
667 // will be used as alt text if the event icon
668 $eventtype = get_string($event->eventtype, $event->modulename);
669 } else {
670 $eventtype = '';
672 $icon = $OUTPUT->pix_url('icon', $event->modulename) . '';
674 $event->icon = '<img src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" class="icon" />';
675 $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
676 $event->courselink = calendar_get_courselink($module->course);
677 $event->cmid = $module->id;
679 } else if($event->courseid == SITEID) { // Site event
680 $event->icon = '<img src="'.$OUTPUT->pix_url('i/siteevent') . '" alt="'.get_string('globalevent', 'calendar').'" class="icon" />';
681 $event->cssclass = 'calendar_event_global';
682 } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
683 $event->icon = '<img src="'.$OUTPUT->pix_url('i/courseevent') . '" alt="'.get_string('courseevent', 'calendar').'" class="icon" />';
684 $event->courselink = calendar_get_courselink($event->courseid);
685 $event->cssclass = 'calendar_event_course';
686 } else if ($event->groupid) { // Group event
687 $event->icon = '<img src="'.$OUTPUT->pix_url('i/groupevent') . '" alt="'.get_string('groupevent', 'calendar').'" class="icon" />';
688 $event->courselink = calendar_get_courselink($event->courseid);
689 $event->cssclass = 'calendar_event_group';
690 } else if($event->userid) { // User event
691 $event->icon = '<img src="'.$OUTPUT->pix_url('i/userevent') . '" alt="'.get_string('userevent', 'calendar').'" class="icon" />';
692 $event->cssclass = 'calendar_event_user';
694 return $event;
698 * Get calendar events
700 * @param int $tstart Start time of time range for events
701 * @param int $tend End time of time range for events
702 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
703 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
704 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
705 * @param boolean $withduration whether only events starting within time range selected
706 * or events in progress/already started selected as well
707 * @param boolean $ignorehidden whether to select only visible events or all events
708 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
710 function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
711 global $DB;
713 $whereclause = '';
714 // Quick test
715 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
716 return array();
719 if(is_array($users) && !empty($users)) {
720 // Events from a number of users
721 if(!empty($whereclause)) $whereclause .= ' OR';
722 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
723 } else if(is_numeric($users)) {
724 // Events from one user
725 if(!empty($whereclause)) $whereclause .= ' OR';
726 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
727 } else if($users === true) {
728 // Events from ALL users
729 if(!empty($whereclause)) $whereclause .= ' OR';
730 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
731 } else if($users === false) {
732 // No user at all, do nothing
735 if(is_array($groups) && !empty($groups)) {
736 // Events from a number of groups
737 if(!empty($whereclause)) $whereclause .= ' OR';
738 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
739 } else if(is_numeric($groups)) {
740 // Events from one group
741 if(!empty($whereclause)) $whereclause .= ' OR ';
742 $whereclause .= ' groupid = '.$groups;
743 } else if($groups === true) {
744 // Events from ALL groups
745 if(!empty($whereclause)) $whereclause .= ' OR ';
746 $whereclause .= ' groupid != 0';
748 // boolean false (no groups at all): we don't need to do anything
750 if(is_array($courses) && !empty($courses)) {
751 if(!empty($whereclause)) {
752 $whereclause .= ' OR';
754 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
755 } else if(is_numeric($courses)) {
756 // One course
757 if(!empty($whereclause)) $whereclause .= ' OR';
758 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
759 } else if ($courses === true) {
760 // Events from ALL courses
761 if(!empty($whereclause)) $whereclause .= ' OR';
762 $whereclause .= ' (groupid = 0 AND courseid != 0)';
765 // Security check: if, by now, we have NOTHING in $whereclause, then it means
766 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
767 // events no matter what. Allowing the code to proceed might return a completely
768 // valid query with only time constraints, thus selecting ALL events in that time frame!
769 if(empty($whereclause)) {
770 return array();
773 if($withduration) {
774 $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
776 else {
777 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
779 if(!empty($whereclause)) {
780 // We have additional constraints
781 $whereclause = $timeclause.' AND ('.$whereclause.')';
783 else {
784 // Just basic time filtering
785 $whereclause = $timeclause;
788 if ($ignorehidden) {
789 $whereclause .= ' AND visible = 1';
792 $events = $DB->get_records_select('event', $whereclause, null, 'timestart');
793 if ($events === false) {
794 $events = array();
796 return $events;
799 /** Get calendar events by id
801 * @since Moodle 2.5
802 * @param array $eventids list of event ids
803 * @return array Array of event entries, empty array if nothing found
806 function calendar_get_events_by_id($eventids) {
807 global $DB;
809 if (!is_array($eventids) || empty($eventids)) {
810 return array();
812 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
813 $wheresql = "id $wheresql";
815 return $DB->get_records_select('event', $wheresql, $params);
819 * Get control options for Calendar
821 * @param string $type of calendar
822 * @param array $data calendar information
823 * @return string $content return available control for the calender in html
825 function calendar_top_controls($type, $data) {
826 global $CFG, $PAGE;
827 $content = '';
828 if(!isset($data['d'])) {
829 $data['d'] = 1;
832 // Ensure course id passed if relevant
833 // Required due to changes in view/lib.php mainly (calendar_session_vars())
834 $courseid = '';
835 if (!empty($data['id'])) {
836 $courseid = '&amp;course='.$data['id'];
839 if(!checkdate($data['m'], $data['d'], $data['y'])) {
840 $time = time();
842 else {
843 $time = make_timestamp($data['y'], $data['m'], $data['d']);
845 $date = usergetdate($time);
847 $data['m'] = $date['mon'];
848 $data['y'] = $date['year'];
849 $urlbase = $PAGE->url;
851 //Accessibility: calendar block controls, replaced <table> with <div>.
852 //$nexttext = link_arrow_right(get_string('monthnext', 'access'), $url='', $accesshide=true);
853 //$prevtext = link_arrow_left(get_string('monthprev', 'access'), $url='', $accesshide=true);
855 switch($type) {
856 case 'frontpage':
857 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
858 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
859 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, 0, $nextmonth, $nextyear, true);
860 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, 0, $prevmonth, $prevyear, true);
862 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
863 if (!empty($data['id'])) {
864 $calendarlink->param('course', $data['id']);
867 if (right_to_left()) {
868 $left = $nextlink;
869 $right = $prevlink;
870 } else {
871 $left = $prevlink;
872 $right = $nextlink;
875 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
876 $content .= $left.'<span class="hide"> | </span>';
877 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
878 $content .= '<span class="hide"> | </span>'. $right;
879 $content .= "<span class=\"clearer\"><!-- --></span>\n";
880 $content .= html_writer::end_tag('div');
882 break;
883 case 'course':
884 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
885 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
886 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, 0, $nextmonth, $nextyear, true);
887 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, 0, $prevmonth, $prevyear, true);
889 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
890 if (!empty($data['id'])) {
891 $calendarlink->param('course', $data['id']);
894 if (right_to_left()) {
895 $left = $nextlink;
896 $right = $prevlink;
897 } else {
898 $left = $prevlink;
899 $right = $nextlink;
902 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
903 $content .= $left.'<span class="hide"> | </span>';
904 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
905 $content .= '<span class="hide"> | </span>'. $right;
906 $content .= "<span class=\"clearer\"><!-- --></span>";
907 $content .= html_writer::end_tag('div');
908 break;
909 case 'upcoming':
910 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'upcoming')), 1, $data['m'], $data['y']);
911 if (!empty($data['id'])) {
912 $calendarlink->param('course', $data['id']);
914 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
915 $content .= html_writer::tag('div', $calendarlink, array('class'=>'centered'));
916 break;
917 case 'display':
918 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
919 if (!empty($data['id'])) {
920 $calendarlink->param('course', $data['id']);
922 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
923 $content .= html_writer::tag('h3', $calendarlink);
924 break;
925 case 'month':
926 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
927 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
928 $prevdate = make_timestamp($prevyear, $prevmonth, 1);
929 $nextdate = make_timestamp($nextyear, $nextmonth, 1);
930 $prevlink = calendar_get_link_previous(userdate($prevdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $prevmonth, $prevyear);
931 $nextlink = calendar_get_link_next(userdate($nextdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $nextmonth, $nextyear);
933 if (right_to_left()) {
934 $left = $nextlink;
935 $right = $prevlink;
936 } else {
937 $left = $prevlink;
938 $right = $nextlink;
941 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
942 $content .= $left . '<span class="hide"> | </span><h1 class="current">'.userdate($time, get_string('strftimemonthyear'))."</h1>";
943 $content .= '<span class="hide"> | </span>' . $right;
944 $content .= '<span class="clearer"><!-- --></span>';
945 $content .= html_writer::end_tag('div')."\n";
946 break;
947 case 'day':
948 $days = calendar_get_days();
949 $data['d'] = $date['mday']; // Just for convenience
950 $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
951 $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] + 1));
952 $prevname = calendar_wday_name($days[$prevdate['wday']]);
953 $nextname = calendar_wday_name($days[$nextdate['wday']]);
954 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&amp;', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
955 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&amp;', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);
957 if (right_to_left()) {
958 $left = $nextlink;
959 $right = $prevlink;
960 } else {
961 $left = $prevlink;
962 $right = $nextlink;
965 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
966 $content .= $left;
967 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimedaydate')).'</span>';
968 $content .= '<span class="hide"> | </span>'. $right;
969 $content .= "<span class=\"clearer\"><!-- --></span>";
970 $content .= html_writer::end_tag('div')."\n";
972 break;
974 return $content;
978 * Formats a filter control element.
980 * @param moodle_url $url of the filter
981 * @param int $type constant defining the type filter
982 * @return string html content of the element
984 function calendar_filter_controls_element(moodle_url $url, $type) {
985 global $OUTPUT;
986 switch ($type) {
987 case CALENDAR_EVENT_GLOBAL:
988 $typeforhumans = 'global';
989 $class = 'calendar_event_global';
990 break;
991 case CALENDAR_EVENT_COURSE:
992 $typeforhumans = 'course';
993 $class = 'calendar_event_course';
994 break;
995 case CALENDAR_EVENT_GROUP:
996 $typeforhumans = 'groups';
997 $class = 'calendar_event_group';
998 break;
999 case CALENDAR_EVENT_USER:
1000 $typeforhumans = 'user';
1001 $class = 'calendar_event_user';
1002 break;
1004 if (calendar_show_event_type($type)) {
1005 $icon = $OUTPUT->pix_icon('t/hide', get_string('hide'));
1006 $str = get_string('hide'.$typeforhumans.'events', 'calendar');
1007 } else {
1008 $icon = $OUTPUT->pix_icon('t/show', get_string('show'));
1009 $str = get_string('show'.$typeforhumans.'events', 'calendar');
1011 $content = html_writer::start_tag('li', array('class' => 'calendar_event'));
1012 $content .= html_writer::start_tag('a', array('href' => $url));
1013 $content .= html_writer::tag('span', $icon, array('class' => $class));
1014 $content .= html_writer::tag('span', $str, array('class' => 'eventname'));
1015 $content .= html_writer::end_tag('a');
1016 $content .= html_writer::end_tag('li');
1017 return $content;
1021 * Get the controls filter for calendar.
1023 * Filter is used to hide calendar info from the display page
1025 * @param moodle_url $returnurl return-url for filter controls
1026 * @return string $content return filter controls in html
1028 function calendar_filter_controls(moodle_url $returnurl) {
1029 global $CFG, $USER, $OUTPUT;
1031 $groupevents = true;
1032 $id = optional_param( 'id',0,PARAM_INT );
1033 $seturl = new moodle_url('/calendar/set.php', array('return' => base64_encode($returnurl->out(false)), 'sesskey'=>sesskey()));
1034 $content = html_writer::start_tag('ul');
1036 $seturl->param('var', 'showglobal');
1037 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GLOBAL);
1039 $seturl->param('var', 'showcourses');
1040 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_COURSE);
1042 if (isloggedin() && !isguestuser()) {
1043 if ($groupevents) {
1044 // This course MIGHT have group events defined, so show the filter
1045 $seturl->param('var', 'showgroups');
1046 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GROUP);
1047 } else {
1048 // This course CANNOT have group events, so lose the filter
1050 $seturl->param('var', 'showuser');
1051 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_USER);
1053 $content .= html_writer::end_tag('ul');
1055 return $content;
1059 * Return the representation day
1061 * @param int $tstamp Timestamp in GMT
1062 * @param int $now current Unix timestamp
1063 * @param bool $usecommonwords
1064 * @return string the formatted date/time
1066 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1068 static $shortformat;
1069 if(empty($shortformat)) {
1070 $shortformat = get_string('strftimedayshort');
1073 if($now === false) {
1074 $now = time();
1077 // To have it in one place, if a change is needed
1078 $formal = userdate($tstamp, $shortformat);
1080 $datestamp = usergetdate($tstamp);
1081 $datenow = usergetdate($now);
1083 if($usecommonwords == false) {
1084 // We don't want words, just a date
1085 return $formal;
1087 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1088 // Today
1089 return get_string('today', 'calendar');
1091 else if(
1092 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1093 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
1095 // Yesterday
1096 return get_string('yesterday', 'calendar');
1098 else if(
1099 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1100 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
1102 // Tomorrow
1103 return get_string('tomorrow', 'calendar');
1105 else {
1106 return $formal;
1111 * return the formatted representation time
1113 * @param int $time the timestamp in UTC, as obtained from the database
1114 * @return string the formatted date/time
1116 function calendar_time_representation($time) {
1117 static $langtimeformat = NULL;
1118 if($langtimeformat === NULL) {
1119 $langtimeformat = get_string('strftimetime');
1121 $timeformat = get_user_preferences('calendar_timeformat');
1122 if(empty($timeformat)){
1123 $timeformat = get_config(NULL,'calendar_site_timeformat');
1125 // The ? is needed because the preference might be present, but empty
1126 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
1130 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1132 * @param string|moodle_url $linkbase
1133 * @param int $d The number of the day.
1134 * @param int $m The number of the month.
1135 * @param int $y The number of the year.
1136 * @return moodle_url|null $linkbase
1138 function calendar_get_link_href($linkbase, $d, $m, $y) {
1139 if (empty($linkbase)) {
1140 return '';
1142 if (!($linkbase instanceof moodle_url)) {
1143 $linkbase = new moodle_url($linkbase);
1145 if (!empty($d)) {
1146 $linkbase->param('cal_d', $d);
1148 if (!empty($m)) {
1149 $linkbase->param('cal_m', $m);
1151 if (!empty($y)) {
1152 $linkbase->param('cal_y', $y);
1154 return $linkbase;
1158 * Build and return a previous month HTML link, with an arrow.
1160 * @param string $text The text label.
1161 * @param string|moodle_url $linkbase The URL stub.
1162 * @param int $d The number of the date.
1163 * @param int $m The number of the month.
1164 * @param int $y year The number of the year.
1165 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1166 * @return string HTML string.
1168 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide=false) {
1169 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1170 if (empty($href)) {
1171 return $text;
1173 return link_arrow_left($text, (string)$href, $accesshide, 'previous');
1177 * Build and return a next month HTML link, with an arrow.
1179 * @param string $text The text label.
1180 * @param string|moodle_url $linkbase The URL stub.
1181 * @param int $d the number of the Day
1182 * @param int $m The number of the month.
1183 * @param int $y The number of the year.
1184 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1185 * @return string HTML string.
1187 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide=false) {
1188 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1189 if (empty($href)) {
1190 return $text;
1192 return link_arrow_right($text, (string)$href, $accesshide, 'next');
1196 * Return the name of the weekday
1198 * @param string $englishname
1199 * @return string of the weekeday
1201 function calendar_wday_name($englishname) {
1202 return get_string(strtolower($englishname), 'calendar');
1206 * Return the number of days in month
1208 * @param int $month the number of the month.
1209 * @param int $year the number of the year
1210 * @return int
1212 function calendar_days_in_month($month, $year) {
1213 return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
1217 * Get the upcoming event block
1219 * @param array $events list of events
1220 * @param moodle_url|string $linkhref link to event referer
1221 * @param boolean $showcourselink whether links to courses should be shown
1222 * @return string|null $content html block content
1224 function calendar_get_block_upcoming($events, $linkhref = NULL, $showcourselink = false) {
1225 $content = '';
1226 $lines = count($events);
1227 if (!$lines) {
1228 return $content;
1231 for ($i = 0; $i < $lines; ++$i) {
1232 if (!isset($events[$i]->time)) { // Just for robustness
1233 continue;
1235 $events[$i] = calendar_add_event_metadata($events[$i]);
1236 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span>';
1237 if (!empty($events[$i]->referer)) {
1238 // That's an activity event, so let's provide the hyperlink
1239 $content .= $events[$i]->referer;
1240 } else {
1241 if(!empty($linkhref)) {
1242 $ed = usergetdate($events[$i]->timestart);
1243 $href = calendar_get_link_href(new moodle_url(CALENDAR_URL.$linkhref), $ed['mday'], $ed['mon'], $ed['year']);
1244 $href->set_anchor('event_'.$events[$i]->id);
1245 $content .= html_writer::link($href, $events[$i]->name);
1247 else {
1248 $content .= $events[$i]->name;
1251 $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
1252 if ($showcourselink && !empty($events[$i]->courselink)) {
1253 $content .= html_writer::div($events[$i]->courselink, 'course');
1255 $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
1256 if ($i < $lines - 1) $content .= '<hr />';
1259 return $content;
1263 * Get the next following month
1265 * If the current month is December, it will get the first month of the following year.
1268 * @param int $month the number of the month.
1269 * @param int $year the number of the year.
1270 * @return array the following month
1272 function calendar_add_month($month, $year) {
1273 if($month == 12) {
1274 return array(1, $year + 1);
1276 else {
1277 return array($month + 1, $year);
1282 * Get the previous month
1284 * If the current month is January, it will get the last month of the previous year.
1286 * @param int $month the number of the month.
1287 * @param int $year the number of the year.
1288 * @return array previous month
1290 function calendar_sub_month($month, $year) {
1291 if($month == 1) {
1292 return array(12, $year - 1);
1294 else {
1295 return array($month - 1, $year);
1300 * Get per-day basis events
1302 * @param array $events list of events
1303 * @param int $month the number of the month
1304 * @param int $year the number of the year
1305 * @param array $eventsbyday event on specific day
1306 * @param array $durationbyday duration of the event in days
1307 * @param array $typesbyday event type (eg: global, course, user, or group)
1308 * @param array $courses list of courses
1309 * @return void
1311 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1312 $eventsbyday = array();
1313 $typesbyday = array();
1314 $durationbyday = array();
1316 if($events === false) {
1317 return;
1320 foreach($events as $event) {
1322 $startdate = usergetdate($event->timestart);
1323 // Set end date = start date if no duration
1324 if ($event->timeduration) {
1325 $enddate = usergetdate($event->timestart + $event->timeduration - 1);
1326 } else {
1327 $enddate = $startdate;
1330 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
1331 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1332 // Out of bounds
1333 continue;
1336 $eventdaystart = intval($startdate['mday']);
1338 if($startdate['mon'] == $month && $startdate['year'] == $year) {
1339 // Give the event to its day
1340 $eventsbyday[$eventdaystart][] = $event->id;
1342 // Mark the day as having such an event
1343 if($event->courseid == SITEID && $event->groupid == 0) {
1344 $typesbyday[$eventdaystart]['startglobal'] = true;
1345 // Set event class for global event
1346 $events[$event->id]->class = 'calendar_event_global';
1348 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1349 $typesbyday[$eventdaystart]['startcourse'] = true;
1350 // Set event class for course event
1351 $events[$event->id]->class = 'calendar_event_course';
1353 else if($event->groupid) {
1354 $typesbyday[$eventdaystart]['startgroup'] = true;
1355 // Set event class for group event
1356 $events[$event->id]->class = 'calendar_event_group';
1358 else if($event->userid) {
1359 $typesbyday[$eventdaystart]['startuser'] = true;
1360 // Set event class for user event
1361 $events[$event->id]->class = 'calendar_event_user';
1365 if($event->timeduration == 0) {
1366 // Proceed with the next
1367 continue;
1370 // The event starts on $month $year or before. So...
1371 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
1373 // Also, it ends on $month $year or later...
1374 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
1376 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1377 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
1378 $durationbyday[$i][] = $event->id;
1379 if($event->courseid == SITEID && $event->groupid == 0) {
1380 $typesbyday[$i]['durationglobal'] = true;
1382 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1383 $typesbyday[$i]['durationcourse'] = true;
1385 else if($event->groupid) {
1386 $typesbyday[$i]['durationgroup'] = true;
1388 else if($event->userid) {
1389 $typesbyday[$i]['durationuser'] = true;
1394 return;
1398 * Get current module cache
1400 * @param array $coursecache list of course cache
1401 * @param string $modulename name of the module
1402 * @param int $instance module instance number
1403 * @return stdClass|bool $module information
1405 function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1406 $module = get_coursemodule_from_instance($modulename, $instance);
1408 if($module === false) return false;
1409 if(!calendar_get_course_cached($coursecache, $module->course)) {
1410 return false;
1412 return $module;
1416 * Get current course cache
1418 * @param array $coursecache list of course cache
1419 * @param int $courseid id of the course
1420 * @return stdClass $coursecache[$courseid] return the specific course cache
1422 function calendar_get_course_cached(&$coursecache, $courseid) {
1423 if (!isset($coursecache[$courseid])) {
1424 $coursecache[$courseid] = get_course($courseid);
1426 return $coursecache[$courseid];
1430 * Returns the courses to load events for, the
1432 * @param array $courseeventsfrom An array of courses to load calendar events for
1433 * @param bool $ignorefilters specify the use of filters, false is set as default
1434 * @return array An array of courses, groups, and user to load calendar events for based upon filters
1436 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
1437 global $USER, $CFG, $DB;
1439 // For backwards compatability we have to check whether the courses array contains
1440 // just id's in which case we need to load course objects.
1441 $coursestoload = array();
1442 foreach ($courseeventsfrom as $id => $something) {
1443 if (!is_object($something)) {
1444 $coursestoload[] = $id;
1445 unset($courseeventsfrom[$id]);
1448 if (!empty($coursestoload)) {
1449 // TODO remove this in 2.2
1450 debugging('calendar_set_filters now preferes an array of course objects with preloaded contexts', DEBUG_DEVELOPER);
1451 $courseeventsfrom = array_merge($courseeventsfrom, $DB->get_records_list('course', 'id', $coursestoload));
1454 $courses = array();
1455 $user = false;
1456 $group = false;
1458 // capabilities that allow seeing group events from all groups
1459 // TODO: rewrite so that moodle/calendar:manageentries is not necessary here
1460 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
1462 $isloggedin = isloggedin();
1464 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
1465 $courses = array_keys($courseeventsfrom);
1467 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
1468 $courses[] = SITEID;
1470 $courses = array_unique($courses);
1471 sort($courses);
1473 if (!empty($courses) && in_array(SITEID, $courses)) {
1474 // Sort courses for consistent colour highlighting
1475 // Effectively ignoring SITEID as setting as last course id
1476 $key = array_search(SITEID, $courses);
1477 unset($courses[$key]);
1478 $courses[] = SITEID;
1481 if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
1482 $user = $USER->id;
1485 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
1487 if (count($courseeventsfrom)==1) {
1488 $course = reset($courseeventsfrom);
1489 if (has_any_capability($allgroupscaps, context_course::instance($course->id))) {
1490 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
1491 $group = array_keys($coursegroups);
1494 if ($group === false) {
1495 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, context_system::instance())) {
1496 $group = true;
1497 } else if ($isloggedin) {
1498 $groupids = array();
1500 // We already have the courses to examine in $courses
1501 // For each course...
1502 foreach ($courseeventsfrom as $courseid => $course) {
1503 // If the user is an editing teacher in there,
1504 if (!empty($USER->groupmember[$course->id])) {
1505 // We've already cached the users groups for this course so we can just use that
1506 $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
1507 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1508 // If this course has groups, show events from all of those related to the current user
1509 $coursegroups = groups_get_user_groups($course->id, $USER->id);
1510 $groupids = array_merge($groupids, $coursegroups['0']);
1513 if (!empty($groupids)) {
1514 $group = $groupids;
1519 if (empty($courses)) {
1520 $courses = false;
1523 return array($courses, $group, $user);
1527 * Return the capability for editing calendar event
1529 * @param calendar_event $event event object
1530 * @return bool capability to edit event
1532 function calendar_edit_event_allowed($event) {
1533 global $USER, $DB;
1535 // Must be logged in
1536 if (!isloggedin()) {
1537 return false;
1540 // can not be using guest account
1541 if (isguestuser()) {
1542 return false;
1545 // You cannot edit calendar subscription events presently.
1546 if (!empty($event->subscriptionid)) {
1547 return false;
1550 $sitecontext = context_system::instance();
1551 // if user has manageentries at site level, return true
1552 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1553 return true;
1556 // if groupid is set, it's definitely a group event
1557 if (!empty($event->groupid)) {
1558 // Allow users to add/edit group events if:
1559 // 1) They have manageentries (= entries for whole course)
1560 // 2) They have managegroupentries AND are in the group
1561 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1562 return $group && (
1563 has_capability('moodle/calendar:manageentries', $event->context) ||
1564 (has_capability('moodle/calendar:managegroupentries', $event->context)
1565 && groups_is_member($event->groupid)));
1566 } else if (!empty($event->courseid)) {
1567 // if groupid is not set, but course is set,
1568 // it's definiely a course event
1569 return has_capability('moodle/calendar:manageentries', $event->context);
1570 } else if (!empty($event->userid) && $event->userid == $USER->id) {
1571 // if course is not set, but userid id set, it's a user event
1572 return (has_capability('moodle/calendar:manageownentries', $event->context));
1573 } else if (!empty($event->userid)) {
1574 return (has_capability('moodle/calendar:manageentries', $event->context));
1576 return false;
1580 * Returns the default courses to display on the calendar when there isn't a specific
1581 * course to display.
1583 * @return array $courses Array of courses to display
1585 function calendar_get_default_courses() {
1586 global $CFG, $DB;
1588 if (!isloggedin()) {
1589 return array();
1592 $courses = array();
1593 if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', context_system::instance())) {
1594 $select = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1595 $join = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1596 $sql = "SELECT c.* $select
1597 FROM {course} c
1598 $join
1599 WHERE EXISTS (SELECT 1 FROM {event} e WHERE e.courseid = c.id)
1601 $courses = $DB->get_records_sql($sql, array('contextlevel' => CONTEXT_COURSE), 0, 20);
1602 foreach ($courses as $course) {
1603 context_helper::preload_from_record($course);
1605 return $courses;
1608 $courses = enrol_get_my_courses();
1610 return $courses;
1614 * Display calendar preference button
1616 * @param stdClass $course course object
1617 * @return string return preference button in html
1619 function calendar_preferences_button(stdClass $course) {
1620 global $OUTPUT;
1622 // Guests have no preferences
1623 if (!isloggedin() || isguestuser()) {
1624 return '';
1627 return $OUTPUT->single_button(new moodle_url('/calendar/preferences.php', array('course' => $course->id)), get_string("preferences", "calendar"));
1631 * Get event format time
1633 * @param calendar_event $event event object
1634 * @param int $now current time in gmt
1635 * @param array $linkparams list of params for event link
1636 * @param bool $usecommonwords the words as formatted date/time.
1637 * @param int $showtime determine the show time GMT timestamp
1638 * @return string $eventtime link/string for event time
1640 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime=0) {
1641 $startdate = usergetdate($event->timestart);
1642 $enddate = usergetdate($event->timestart + $event->timeduration);
1643 $usermidnightstart = usergetmidnight($event->timestart);
1645 if($event->timeduration) {
1646 // To avoid doing the math if one IF is enough :)
1647 $usermidnightend = usergetmidnight($event->timestart + $event->timeduration);
1649 else {
1650 $usermidnightend = $usermidnightstart;
1653 if (empty($linkparams) || !is_array($linkparams)) {
1654 $linkparams = array();
1656 $linkparams['view'] = 'day';
1658 // OK, now to get a meaningful display...
1659 // First of all we have to construct a human-readable date/time representation
1661 if($event->timeduration) {
1662 // It has a duration
1663 if($usermidnightstart == $usermidnightend ||
1664 ($event->timestart == $usermidnightstart) && ($event->timeduration == 86400 || $event->timeduration == 86399) ||
1665 ($event->timestart + $event->timeduration <= $usermidnightstart + 86400)) {
1666 // But it's all on the same day
1667 $timestart = calendar_time_representation($event->timestart);
1668 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1669 $time = $timestart.' <strong>&raquo;</strong> '.$timeend;
1671 if ($event->timestart == $usermidnightstart && ($event->timeduration == 86400 || $event->timeduration == 86399)) {
1672 $time = get_string('allday', 'calendar');
1675 // Set printable representation
1676 if (!$showtime) {
1677 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1678 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1679 $eventtime = html_writer::link($url, $day).', '.$time;
1680 } else {
1681 $eventtime = $time;
1683 } else {
1684 // It spans two or more days
1685 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords).', ';
1686 if ($showtime == $usermidnightstart) {
1687 $daystart = '';
1689 $timestart = calendar_time_representation($event->timestart);
1690 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords).', ';
1691 if ($showtime == $usermidnightend) {
1692 $dayend = '';
1694 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1696 // Set printable representation
1697 if ($now >= $usermidnightstart && $now < ($usermidnightstart + 86400)) {
1698 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1699 $eventtime = $timestart.' <strong>&raquo;</strong> '.html_writer::link($url, $dayend).$timeend;
1700 } else {
1701 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1702 $eventtime = html_writer::link($url, $daystart).$timestart.' <strong>&raquo;</strong> ';
1704 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1705 $eventtime .= html_writer::link($url, $dayend).$timeend;
1708 } else {
1709 $time = calendar_time_representation($event->timestart);
1711 // Set printable representation
1712 if (!$showtime) {
1713 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1714 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1715 $eventtime = html_writer::link($url, $day).', '.trim($time);
1716 } else {
1717 $eventtime = $time;
1721 if($event->timestart + $event->timeduration < $now) {
1722 // It has expired
1723 $eventtime = '<span class="dimmed_text">'.str_replace(' href=', ' class="dimmed" href=', $eventtime).'</span>';
1726 return $eventtime;
1730 * Display month selector options
1732 * @param string $name for the select element
1733 * @param string|array $selected options for select elements
1735 function calendar_print_month_selector($name, $selected) {
1736 $months = array();
1737 for ($i=1; $i<=12; $i++) {
1738 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
1740 echo html_writer::label(get_string('months'), 'menu'. $name, false, array('class' => 'accesshide'));
1741 echo html_writer::select($months, $name, $selected, false);
1745 * Checks to see if the requested type of event should be shown for the given user.
1747 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
1748 * The type to check the display for (default is to display all)
1749 * @param stdClass|int|null $user The user to check for - by default the current user
1750 * @return bool True if the tyep should be displayed false otherwise
1752 function calendar_show_event_type($type, $user = null) {
1753 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1754 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
1755 global $SESSION;
1756 if (!isset($SESSION->calendarshoweventtype)) {
1757 $SESSION->calendarshoweventtype = $default;
1759 return $SESSION->calendarshoweventtype & $type;
1760 } else {
1761 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
1766 * Sets the display of the event type given $display.
1768 * If $display = true the event type will be shown.
1769 * If $display = false the event type will NOT be shown.
1770 * If $display = null the current value will be toggled and saved.
1772 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type object of CALENDAR_EVENT_XXX
1773 * @param bool $display option to display event type
1774 * @param stdClass|int $user moodle user object or id, null means current user
1776 function calendar_set_event_type_display($type, $display = null, $user = null) {
1777 $persist = get_user_preferences('calendar_persistflt', 0, $user);
1778 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1779 if ($persist === 0) {
1780 global $SESSION;
1781 if (!isset($SESSION->calendarshoweventtype)) {
1782 $SESSION->calendarshoweventtype = $default;
1784 $preference = $SESSION->calendarshoweventtype;
1785 } else {
1786 $preference = get_user_preferences('calendar_savedflt', $default, $user);
1788 $current = $preference & $type;
1789 if ($display === null) {
1790 $display = !$current;
1792 if ($display && !$current) {
1793 $preference += $type;
1794 } else if (!$display && $current) {
1795 $preference -= $type;
1797 if ($persist === 0) {
1798 $SESSION->calendarshoweventtype = $preference;
1799 } else {
1800 if ($preference == $default) {
1801 unset_user_preference('calendar_savedflt', $user);
1802 } else {
1803 set_user_preference('calendar_savedflt', $preference, $user);
1809 * Get calendar's allowed types
1811 * @param stdClass $allowed list of allowed edit for event type
1812 * @param stdClass|int $course object of a course or course id
1814 function calendar_get_allowed_types(&$allowed, $course = null) {
1815 global $USER, $CFG, $DB;
1816 $allowed = new stdClass();
1817 $allowed->user = has_capability('moodle/calendar:manageownentries', context_system::instance());
1818 $allowed->groups = false; // This may change just below
1819 $allowed->courses = false; // This may change just below
1820 $allowed->site = has_capability('moodle/calendar:manageentries', context_course::instance(SITEID));
1822 if (!empty($course)) {
1823 if (!is_object($course)) {
1824 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST);
1826 if ($course->id != SITEID) {
1827 $coursecontext = context_course::instance($course->id);
1828 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
1830 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
1831 $allowed->courses = array($course->id => 1);
1833 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1834 if (has_capability('moodle/site:accessallgroups', $coursecontext)) {
1835 $allowed->groups = groups_get_all_groups($course->id);
1836 } else {
1837 $allowed->groups = groups_get_all_groups($course->id, $USER->id);
1840 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
1841 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1842 if (has_capability('moodle/site:accessallgroups', $coursecontext)) {
1843 $allowed->groups = groups_get_all_groups($course->id);
1844 } else {
1845 $allowed->groups = groups_get_all_groups($course->id, $USER->id);
1854 * See if user can add calendar entries at all
1855 * used to print the "New Event" button
1857 * @param stdClass $course object of a course or course id
1858 * @return bool has the capability to add at least one event type
1860 function calendar_user_can_add_event($course) {
1861 if (!isloggedin() || isguestuser()) {
1862 return false;
1864 calendar_get_allowed_types($allowed, $course);
1865 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);
1869 * Check wether the current user is permitted to add events
1871 * @param stdClass $event object of event
1872 * @return bool has the capability to add event
1874 function calendar_add_event_allowed($event) {
1875 global $USER, $DB;
1877 // can not be using guest account
1878 if (!isloggedin() or isguestuser()) {
1879 return false;
1882 $sitecontext = context_system::instance();
1883 // if user has manageentries at site level, always return true
1884 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1885 return true;
1888 switch ($event->eventtype) {
1889 case 'course':
1890 return has_capability('moodle/calendar:manageentries', $event->context);
1892 case 'group':
1893 // Allow users to add/edit group events if:
1894 // 1) They have manageentries (= entries for whole course)
1895 // 2) They have managegroupentries AND are in the group
1896 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1897 return $group && (
1898 has_capability('moodle/calendar:manageentries', $event->context) ||
1899 (has_capability('moodle/calendar:managegroupentries', $event->context)
1900 && groups_is_member($event->groupid)));
1902 case 'user':
1903 if ($event->userid == $USER->id) {
1904 return (has_capability('moodle/calendar:manageownentries', $event->context));
1906 //there is no 'break;' intentionally
1908 case 'site':
1909 return has_capability('moodle/calendar:manageentries', $event->context);
1911 default:
1912 return has_capability('moodle/calendar:manageentries', $event->context);
1917 * Manage calendar events
1919 * This class provides the required functionality in order to manage calendar events.
1920 * It was introduced as part of Moodle 2.0 and was created in order to provide a
1921 * better framework for dealing with calendar events in particular regard to file
1922 * handling through the new file API
1924 * @package core_calendar
1925 * @category calendar
1926 * @copyright 2009 Sam Hemelryk
1927 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1929 * @property int $id The id within the event table
1930 * @property string $name The name of the event
1931 * @property string $description The description of the event
1932 * @property int $format The format of the description FORMAT_?
1933 * @property int $courseid The course the event is associated with (0 if none)
1934 * @property int $groupid The group the event is associated with (0 if none)
1935 * @property int $userid The user the event is associated with (0 if none)
1936 * @property int $repeatid If this is a repeated event this will be set to the
1937 * id of the original
1938 * @property string $modulename If added by a module this will be the module name
1939 * @property int $instance If added by a module this will be the module instance
1940 * @property string $eventtype The event type
1941 * @property int $timestart The start time as a timestamp
1942 * @property int $timeduration The duration of the event in seconds
1943 * @property int $visible 1 if the event is visible
1944 * @property int $uuid ?
1945 * @property int $sequence ?
1946 * @property int $timemodified The time last modified as a timestamp
1948 class calendar_event {
1950 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
1951 protected $properties = null;
1954 * @var string The converted event discription with file paths resolved. This gets populated when someone requests description for the first time */
1955 protected $_description = null;
1957 /** @var array The options to use with this description editor */
1958 protected $editoroptions = array(
1959 'subdirs'=>false,
1960 'forcehttps'=>false,
1961 'maxfiles'=>-1,
1962 'maxbytes'=>null,
1963 'trusttext'=>false);
1965 /** @var object The context to use with the description editor */
1966 protected $editorcontext = null;
1969 * Instantiates a new event and optionally populates its properties with the
1970 * data provided
1972 * @param stdClass $data Optional. An object containing the properties to for
1973 * an event
1975 public function __construct($data=null) {
1976 global $CFG, $USER;
1978 // First convert to object if it is not already (should either be object or assoc array)
1979 if (!is_object($data)) {
1980 $data = (object)$data;
1983 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
1985 $data->eventrepeats = 0;
1987 if (empty($data->id)) {
1988 $data->id = null;
1991 if (!empty($data->subscriptionid)) {
1992 $data->subscription = calendar_get_subscription($data->subscriptionid);
1995 // Default to a user event
1996 if (empty($data->eventtype)) {
1997 $data->eventtype = 'user';
2000 // Default to the current user
2001 if (empty($data->userid)) {
2002 $data->userid = $USER->id;
2005 if (!empty($data->timeduration) && is_array($data->timeduration)) {
2006 $data->timeduration = make_timestamp($data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'], $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
2008 if (!empty($data->description) && is_array($data->description)) {
2009 $data->format = $data->description['format'];
2010 $data->description = $data->description['text'];
2011 } else if (empty($data->description)) {
2012 $data->description = '';
2013 $data->format = editors_get_preferred_format();
2015 // Ensure form is defaulted correctly
2016 if (empty($data->format)) {
2017 $data->format = editors_get_preferred_format();
2020 if (empty($data->context)) {
2021 $data->context = $this->calculate_context($data);
2023 $this->properties = $data;
2027 * Magic property method
2029 * Attempts to call a set_$key method if one exists otherwise falls back
2030 * to simply set the property
2032 * @param string $key property name
2033 * @param mixed $value value of the property
2035 public function __set($key, $value) {
2036 if (method_exists($this, 'set_'.$key)) {
2037 $this->{'set_'.$key}($value);
2039 $this->properties->{$key} = $value;
2043 * Magic get method
2045 * Attempts to call a get_$key method to return the property and ralls over
2046 * to return the raw property
2048 * @param string $key property name
2049 * @return mixed property value
2051 public function __get($key) {
2052 if (method_exists($this, 'get_'.$key)) {
2053 return $this->{'get_'.$key}();
2055 if (!isset($this->properties->{$key})) {
2056 throw new coding_exception('Undefined property requested');
2058 return $this->properties->{$key};
2062 * Stupid PHP needs an isset magic method if you use the get magic method and
2063 * still want empty calls to work.... blah ~!
2065 * @param string $key $key property name
2066 * @return bool|mixed property value, false if property is not exist
2068 public function __isset($key) {
2069 return !empty($this->properties->{$key});
2073 * Calculate the context value needed for calendar_event.
2074 * Event's type can be determine by the available value store in $data
2075 * It is important to check for the existence of course/courseid to determine
2076 * the course event.
2077 * Default value is set to CONTEXT_USER
2079 * @param stdClass $data information about event
2080 * @return stdClass The context object.
2082 protected function calculate_context(stdClass $data) {
2083 global $USER, $DB;
2085 $context = null;
2086 if (isset($data->courseid) && $data->courseid > 0) {
2087 $context = context_course::instance($data->courseid);
2088 } else if (isset($data->course) && $data->course > 0) {
2089 $context = context_course::instance($data->course);
2090 } else if (isset($data->groupid) && $data->groupid > 0) {
2091 $group = $DB->get_record('groups', array('id'=>$data->groupid));
2092 $context = context_course::instance($group->courseid);
2093 } else if (isset($data->userid) && $data->userid > 0 && $data->userid == $USER->id) {
2094 $context = context_user::instance($data->userid);
2095 } else if (isset($data->userid) && $data->userid > 0 && $data->userid != $USER->id &&
2096 isset($data->instance) && $data->instance > 0) {
2097 $cm = get_coursemodule_from_instance($data->modulename, $data->instance, 0, false, MUST_EXIST);
2098 $context = context_course::instance($cm->course);
2099 } else {
2100 $context = context_user::instance($data->userid);
2103 return $context;
2107 * Returns an array of editoroptions for this event: Called by __get
2108 * Please use $blah = $event->editoroptions;
2110 * @return array event editor options
2112 protected function get_editoroptions() {
2113 return $this->editoroptions;
2117 * Returns an event description: Called by __get
2118 * Please use $blah = $event->description;
2120 * @return string event description
2122 protected function get_description() {
2123 global $CFG;
2125 require_once($CFG->libdir . '/filelib.php');
2127 if ($this->_description === null) {
2128 // Check if we have already resolved the context for this event
2129 if ($this->editorcontext === null) {
2130 // Switch on the event type to decide upon the appropriate context
2131 // to use for this event
2132 $this->editorcontext = $this->properties->context;
2133 if ($this->properties->eventtype != 'user' && $this->properties->eventtype != 'course'
2134 && $this->properties->eventtype != 'site' && $this->properties->eventtype != 'group') {
2135 return clean_text($this->properties->description, $this->properties->format);
2139 // Work out the item id for the editor, if this is a repeated event then the files will
2140 // be associated with the original
2141 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2142 $itemid = $this->properties->repeatid;
2143 } else {
2144 $itemid = $this->properties->id;
2147 // Convert file paths in the description so that things display correctly
2148 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php', $this->editorcontext->id, 'calendar', 'event_description', $itemid);
2149 // Clean the text so no nasties get through
2150 $this->_description = clean_text($this->_description, $this->properties->format);
2152 // Finally return the description
2153 return $this->_description;
2157 * Return the number of repeat events there are in this events series
2159 * @return int number of event repeated
2161 public function count_repeats() {
2162 global $DB;
2163 if (!empty($this->properties->repeatid)) {
2164 $this->properties->eventrepeats = $DB->count_records('event', array('repeatid'=>$this->properties->repeatid));
2165 // We don't want to count ourselves
2166 $this->properties->eventrepeats--;
2168 return $this->properties->eventrepeats;
2172 * Update or create an event within the database
2174 * Pass in a object containing the event properties and this function will
2175 * insert it into the database and deal with any associated files
2177 * @see add_event()
2178 * @see update_event()
2180 * @param stdClass $data object of event
2181 * @param bool $checkcapability if moodle should check calendar managing capability or not
2182 * @return bool event updated
2184 public function update($data, $checkcapability=true) {
2185 global $CFG, $DB, $USER;
2187 foreach ($data as $key=>$value) {
2188 $this->properties->$key = $value;
2191 $this->properties->timemodified = time();
2192 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
2194 if (empty($this->properties->id) || $this->properties->id < 1) {
2196 if ($checkcapability) {
2197 if (!calendar_add_event_allowed($this->properties)) {
2198 print_error('nopermissiontoupdatecalendar');
2202 if ($usingeditor) {
2203 switch ($this->properties->eventtype) {
2204 case 'user':
2205 $this->properties->courseid = 0;
2206 $this->properties->course = 0;
2207 $this->properties->groupid = 0;
2208 $this->properties->userid = $USER->id;
2209 break;
2210 case 'site':
2211 $this->properties->courseid = SITEID;
2212 $this->properties->course = SITEID;
2213 $this->properties->groupid = 0;
2214 $this->properties->userid = $USER->id;
2215 break;
2216 case 'course':
2217 $this->properties->groupid = 0;
2218 $this->properties->userid = $USER->id;
2219 break;
2220 case 'group':
2221 $this->properties->userid = $USER->id;
2222 break;
2223 default:
2224 // Ewww we should NEVER get here, but just incase we do lets
2225 // fail gracefully
2226 $usingeditor = false;
2227 break;
2230 // If we are actually using the editor, we recalculate the context because some default values
2231 // were set when calculate_context() was called from the constructor.
2232 if ($usingeditor) {
2233 $this->properties->context = $this->calculate_context($this->properties);
2234 $this->editorcontext = $this->properties->context;
2237 $editor = $this->properties->description;
2238 $this->properties->format = $this->properties->description['format'];
2239 $this->properties->description = $this->properties->description['text'];
2242 // Insert the event into the database
2243 $this->properties->id = $DB->insert_record('event', $this->properties);
2245 if ($usingeditor) {
2246 $this->properties->description = file_save_draft_area_files(
2247 $editor['itemid'],
2248 $this->editorcontext->id,
2249 'calendar',
2250 'event_description',
2251 $this->properties->id,
2252 $this->editoroptions,
2253 $editor['text'],
2254 $this->editoroptions['forcehttps']);
2255 $DB->set_field('event', 'description', $this->properties->description, array('id'=>$this->properties->id));
2258 // Log the event entry.
2259 add_to_log($this->properties->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2261 $repeatedids = array();
2263 if (!empty($this->properties->repeat)) {
2264 $this->properties->repeatid = $this->properties->id;
2265 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id'=>$this->properties->id));
2267 $eventcopy = clone($this->properties);
2268 unset($eventcopy->id);
2270 for($i = 1; $i < $eventcopy->repeats; $i++) {
2272 $eventcopy->timestart = ($eventcopy->timestart+WEEKSECS) + dst_offset_on($eventcopy->timestart) - dst_offset_on($eventcopy->timestart+WEEKSECS);
2274 // Get the event id for the log record.
2275 $eventcopyid = $DB->insert_record('event', $eventcopy);
2277 // If the context has been set delete all associated files
2278 if ($usingeditor) {
2279 $fs = get_file_storage();
2280 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
2281 foreach ($files as $file) {
2282 $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
2286 $repeatedids[] = $eventcopyid;
2287 // Log the event entry.
2288 add_to_log($eventcopy->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$eventcopyid, $eventcopy->name);
2292 // Hook for tracking added events
2293 self::calendar_event_hook('add_event', array($this->properties, $repeatedids));
2294 return true;
2295 } else {
2297 if ($checkcapability) {
2298 if(!calendar_edit_event_allowed($this->properties)) {
2299 print_error('nopermissiontoupdatecalendar');
2303 if ($usingeditor) {
2304 if ($this->editorcontext !== null) {
2305 $this->properties->description = file_save_draft_area_files(
2306 $this->properties->description['itemid'],
2307 $this->editorcontext->id,
2308 'calendar',
2309 'event_description',
2310 $this->properties->id,
2311 $this->editoroptions,
2312 $this->properties->description['text'],
2313 $this->editoroptions['forcehttps']);
2314 } else {
2315 $this->properties->format = $this->properties->description['format'];
2316 $this->properties->description = $this->properties->description['text'];
2320 $event = $DB->get_record('event', array('id'=>$this->properties->id));
2322 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
2324 if ($updaterepeated) {
2325 // Update all
2326 if ($this->properties->timestart != $event->timestart) {
2327 $timestartoffset = $this->properties->timestart - $event->timestart;
2328 $sql = "UPDATE {event}
2329 SET name = ?,
2330 description = ?,
2331 timestart = timestart + ?,
2332 timeduration = ?,
2333 timemodified = ?
2334 WHERE repeatid = ?";
2335 $params = array($this->properties->name, $this->properties->description, $timestartoffset, $this->properties->timeduration, time(), $event->repeatid);
2336 } else {
2337 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
2338 $params = array($this->properties->name, $this->properties->description, $this->properties->timeduration, time(), $event->repeatid);
2340 $DB->execute($sql, $params);
2342 // Log the event update.
2343 add_to_log($this->properties->courseid, 'calendar', 'edit all', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2344 } else {
2345 $DB->update_record('event', $this->properties);
2346 $event = calendar_event::load($this->properties->id);
2347 $this->properties = $event->properties();
2348 add_to_log($this->properties->courseid, 'calendar', 'edit', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2351 // Hook for tracking event updates
2352 self::calendar_event_hook('update_event', array($this->properties, $updaterepeated));
2353 return true;
2358 * Deletes an event and if selected an repeated events in the same series
2360 * This function deletes an event, any associated events if $deleterepeated=true,
2361 * and cleans up any files associated with the events.
2363 * @see delete_event()
2365 * @param bool $deleterepeated delete event repeatedly
2366 * @return bool succession of deleting event
2368 public function delete($deleterepeated=false) {
2369 global $DB;
2371 // If $this->properties->id is not set then something is wrong
2372 if (empty($this->properties->id)) {
2373 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
2374 return false;
2377 // Delete the event
2378 $DB->delete_records('event', array('id'=>$this->properties->id));
2380 // If we are deleting parent of a repeated event series, promote the next event in the series as parent
2381 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
2382 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC", array($this->properties->id), IGNORE_MULTIPLE);
2383 if (!empty($newparent)) {
2384 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?", array($newparent, $this->properties->id));
2385 // Get all records where the repeatid is the same as the event being removed
2386 $events = $DB->get_records('event', array('repeatid' => $newparent));
2387 // For each of the returned events trigger the event_update hook.
2388 foreach ($events as $event) {
2389 self::calendar_event_hook('update_event', array($event, false));
2394 // If the editor context hasn't already been set then set it now
2395 if ($this->editorcontext === null) {
2396 $this->editorcontext = $this->properties->context;
2399 // If the context has been set delete all associated files
2400 if ($this->editorcontext !== null) {
2401 $fs = get_file_storage();
2402 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
2403 foreach ($files as $file) {
2404 $file->delete();
2408 // Fire the event deleted hook
2409 self::calendar_event_hook('delete_event', array($this->properties->id, $deleterepeated));
2411 // If we need to delete repeated events then we will fetch them all and delete one by one
2412 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2413 // Get all records where the repeatid is the same as the event being removed
2414 $events = $DB->get_records('event', array('repeatid'=>$this->properties->repeatid));
2415 // For each of the returned events populate a calendar_event object and call delete
2416 // make sure the arg passed is false as we are already deleting all repeats
2417 foreach ($events as $event) {
2418 $event = new calendar_event($event);
2419 $event->delete(false);
2423 return true;
2427 * Fetch all event properties
2429 * This function returns all of the events properties as an object and optionally
2430 * can prepare an editor for the description field at the same time. This is
2431 * designed to work when the properties are going to be used to set the default
2432 * values of a moodle forms form.
2434 * @param bool $prepareeditor If set to true a editor is prepared for use with
2435 * the mforms editor element. (for description)
2436 * @return stdClass Object containing event properties
2438 public function properties($prepareeditor=false) {
2439 global $USER, $CFG, $DB;
2441 // First take a copy of the properties. We don't want to actually change the
2442 // properties or we'd forever be converting back and forwards between an
2443 // editor formatted description and not
2444 $properties = clone($this->properties);
2445 // Clean the description here
2446 $properties->description = clean_text($properties->description, $properties->format);
2448 // If set to true we need to prepare the properties for use with an editor
2449 // and prepare the file area
2450 if ($prepareeditor) {
2452 // We may or may not have a property id. If we do then we need to work
2453 // out the context so we can copy the existing files to the draft area
2454 if (!empty($properties->id)) {
2456 if ($properties->eventtype === 'site') {
2457 // Site context
2458 $this->editorcontext = $this->properties->context;
2459 } else if ($properties->eventtype === 'user') {
2460 // User context
2461 $this->editorcontext = $this->properties->context;
2462 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
2463 // First check the course is valid
2464 $course = $DB->get_record('course', array('id'=>$properties->courseid));
2465 if (!$course) {
2466 print_error('invalidcourse');
2468 // Course context
2469 $this->editorcontext = $this->properties->context;
2470 // We have a course and are within the course context so we had
2471 // better use the courses max bytes value
2472 $this->editoroptions['maxbytes'] = $course->maxbytes;
2473 } else {
2474 // If we get here we have a custom event type as used by some
2475 // modules. In this case the event will have been added by
2476 // code and we won't need the editor
2477 $this->editoroptions['maxbytes'] = 0;
2478 $this->editoroptions['maxfiles'] = 0;
2481 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
2482 $contextid = false;
2483 } else {
2484 // Get the context id that is what we really want
2485 $contextid = $this->editorcontext->id;
2487 } else {
2489 // If we get here then this is a new event in which case we don't need a
2490 // context as there is no existing files to copy to the draft area.
2491 $contextid = null;
2494 // If the contextid === false we don't support files so no preparing
2495 // a draft area
2496 if ($contextid !== false) {
2497 // Just encase it has already been submitted
2498 $draftiddescription = file_get_submitted_draft_itemid('description');
2499 // Prepare the draft area, this copies existing files to the draft area as well
2500 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar', 'event_description', $properties->id, $this->editoroptions, $properties->description);
2501 } else {
2502 $draftiddescription = 0;
2505 // Structure the description field as the editor requires
2506 $properties->description = array('text'=>$properties->description, 'format'=>$properties->format, 'itemid'=>$draftiddescription);
2509 // Finally return the properties
2510 return $properties;
2514 * Toggles the visibility of an event
2516 * @param null|bool $force If it is left null the events visibility is flipped,
2517 * If it is false the event is made hidden, if it is true it
2518 * is made visible.
2519 * @return bool if event is successfully updated, toggle will be visible
2521 public function toggle_visibility($force=null) {
2522 global $CFG, $DB;
2524 // Set visible to the default if it is not already set
2525 if (empty($this->properties->visible)) {
2526 $this->properties->visible = 1;
2529 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
2530 // Make this event visible
2531 $this->properties->visible = 1;
2532 // Fire the hook
2533 self::calendar_event_hook('show_event', array($this->properties));
2534 } else {
2535 // Make this event hidden
2536 $this->properties->visible = 0;
2537 // Fire the hook
2538 self::calendar_event_hook('hide_event', array($this->properties));
2541 // Update the database to reflect this change
2542 return $DB->set_field('event', 'visible', $this->properties->visible, array('id'=>$this->properties->id));
2546 * Attempts to call the hook for the specified action should a calendar type
2547 * by set $CFG->calendar, and the appopriate function defined
2549 * @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
2550 * @param array $args The args to pass to the hook, usually the event is the first element
2551 * @return bool attempts to call event hook
2553 public static function calendar_event_hook($action, array $args) {
2554 global $CFG;
2555 static $extcalendarinc;
2556 if ($extcalendarinc === null) {
2557 if (!empty($CFG->calendar)) {
2558 if (is_readable($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
2559 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
2560 $extcalendarinc = true;
2561 } else {
2562 debugging("Calendar lib file missing or not readable at /calendar/{$CFG->calendar}/lib.php.",
2563 DEBUG_DEVELOPER);
2564 $extcalendarinc = false;
2566 } else {
2567 $extcalendarinc = false;
2570 if($extcalendarinc === false) {
2571 return false;
2573 $hook = $CFG->calendar .'_'.$action;
2574 if (function_exists($hook)) {
2575 call_user_func_array($hook, $args);
2576 return true;
2578 return false;
2582 * Returns a calendar_event object when provided with an event id
2584 * This function makes use of MUST_EXIST, if the event id passed in is invalid
2585 * it will result in an exception being thrown
2587 * @param int|object $param event object or event id
2588 * @return calendar_event|false status for loading calendar_event
2590 public static function load($param) {
2591 global $DB;
2592 if (is_object($param)) {
2593 $event = new calendar_event($param);
2594 } else {
2595 $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST);
2596 $event = new calendar_event($event);
2598 return $event;
2602 * Creates a new event and returns a calendar_event object
2604 * @param object|array $properties An object containing event properties
2605 * @return calendar_event|false The event object or false if it failed
2607 public static function create($properties) {
2608 if (is_array($properties)) {
2609 $properties = (object)$properties;
2611 if (!is_object($properties)) {
2612 throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2614 $event = new calendar_event($properties);
2615 if ($event->update($properties)) {
2616 return $event;
2617 } else {
2618 return false;
2624 * Calendar information class
2626 * This class is used simply to organise the information pertaining to a calendar
2627 * and is used primarily to make information easily available.
2629 * @package core_calendar
2630 * @category calendar
2631 * @copyright 2010 Sam Hemelryk
2632 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2634 class calendar_information {
2635 /** @var int The day */
2636 public $day;
2638 /** @var int The month */
2639 public $month;
2641 /** @var int The year */
2642 public $year;
2644 /** @var int A course id */
2645 public $courseid = null;
2647 /** @var array An array of courses */
2648 public $courses = array();
2650 /** @var array An array of groups */
2651 public $groups = array();
2653 /** @var array An array of users */
2654 public $users = array();
2657 * Creates a new instance
2659 * @param int $day the number of the day
2660 * @param int $month the number of the month
2661 * @param int $year the number of the year
2663 public function __construct($day=0, $month=0, $year=0) {
2665 $date = usergetdate(time());
2667 if (empty($day)) {
2668 $day = $date['mday'];
2671 if (empty($month)) {
2672 $month = $date['mon'];
2675 if (empty($year)) {
2676 $year = $date['year'];
2679 $this->day = $day;
2680 $this->month = $month;
2681 $this->year = $year;
2685 * Initialize calendar information
2687 * @param stdClass $course object
2688 * @param array $coursestoload An array of courses [$course->id => $course]
2689 * @param bool $ignorefilters options to use filter
2691 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
2692 $this->courseid = $course->id;
2693 $this->course = $course;
2694 list($courses, $group, $user) = calendar_set_filters($coursestoload, $ignorefilters);
2695 $this->courses = $courses;
2696 $this->groups = $group;
2697 $this->users = $user;
2701 * Ensures the date for the calendar is correct and either sets it to now
2702 * or throws a moodle_exception if not
2704 * @param bool $defaultonow use current time
2705 * @throws moodle_exception
2706 * @return bool validation of checkdate
2708 public function checkdate($defaultonow = true) {
2709 if (!checkdate($this->month, $this->day, $this->year)) {
2710 if ($defaultonow) {
2711 $now = usergetdate(time());
2712 $this->day = intval($now['mday']);
2713 $this->month = intval($now['mon']);
2714 $this->year = intval($now['year']);
2715 return true;
2716 } else {
2717 throw new moodle_exception('invaliddate');
2720 return true;
2723 * Gets todays timestamp for the calendar
2725 * @return int today timestamp
2727 public function timestamp_today() {
2728 return make_timestamp($this->year, $this->month, $this->day);
2731 * Gets tomorrows timestamp for the calendar
2733 * @return int tomorrow timestamp
2735 public function timestamp_tomorrow() {
2736 return make_timestamp($this->year, $this->month, $this->day+1);
2739 * Adds the pretend blocks for the calendar
2741 * @param core_calendar_renderer $renderer
2742 * @param bool $showfilters display filters, false is set as default
2743 * @param string|null $view preference view options (eg: day, month, upcoming)
2745 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
2746 if ($showfilters) {
2747 $filters = new block_contents();
2748 $filters->content = $renderer->fake_block_filters($this->courseid, $this->day, $this->month, $this->year, $view, $this->courses);
2749 $filters->footer = '';
2750 $filters->title = get_string('eventskey', 'calendar');
2751 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
2753 $block = new block_contents;
2754 $block->content = $renderer->fake_block_threemonths($this);
2755 $block->footer = '';
2756 $block->title = get_string('monthlyview', 'calendar');
2757 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
2762 * Returns option list for the poll interval setting.
2764 * @return array An array of poll interval options. Interval => description.
2766 function calendar_get_pollinterval_choices() {
2767 return array(
2768 '0' => new lang_string('never', 'calendar'),
2769 '3600' => new lang_string('hourly', 'calendar'),
2770 '86400' => new lang_string('daily', 'calendar'),
2771 '604800' => new lang_string('weekly', 'calendar'),
2772 '2628000' => new lang_string('monthly', 'calendar'),
2773 '31536000' => new lang_string('annually', 'calendar')
2778 * Returns option list of available options for the calendar event type, given the current user and course.
2780 * @param int $courseid The id of the course
2781 * @return array An array containing the event types the user can create.
2783 function calendar_get_eventtype_choices($courseid) {
2784 $choices = array();
2785 $allowed = new stdClass;
2786 calendar_get_allowed_types($allowed, $courseid);
2788 if ($allowed->user) {
2789 $choices['user'] = get_string('userevents', 'calendar');
2791 if ($allowed->site) {
2792 $choices['site'] = get_string('siteevents', 'calendar');
2794 if (!empty($allowed->courses)) {
2795 $choices['course'] = get_string('courseevents', 'calendar');
2797 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2798 $choices['group'] = get_string('group');
2801 return array($choices, $allowed->groups);
2805 * Add an iCalendar subscription to the database.
2807 * @param stdClass $sub The subscription object (e.g. from the form)
2808 * @return int The insert ID, if any.
2810 function calendar_add_subscription($sub) {
2811 global $DB, $USER, $SITE;
2813 if ($sub->eventtype === 'site') {
2814 $sub->courseid = $SITE->id;
2815 } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
2816 $sub->courseid = $sub->course;
2817 } else {
2818 // User events.
2819 $sub->courseid = 0;
2821 $sub->userid = $USER->id;
2823 // File subscriptions never update.
2824 if (empty($sub->url)) {
2825 $sub->pollinterval = 0;
2828 if (!empty($sub->name)) {
2829 if (empty($sub->id)) {
2830 $id = $DB->insert_record('event_subscriptions', $sub);
2831 // we cannot cache the data here because $sub is not complete.
2832 return $id;
2833 } else {
2834 // Why are we doing an update here?
2835 calendar_update_subscription($sub);
2836 return $sub->id;
2838 } else {
2839 print_error('errorbadsubscription', 'importcalendar');
2844 * Add an iCalendar event to the Moodle calendar.
2846 * @param object $event The RFC-2445 iCalendar event
2847 * @param int $courseid The course ID
2848 * @param int $subscriptionid The iCalendar subscription ID
2849 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2850 * @return int Code: 1=updated, 2=inserted, 0=error
2852 function calendar_add_icalendar_event($event, $courseid, $subscriptionid) {
2853 global $DB, $USER;
2855 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2856 if (empty($event->properties['SUMMARY'])) {
2857 return 0;
2860 $name = $event->properties['SUMMARY'][0]->value;
2861 $name = str_replace('\n', '<br />', $name);
2862 $name = str_replace('\\', '', $name);
2863 $name = preg_replace('/\s+/', ' ', $name);
2865 $eventrecord = new stdClass;
2866 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
2868 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2869 $description = '';
2870 } else {
2871 $description = $event->properties['DESCRIPTION'][0]->value;
2872 $description = str_replace('\n', '<br />', $description);
2873 $description = str_replace('\\', '', $description);
2874 $description = preg_replace('/\s+/', ' ', $description);
2876 $eventrecord->description = clean_param($description, PARAM_NOTAGS);
2878 // Probably a repeating event with RRULE etc. TODO: skip for now.
2879 if (empty($event->properties['DTSTART'][0]->value)) {
2880 return 0;
2883 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value);
2884 if (empty($event->properties['DTEND'])) {
2885 $eventrecord->timeduration = 3600; // one hour if no end time specified
2886 } else {
2887 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value) - $eventrecord->timestart;
2889 $eventrecord->uuid = $event->properties['UID'][0]->value;
2890 $eventrecord->timemodified = time();
2892 // Add the iCal subscription details if required.
2893 // We should never do anything with an event without a subscription reference.
2894 $sub = calendar_get_subscription($subscriptionid);
2895 $eventrecord->subscriptionid = $subscriptionid;
2896 $eventrecord->userid = $sub->userid;
2897 $eventrecord->groupid = $sub->groupid;
2898 $eventrecord->courseid = $sub->courseid;
2899 $eventrecord->eventtype = $sub->eventtype;
2901 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid))) {
2902 $eventrecord->id = $updaterecord->id;
2903 if ($DB->update_record('event', $eventrecord)) {
2904 return CALENDAR_IMPORT_EVENT_UPDATED;
2905 } else {
2906 return 0;
2908 } else {
2909 if ($DB->insert_record('event', $eventrecord)) {
2910 return CALENDAR_IMPORT_EVENT_INSERTED;
2911 } else {
2912 return 0;
2918 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2920 * @param int $subscriptionid The ID of the subscription we are acting upon.
2921 * @param int $pollinterval The poll interval to use.
2922 * @param int $action The action to be performed. One of update or remove.
2923 * @throws dml_exception if invalid subscriptionid is provided
2924 * @return string A log of the import progress, including errors
2926 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2928 // Fetch the subscription from the database making sure it exists.
2929 $sub = calendar_get_subscription($subscriptionid);
2931 // Update or remove the subscription, based on action.
2932 switch ($action) {
2933 case CALENDAR_SUBSCRIPTION_UPDATE:
2934 // Skip updating file subscriptions.
2935 if (empty($sub->url)) {
2936 break;
2938 $sub->pollinterval = $pollinterval;
2939 calendar_update_subscription($sub);
2941 // Update the events.
2942 return "<p>".get_string('subscriptionupdated', 'calendar', $sub->name)."</p>" . calendar_update_subscription_events($subscriptionid);
2944 case CALENDAR_SUBSCRIPTION_REMOVE:
2945 calendar_delete_subscription($subscriptionid);
2946 return get_string('subscriptionremoved', 'calendar', $sub->name);
2947 break;
2949 default:
2950 break;
2952 return '';
2956 * Delete subscription and all related events.
2958 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
2960 function calendar_delete_subscription($subscription) {
2961 global $DB;
2963 if (is_object($subscription)) {
2964 $subscription = $subscription->id;
2966 // Delete subscription and related events.
2967 $DB->delete_records('event', array('subscriptionid' => $subscription));
2968 $DB->delete_records('event_subscriptions', array('id' => $subscription));
2969 cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription));
2972 * From a URL, fetch the calendar and return an iCalendar object.
2974 * @param string $url The iCalendar URL
2975 * @return stdClass The iCalendar object
2977 function calendar_get_icalendar($url) {
2978 global $CFG;
2980 require_once($CFG->libdir.'/filelib.php');
2982 $curl = new curl();
2983 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
2984 $calendar = $curl->get($url);
2985 // Http code validation should actually be the job of curl class.
2986 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
2987 throw new moodle_exception('errorinvalidicalurl', 'calendar');
2990 $ical = new iCalendar();
2991 $ical->unserialize($calendar);
2992 return $ical;
2996 * Import events from an iCalendar object into a course calendar.
2998 * @param stdClass $ical The iCalendar object.
2999 * @param int $courseid The course ID for the calendar.
3000 * @param int $subscriptionid The subscription ID.
3001 * @return string A log of the import progress, including errors.
3003 function calendar_import_icalendar_events($ical, $courseid, $subscriptionid = null) {
3004 global $DB;
3005 $return = '';
3006 $eventcount = 0;
3007 $updatecount = 0;
3009 // Large calendars take a while...
3010 set_time_limit(300);
3012 // Mark all events in a subscription with a zero timestamp.
3013 if (!empty($subscriptionid)) {
3014 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
3015 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3017 foreach ($ical->components['VEVENT'] as $event) {
3018 $res = calendar_add_icalendar_event($event, $courseid, $subscriptionid);
3019 switch ($res) {
3020 case CALENDAR_IMPORT_EVENT_UPDATED:
3021 $updatecount++;
3022 break;
3023 case CALENDAR_IMPORT_EVENT_INSERTED:
3024 $eventcount++;
3025 break;
3026 case 0:
3027 $return .= '<p>'.get_string('erroraddingevent', 'calendar').': '.(empty($event->properties['SUMMARY'])?'('.get_string('notitle', 'calendar').')':$event->properties['SUMMARY'][0]->value)." </p>\n";
3028 break;
3031 $return .= "<p> ".get_string('eventsimported', 'calendar', $eventcount)."</p>";
3032 $return .= "<p> ".get_string('eventsupdated', 'calendar', $updatecount)."</p>";
3034 // Delete remaining zero-marked events since they're not in remote calendar.
3035 if (!empty($subscriptionid)) {
3036 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3037 if (!empty($deletecount)) {
3038 $sql = "DELETE FROM {event} WHERE timemodified = :time AND subscriptionid = :id";
3039 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3040 $return .= "<p> ".get_string('eventsdeleted', 'calendar').": {$deletecount} </p>\n";
3044 return $return;
3048 * Fetch a calendar subscription and update the events in the calendar.
3050 * @param int $subscriptionid The course ID for the calendar.
3051 * @return string A log of the import progress, including errors.
3053 function calendar_update_subscription_events($subscriptionid) {
3054 global $DB;
3056 $sub = calendar_get_subscription($subscriptionid);
3057 // Don't update a file subscription. TODO: Update from a new uploaded file.
3058 if (empty($sub->url)) {
3059 return 'File subscription not updated.';
3061 $ical = calendar_get_icalendar($sub->url);
3062 $return = calendar_import_icalendar_events($ical, $sub->courseid, $subscriptionid);
3063 $sub->lastupdated = time();
3064 calendar_update_subscription($sub);
3065 return $return;
3069 * Update a calendar subscription. Also updates the associated cache.
3071 * @param stdClass|array $subscription Subscription record.
3072 * @throws coding_exception If something goes wrong
3073 * @since Moodle 2.5
3075 function calendar_update_subscription($subscription) {
3076 global $DB;
3078 if (is_array($subscription)) {
3079 $subscription = (object)$subscription;
3081 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
3082 throw new coding_exception('Cannot update a subscription without a valid id');
3085 $DB->update_record('event_subscriptions', $subscription);
3086 // Update cache.
3087 $cache = cache::make('core', 'calendar_subscriptions');
3088 $cache->set($subscription->id, $subscription);
3092 * Checks to see if the user can edit a given subscription feed.
3094 * @param mixed $subscriptionorid Subscription object or id
3095 * @return bool true if current user can edit the subscription else false
3097 function calendar_can_edit_subscription($subscriptionorid) {
3098 global $DB;
3100 if (is_array($subscriptionorid)) {
3101 $subscription = (object)$subscriptionorid;
3102 } else if (is_object($subscriptionorid)) {
3103 $subscription = $subscriptionorid;
3104 } else {
3105 $subscription = calendar_get_subscription($subscriptionorid);
3107 $allowed = new stdClass;
3108 $courseid = $subscription->courseid;
3109 $groupid = $subscription->groupid;
3110 calendar_get_allowed_types($allowed, $courseid);
3111 switch ($subscription->eventtype) {
3112 case 'user':
3113 return $allowed->user;
3114 case 'course':
3115 if (isset($allowed->courses[$courseid])) {
3116 return $allowed->courses[$courseid];
3117 } else {
3118 return false;
3120 case 'site':
3121 return $allowed->site;
3122 case 'group':
3123 if (isset($allowed->groups[$groupid])) {
3124 return $allowed->groups[$groupid];
3125 } else {
3126 return false;
3128 default:
3129 return false;
3134 * Update calendar subscriptions.
3136 * @return bool
3138 function calendar_cron() {
3139 global $CFG, $DB;
3141 // In order to execute this we need bennu.
3142 require_once($CFG->libdir.'/bennu/bennu.inc.php');
3144 mtrace('Updating calendar subscriptions:');
3145 cron_trace_time_and_memory();
3147 $time = time();
3148 $subscriptions = $DB->get_records_sql('SELECT * FROM {event_subscriptions} WHERE pollinterval > 0 AND lastupdated + pollinterval < ?', array($time));
3149 foreach ($subscriptions as $sub) {
3150 mtrace("Updating calendar subscription {$sub->name} in course {$sub->courseid}");
3151 try {
3152 $log = calendar_update_subscription_events($sub->id);
3153 } catch (moodle_exception $ex) {
3156 mtrace(trim(strip_tags($log)));
3159 mtrace('Finished updating calendar subscriptions.');
3161 return true;