2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * @package core_calendar
21 * @copyright 2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 if (!defined('MOODLE_INTERNAL')) {
27 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
31 * These are read by the administration component to provide default values
35 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
37 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
40 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
42 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
45 * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
47 define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
49 // This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
50 // Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
53 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
55 define('CALENDAR_DEFAULT_WEEKEND', 65);
58 * CALENDAR_URL - path to calendar's folder
60 define('CALENDAR_URL', $CFG->wwwroot
.'/calendar/');
63 * CALENDAR_TF_24 - Calendar time in 24 hours format
65 define('CALENDAR_TF_24', '%H:%M');
68 * CALENDAR_TF_12 - Calendar time in 12 hours format
70 define('CALENDAR_TF_12', '%I:%M %p');
73 * CALENDAR_EVENT_GLOBAL - Global calendar event types
75 define('CALENDAR_EVENT_GLOBAL', 1);
78 * CALENDAR_EVENT_COURSE - Course calendar event types
80 define('CALENDAR_EVENT_COURSE', 2);
83 * CALENDAR_EVENT_GROUP - group calendar event types
85 define('CALENDAR_EVENT_GROUP', 4);
88 * CALENDAR_EVENT_USER - user calendar event types
90 define('CALENDAR_EVENT_USER', 8);
94 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
96 define('CALENDAR_IMPORT_FROM_FILE', 0);
99 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
101 define('CALENDAR_IMPORT_FROM_URL', 1);
104 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
106 define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
109 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
111 define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
114 * Return the days of the week
116 * @return array array of days
118 function calendar_get_days() {
119 return array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
123 * Get the subscription from a given id
126 * @param int $id id of the subscription
127 * @return stdClass Subscription record from DB
128 * @throws moodle_exception for an invalid id
130 function calendar_get_subscription($id) {
133 $cache = cache
::make('core', 'calendar_subscriptions');
134 $subscription = $cache->get($id);
135 if (empty($subscription)) {
136 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST
);
138 $cache->set($id, $subscription);
140 return $subscription;
144 * Gets the first day of the week
146 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
150 function calendar_get_starting_weekday() {
153 if (isset($CFG->calendar_startwday
)) {
154 $firstday = $CFG->calendar_startwday
;
156 $firstday = get_string('firstdayofweek', 'langconfig');
159 if(!is_numeric($firstday)) {
160 return CALENDAR_DEFAULT_STARTING_WEEKDAY
;
162 return intval($firstday) %
7;
167 * Generates the HTML for a miniature calendar
169 * @param array $courses list of course to list events from
170 * @param array $groups list of group
171 * @param array $users user's info
172 * @param int $cal_month calendar month in numeric, default is set to false
173 * @param int $cal_year calendar month in numeric, default is set to false
174 * @param string $placement the place/page the calendar is set to appear - passed on the the controls function
175 * @param int $courseid id of the course the calendar is displayed on - passed on the the controls function
176 * @return string $content return html table for mini calendar
178 function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_year = false, $placement = false, $courseid = false ) {
179 global $CFG, $USER, $OUTPUT;
181 $display = new stdClass
;
182 $display->minwday
= get_user_preferences('calendar_startwday', calendar_get_starting_weekday());
183 $display->maxwday
= $display->minwday +
6;
187 if(!empty($cal_month) && !empty($cal_year)) {
188 $thisdate = usergetdate(time()); // Date and time the user sees at his location
189 if($cal_month == $thisdate['mon'] && $cal_year == $thisdate['year']) {
190 // Navigated to this month
192 $display->thismonth
= true;
194 // Navigated to other month, let's do a nice trick and save us a lot of work...
195 if(!checkdate($cal_month, 1, $cal_year)) {
196 $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']);
197 $display->thismonth
= true;
199 $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year);
200 $display->thismonth
= false;
204 $date = usergetdate(time()); // Date and time the user sees at his location
205 $display->thismonth
= true;
208 // Fill in the variables we 're going to use, nice and tidy
209 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display
210 $display->maxdays
= calendar_days_in_month($m, $y);
212 if (get_user_timezone_offset() < 99) {
213 // We 'll keep these values as GMT here, and offset them when the time comes to query the db
214 $display->tstart
= gmmktime(0, 0, 0, $m, 1, $y); // This is GMT
215 $display->tend
= gmmktime(23, 59, 59, $m, $display->maxdays
, $y); // GMT
217 // no timezone info specified
218 $display->tstart
= mktime(0, 0, 0, $m, 1, $y);
219 $display->tend
= mktime(23, 59, 59, $m, $display->maxdays
, $y);
222 $startwday = dayofweek(1, $m, $y);
224 // Align the starting weekday to fall in our display range
225 // This is simple, not foolproof.
226 if($startwday < $display->minwday
) {
230 // TODO: THIS IS TEMPORARY CODE!
231 // [pj] I was just reading through this and realized that I when writing this code I was probably
232 // asking for trouble, as all these time manipulations seem to be unnecessary and a simple
233 // make_timestamp would accomplish the same thing. So here goes a test:
234 //$test_start = make_timestamp($y, $m, 1);
235 //$test_end = make_timestamp($y, $m, $display->maxdays, 23, 59, 59);
236 //if($test_start != usertime($display->tstart) - dst_offset_on($display->tstart)) {
237 //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);
239 //if($test_end != usertime($display->tend) - dst_offset_on($display->tend)) {
240 //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);
244 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
245 $events = calendar_get_events(
246 usertime($display->tstart
) - dst_offset_on($display->tstart
),
247 usertime($display->tend
) - dst_offset_on($display->tend
),
248 $users, $groups, $courses);
250 // Set event course class for course events
251 if (!empty($events)) {
252 foreach ($events as $eventid => $event) {
253 if (!empty($event->modulename
)) {
254 $cm = get_coursemodule_from_instance($event->modulename
, $event->instance
);
255 if (!groups_course_module_visible($cm)) {
256 unset($events[$eventid]);
262 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
263 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
264 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
265 // arguments to this function.
267 $hrefparams = array();
268 if(!empty($courses)) {
269 $courses = array_diff($courses, array(SITEID
));
270 if(count($courses) == 1) {
271 $hrefparams['course'] = reset($courses);
275 // We want to have easy access by day, since the display is on a per-day basis.
276 // Arguments passed by reference.
277 //calendar_events_by_day($events, $display->tstart, $eventsbyday, $durationbyday, $typesbyday);
278 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
280 //Accessibility: added summary and <abbr> elements.
281 $days_title = calendar_get_days();
283 $summary = get_string('calendarheading', 'calendar', userdate(make_timestamp($y, $m), get_string('strftimemonthyear')));
284 $content .= '<table class="minicalendar calendartable" summary="'.$summary.'">'; // Begin table
285 if (($placement !== false) && ($courseid !== false)) {
286 $content .= '<caption>'. calendar_top_controls($placement, array('id' => $courseid, 'm' => $m, 'y' => $y)) .'</caption>';
288 $content .= '<tr class="weekdays">'; // Header row: day names
290 // Print out the names of the weekdays
291 $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
292 for($i = $display->minwday
; $i <= $display->maxwday
; ++
$i) {
293 // This uses the % operator to get the correct weekday no matter what shift we have
294 // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
295 $content .= '<th scope="col"><abbr title="'. get_string($days_title[$i %
7], 'calendar') .'">'.
296 get_string($days[$i %
7], 'calendar') ."</abbr></th>\n";
299 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
301 // For the table display. $week is the row; $dayweek is the column.
302 $dayweek = $startwday;
304 // Paddding (the first week may have blank days in the beginning)
305 for($i = $display->minwday
; $i < $startwday; ++
$i) {
306 $content .= '<td class="dayblank"> </td>'."\n";
309 $weekend = CALENDAR_DEFAULT_WEEKEND
;
310 if (isset($CFG->calendar_weekend
)) {
311 $weekend = intval($CFG->calendar_weekend
);
314 // Now display all the calendar
315 for($day = 1; $day <= $display->maxdays
; ++
$day, ++
$dayweek) {
316 if($dayweek > $display->maxwday
) {
317 // We need to change week (table row)
318 $content .= '</tr><tr>';
319 $dayweek = $display->minwday
;
324 if ($weekend & (1 << ($dayweek %
7))) {
325 // Weekend. This is true no matter what the exact range is.
326 $class = 'weekend day';
328 // Normal working day.
332 // Special visual fx if an event is defined
333 if(isset($eventsbyday[$day])) {
334 $class .= ' hasevent';
335 $hrefparams['view'] = 'day';
336 $dayhref = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', $hrefparams), $day, $m, $y);
339 foreach($eventsbyday[$day] as $eventid) {
340 if (!isset($events[$eventid])) {
343 $event = new calendar_event($events[$eventid]);
345 $component = 'moodle';
346 if(!empty($event->modulename
)) {
348 $popupalt = $event->modulename
;
349 $component = $event->modulename
;
350 } else if ($event->courseid
== SITEID
) { // Site event
351 $popupicon = 'i/siteevent';
352 } else if ($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) { // Course event
353 $popupicon = 'i/courseevent';
354 } else if ($event->groupid
) { // Group event
355 $popupicon = 'i/groupevent';
356 } else if ($event->userid
) { // User event
357 $popupicon = 'i/userevent';
360 $dayhref->set_anchor('event_'.$event->id
);
362 $popupcontent .= html_writer
::start_tag('div');
363 $popupcontent .= $OUTPUT->pix_icon($popupicon, $popupalt, $component);
364 $name = format_string($event->name
, true);
365 // Show ical source if needed.
366 if (!empty($event->subscription
) && $CFG->calendar_showicalsource
) {
369 $a->source
= $event->subscription
->name
;
370 $name = get_string('namewithsource', 'calendar', $a);
372 $popupcontent .= html_writer
::link($dayhref, $name);
373 $popupcontent .= html_writer
::end_tag('div');
376 //Accessibility: functionality moved to calendar_get_popup.
377 if($display->thismonth
&& $day == $d) {
378 $popupid = calendar_get_popup(true, $events[$eventid]->timestart
, $popupcontent);
380 $popupid = calendar_get_popup(false, $events[$eventid]->timestart
, $popupcontent);
383 // Class and cell content
384 if(isset($typesbyday[$day]['startglobal'])) {
385 $class .= ' calendar_event_global';
386 } else if(isset($typesbyday[$day]['startcourse'])) {
387 $class .= ' calendar_event_course';
388 } else if(isset($typesbyday[$day]['startgroup'])) {
389 $class .= ' calendar_event_group';
390 } else if(isset($typesbyday[$day]['startuser'])) {
391 $class .= ' calendar_event_user';
393 $cell = html_writer
::link($dayhref, $day, array('aria-controls' => $popupid.'_panel', 'id' => $popupid));
398 $durationclass = false;
399 if (isset($typesbyday[$day]['durationglobal'])) {
400 $durationclass = ' duration_global';
401 } else if(isset($typesbyday[$day]['durationcourse'])) {
402 $durationclass = ' duration_course';
403 } else if(isset($typesbyday[$day]['durationgroup'])) {
404 $durationclass = ' duration_group';
405 } else if(isset($typesbyday[$day]['durationuser'])) {
406 $durationclass = ' duration_user';
408 if ($durationclass) {
409 $class .= ' duration '.$durationclass;
412 // If event has a class set then add it to the table day <td> tag
413 // Note: only one colour for minicalendar
414 if(isset($eventsbyday[$day])) {
415 foreach($eventsbyday[$day] as $eventid) {
416 if (!isset($events[$eventid])) {
419 $event = $events[$eventid];
420 if (!empty($event->class)) {
421 $class .= ' '.$event->class;
427 // Special visual fx for today
428 //Accessibility: hidden text for today, and popup.
429 if($display->thismonth
&& $day == $d) {
431 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
433 if(! isset($eventsbyday[$day])) {
434 $class .= ' eventnone';
435 $popupid = calendar_get_popup(true, false);
436 $cell = html_writer
::link('#', $day, array('aria-controls' => $popupid.'_panel', 'id' => $popupid));
438 $cell = get_accesshide($today.' ').$cell;
443 $class = ' class="'.$class.'"';
445 $content .= '<td'.$class.'>'.$cell."</td>\n";
448 // Paddding (the last week may have blank days at the end)
449 for($i = $dayweek; $i <= $display->maxwday
; ++
$i) {
450 $content .= '<td class="dayblank"> </td>';
452 $content .= '</tr>'; // Last row ends
454 $content .= '</table>'; // Tabular display of days ends
460 * Gets the calendar popup
462 * It called at multiple points in from calendar_get_mini.
463 * Copied and modified from calendar_get_mini.
465 * @param bool $is_today false except when called on the current day.
466 * @param mixed $event_timestart $events[$eventid]->timestart, OR false if there are no events.
467 * @param string $popupcontent content for the popup window/layout.
468 * @return string eventid for the calendar_tooltip popup window/layout.
470 function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
473 if ($popupcount === null) {
478 $popupcaption = get_string('today', 'calendar').' ';
480 if (false === $event_timestart) {
481 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
482 $popupcontent = get_string('eventnone', 'calendar');
485 $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
487 $id = 'calendar_tooltip_'.$popupcount;
488 $PAGE->requires
->yui_module('moodle-calendar-eventmanager', 'M.core_calendar.add_event', array(array('eventId'=>$id,'title'=>$popupcaption, 'content'=>$popupcontent)));
495 * Gets the calendar upcoming event
497 * @param array $courses array of courses
498 * @param array|int|bool $groups array of groups, group id or boolean for all/no group events
499 * @param array|int|bool $users array of users, user id or boolean for all/no user events
500 * @param int $daysinfuture number of days in the future we 'll look
501 * @param int $maxevents maximum number of events
502 * @param int $fromtime start time
503 * @return array $output array of upcoming events
505 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
506 global $CFG, $COURSE, $DB;
508 $display = new stdClass
;
509 $display->range
= $daysinfuture; // How many days in the future we 'll look
510 $display->maxevents
= $maxevents;
514 // Prepare "course caching", since it may save us a lot of queries
515 $coursecache = array();
518 $now = time(); // We 'll need this later
519 $usermidnighttoday = usergetmidnight($now);
522 $display->tstart
= $fromtime;
524 $display->tstart
= $usermidnighttoday;
527 // This works correctly with respect to the user's DST, but it is accurate
528 // only because $fromtime is always the exact midnight of some day!
529 $display->tend
= usergetmidnight($display->tstart + DAYSECS
* $display->range +
3 * HOURSECS
) - 1;
531 // Get the events matching our criteria
532 $events = calendar_get_events($display->tstart
, $display->tend
, $users, $groups, $courses);
534 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
535 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
536 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
537 // arguments to this function.
539 $hrefparams = array();
540 if(!empty($courses)) {
541 $courses = array_diff($courses, array(SITEID
));
542 if(count($courses) == 1) {
543 $hrefparams['course'] = reset($courses);
547 if ($events !== false) {
549 $modinfo = get_fast_modinfo($COURSE);
551 foreach($events as $event) {
554 if (!empty($event->modulename
)) {
555 if ($event->courseid
== $COURSE->id
) {
556 if (isset($modinfo->instances
[$event->modulename
][$event->instance
])) {
557 $cm = $modinfo->instances
[$event->modulename
][$event->instance
];
558 if (!$cm->uservisible
) {
563 if (!$cm = get_coursemodule_from_instance($event->modulename
, $event->instance
)) {
566 if (!coursemodule_visible_for_user($cm)) {
570 if ($event->modulename
== 'assignment'){
571 // create calendar_event to test edit_event capability
572 // this new event will also prevent double creation of calendar_event object
573 $checkevent = new calendar_event($event);
574 // TODO: rewrite this hack somehow
575 if (!calendar_edit_event_allowed($checkevent)){ // cannot manage entries, eg. student
576 if (!$assignment = $DB->get_record('assignment', array('id'=>$event->instance
))) {
577 // print_error("invalidid", 'assignment');
580 // assign assignment to assignment object to use hidden_is_hidden method
581 require_once($CFG->dirroot
.'/mod/assignment/lib.php');
583 if (!file_exists($CFG->dirroot
.'/mod/assignment/type/'.$assignment->assignmenttype
.'/assignment.class.php')) {
586 require_once ($CFG->dirroot
.'/mod/assignment/type/'.$assignment->assignmenttype
.'/assignment.class.php');
588 $assignmentclass = 'assignment_'.$assignment->assignmenttype
;
589 $assignmentinstance = new $assignmentclass($cm->id
, $assignment, $cm);
591 if ($assignmentinstance->description_is_hidden()){//force not to show description before availability
592 $event->description
= get_string('notavailableyet', 'assignment');
598 if ($processed >= $display->maxevents
) {
602 $event->time
= calendar_format_event_time($event, $now, $hrefparams);
611 * Add calendar event metadata
613 * @param stdClass $event event info
614 * @return stdClass $event metadata
616 function calendar_add_event_metadata($event) {
617 global $CFG, $OUTPUT;
619 //Support multilang in event->name
620 $event->name
= format_string($event->name
,true);
622 if(!empty($event->modulename
)) { // Activity event
623 // The module name is set. I will assume that it has to be displayed, and
624 // also that it is an automatically-generated event. And of course that the
625 // fields for get_coursemodule_from_instance are set correctly.
626 $module = calendar_get_module_cached($coursecache, $event->modulename
, $event->instance
);
628 if ($module === false) {
632 $modulename = get_string('modulename', $event->modulename
);
633 if (get_string_manager()->string_exists($event->eventtype
, $event->modulename
)) {
634 // will be used as alt text if the event icon
635 $eventtype = get_string($event->eventtype
, $event->modulename
);
639 $icon = $OUTPUT->pix_url('icon', $event->modulename
) . '';
641 $context = context_course
::instance($module->course
);
642 $fullname = format_string($coursecache[$module->course
]->fullname
, true, array('context' => $context));
644 $event->icon
= '<img src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" class="icon" />';
645 $event->referer
= '<a href="'.$CFG->wwwroot
.'/mod/'.$event->modulename
.'/view.php?id='.$module->id
.'">'.$event->name
.'</a>';
646 $event->courselink
= '<a href="'.$CFG->wwwroot
.'/course/view.php?id='.$module->course
.'">'.$fullname.'</a>';
647 $event->cmid
= $module->id
;
650 } else if($event->courseid
== SITEID
) { // Site event
651 $event->icon
= '<img src="'.$OUTPUT->pix_url('i/siteevent') . '" alt="'.get_string('globalevent', 'calendar').'" class="icon" />';
652 $event->cssclass
= 'calendar_event_global';
653 } else if($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) { // Course event
654 calendar_get_course_cached($coursecache, $event->courseid
);
656 $context = context_course
::instance($event->courseid
);
657 $fullname = format_string($coursecache[$event->courseid
]->fullname
, true, array('context' => $context));
659 $event->icon
= '<img src="'.$OUTPUT->pix_url('i/courseevent') . '" alt="'.get_string('courseevent', 'calendar').'" class="icon" />';
660 $event->courselink
= '<a href="'.$CFG->wwwroot
.'/course/view.php?id='.$event->courseid
.'">'.$fullname.'</a>';
661 $event->cssclass
= 'calendar_event_course';
662 } else if ($event->groupid
) { // Group event
663 $event->icon
= '<img src="'.$OUTPUT->pix_url('i/groupevent') . '" alt="'.get_string('groupevent', 'calendar').'" class="icon" />';
664 $event->cssclass
= 'calendar_event_group';
665 } else if($event->userid
) { // User event
666 $event->icon
= '<img src="'.$OUTPUT->pix_url('i/userevent') . '" alt="'.get_string('userevent', 'calendar').'" class="icon" />';
667 $event->cssclass
= 'calendar_event_user';
673 * Get calendar events
675 * @param int $tstart Start time of time range for events
676 * @param int $tend End time of time range for events
677 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
678 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
679 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
680 * @param boolean $withduration whether only events starting within time range selected
681 * or events in progress/already started selected as well
682 * @param boolean $ignorehidden whether to select only visible events or all events
683 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
685 function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
690 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
694 if(is_array($users) && !empty($users)) {
695 // Events from a number of users
696 if(!empty($whereclause)) $whereclause .= ' OR';
697 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
698 } else if(is_numeric($users)) {
699 // Events from one user
700 if(!empty($whereclause)) $whereclause .= ' OR';
701 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
702 } else if($users === true) {
703 // Events from ALL users
704 if(!empty($whereclause)) $whereclause .= ' OR';
705 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
706 } else if($users === false) {
707 // No user at all, do nothing
710 if(is_array($groups) && !empty($groups)) {
711 // Events from a number of groups
712 if(!empty($whereclause)) $whereclause .= ' OR';
713 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
714 } else if(is_numeric($groups)) {
715 // Events from one group
716 if(!empty($whereclause)) $whereclause .= ' OR ';
717 $whereclause .= ' groupid = '.$groups;
718 } else if($groups === true) {
719 // Events from ALL groups
720 if(!empty($whereclause)) $whereclause .= ' OR ';
721 $whereclause .= ' groupid != 0';
723 // boolean false (no groups at all): we don't need to do anything
725 if(is_array($courses) && !empty($courses)) {
726 if(!empty($whereclause)) {
727 $whereclause .= ' OR';
729 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
730 } else if(is_numeric($courses)) {
732 if(!empty($whereclause)) $whereclause .= ' OR';
733 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
734 } else if ($courses === true) {
735 // Events from ALL courses
736 if(!empty($whereclause)) $whereclause .= ' OR';
737 $whereclause .= ' (groupid = 0 AND courseid != 0)';
740 // Security check: if, by now, we have NOTHING in $whereclause, then it means
741 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
742 // events no matter what. Allowing the code to proceed might return a completely
743 // valid query with only time constraints, thus selecting ALL events in that time frame!
744 if(empty($whereclause)) {
749 $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
752 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
754 if(!empty($whereclause)) {
755 // We have additional constraints
756 $whereclause = $timeclause.' AND ('.$whereclause.')';
759 // Just basic time filtering
760 $whereclause = $timeclause;
764 $whereclause .= ' AND visible = 1';
767 $events = $DB->get_records_select('event', $whereclause, null, 'timestart');
768 if ($events === false) {
774 /** Get calendar events by id
777 * @param array $eventids list of event ids
778 * @return array Array of event entries, empty array if nothing found
781 function calendar_get_events_by_id($eventids) {
784 if (!is_array($eventids) ||
empty($eventids)) {
787 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
788 $wheresql = "id $wheresql";
790 return $DB->get_records_select('event', $wheresql, $params);
794 * Get control options for Calendar
796 * @param string $type of calendar
797 * @param array $data calendar information
798 * @return string $content return available control for the calender in html
800 function calendar_top_controls($type, $data) {
803 if(!isset($data['d'])) {
807 // Ensure course id passed if relevant
808 // Required due to changes in view/lib.php mainly (calendar_session_vars())
810 if (!empty($data['id'])) {
811 $courseid = '&course='.$data['id'];
814 if(!checkdate($data['m'], $data['d'], $data['y'])) {
818 $time = make_timestamp($data['y'], $data['m'], $data['d']);
820 $date = usergetdate($time);
822 $data['m'] = $date['mon'];
823 $data['y'] = $date['year'];
824 $urlbase = $PAGE->url
;
826 //Accessibility: calendar block controls, replaced <table> with <div>.
827 //$nexttext = link_arrow_right(get_string('monthnext', 'access'), $url='', $accesshide=true);
828 //$prevtext = link_arrow_left(get_string('monthprev', 'access'), $url='', $accesshide=true);
832 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
833 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
834 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, 0, $nextmonth, $nextyear, true);
835 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, 0, $prevmonth, $prevyear, true);
837 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
838 if (!empty($data['id'])) {
839 $calendarlink->param('course', $data['id']);
842 if (right_to_left()) {
850 $content .= html_writer
::start_tag('div', array('class'=>'calendar-controls'));
851 $content .= $left.'<span class="hide"> | </span>';
852 $content .= html_writer
::tag('span', html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
853 $content .= '<span class="hide"> | </span>'. $right;
854 $content .= "<span class=\"clearer\"><!-- --></span>\n";
855 $content .= html_writer
::end_tag('div');
859 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
860 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
861 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, 0, $nextmonth, $nextyear, true);
862 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, 0, $prevmonth, $prevyear, true);
864 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
865 if (!empty($data['id'])) {
866 $calendarlink->param('course', $data['id']);
869 if (right_to_left()) {
877 $content .= html_writer
::start_tag('div', array('class'=>'calendar-controls'));
878 $content .= $left.'<span class="hide"> | </span>';
879 $content .= html_writer
::tag('span', html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
880 $content .= '<span class="hide"> | </span>'. $right;
881 $content .= "<span class=\"clearer\"><!-- --></span>";
882 $content .= html_writer
::end_tag('div');
885 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', array('view'=>'upcoming')), 1, $data['m'], $data['y']);
886 if (!empty($data['id'])) {
887 $calendarlink->param('course', $data['id']);
889 $calendarlink = html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
890 $content .= html_writer
::tag('div', $calendarlink, array('class'=>'centered'));
893 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
894 if (!empty($data['id'])) {
895 $calendarlink->param('course', $data['id']);
897 $calendarlink = html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
898 $content .= html_writer
::tag('h3', $calendarlink);
901 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
902 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
903 $prevdate = make_timestamp($prevyear, $prevmonth, 1);
904 $nextdate = make_timestamp($nextyear, $nextmonth, 1);
905 $prevlink = calendar_get_link_previous(userdate($prevdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&', 1, $prevmonth, $prevyear);
906 $nextlink = calendar_get_link_next(userdate($nextdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&', 1, $nextmonth, $nextyear);
908 if (right_to_left()) {
916 $content .= html_writer
::start_tag('div', array('class'=>'calendar-controls'));
917 $content .= $left . '<span class="hide"> | </span><h1 class="current">'.userdate($time, get_string('strftimemonthyear'))."</h1>";
918 $content .= '<span class="hide"> | </span>' . $right;
919 $content .= '<span class="clearer"><!-- --></span>';
920 $content .= html_writer
::end_tag('div')."\n";
923 $days = calendar_get_days();
924 $data['d'] = $date['mday']; // Just for convenience
925 $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
926 $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] +
1));
927 $prevname = calendar_wday_name($days[$prevdate['wday']]);
928 $nextname = calendar_wday_name($days[$nextdate['wday']]);
929 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
930 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);
932 if (right_to_left()) {
940 $content .= html_writer
::start_tag('div', array('class'=>'calendar-controls'));
942 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimedaydate')).'</span>';
943 $content .= '<span class="hide"> | </span>'. $right;
944 $content .= "<span class=\"clearer\"><!-- --></span>";
945 $content .= html_writer
::end_tag('div')."\n";
953 * Formats a filter control element.
955 * @param moodle_url $url of the filter
956 * @param int $type constant defining the type filter
957 * @return string html content of the element
959 function calendar_filter_controls_element(moodle_url
$url, $type) {
962 case CALENDAR_EVENT_GLOBAL
:
963 $typeforhumans = 'global';
964 $class = 'calendar_event_global';
966 case CALENDAR_EVENT_COURSE
:
967 $typeforhumans = 'course';
968 $class = 'calendar_event_course';
970 case CALENDAR_EVENT_GROUP
:
971 $typeforhumans = 'groups';
972 $class = 'calendar_event_group';
974 case CALENDAR_EVENT_USER
:
975 $typeforhumans = 'user';
976 $class = 'calendar_event_user';
979 if (calendar_show_event_type($type)) {
980 $icon = $OUTPUT->pix_icon('t/hide', get_string('hide'));
981 $str = get_string('hide'.$typeforhumans.'events', 'calendar');
983 $icon = $OUTPUT->pix_icon('t/show', get_string('show'));
984 $str = get_string('show'.$typeforhumans.'events', 'calendar');
986 $content = html_writer
::start_tag('li', array('class' => 'calendar_event'));
987 $content .= html_writer
::start_tag('a', array('href' => $url));
988 $content .= html_writer
::tag('span', $icon, array('class' => $class));
989 $content .= html_writer
::tag('span', $str, array('class' => 'eventname'));
990 $content .= html_writer
::end_tag('a');
991 $content .= html_writer
::end_tag('li');
996 * Get the controls filter for calendar.
998 * Filter is used to hide calendar info from the display page
1000 * @param moodle_url $returnurl return-url for filter controls
1001 * @return string $content return filter controls in html
1003 function calendar_filter_controls(moodle_url
$returnurl) {
1004 global $CFG, $USER, $OUTPUT;
1006 $groupevents = true;
1007 $id = optional_param( 'id',0,PARAM_INT
);
1008 $seturl = new moodle_url('/calendar/set.php', array('return' => base64_encode($returnurl->out(false)), 'sesskey'=>sesskey()));
1009 $content = html_writer
::start_tag('ul');
1011 $seturl->param('var', 'showglobal');
1012 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GLOBAL
);
1014 $seturl->param('var', 'showcourses');
1015 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_COURSE
);
1017 if (isloggedin() && !isguestuser()) {
1019 // This course MIGHT have group events defined, so show the filter
1020 $seturl->param('var', 'showgroups');
1021 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GROUP
);
1023 // This course CANNOT have group events, so lose the filter
1025 $seturl->param('var', 'showuser');
1026 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_USER
);
1028 $content .= html_writer
::end_tag('ul');
1034 * Return the representation day
1036 * @param int $tstamp Timestamp in GMT
1037 * @param int $now current Unix timestamp
1038 * @param bool $usecommonwords
1039 * @return string the formatted date/time
1041 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1043 static $shortformat;
1044 if(empty($shortformat)) {
1045 $shortformat = get_string('strftimedayshort');
1048 if($now === false) {
1052 // To have it in one place, if a change is needed
1053 $formal = userdate($tstamp, $shortformat);
1055 $datestamp = usergetdate($tstamp);
1056 $datenow = usergetdate($now);
1058 if($usecommonwords == false) {
1059 // We don't want words, just a date
1062 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1064 return get_string('today', 'calendar');
1067 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1068 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
1071 return get_string('yesterday', 'calendar');
1074 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] +
1 ) ||
1075 ($datestamp['year'] == $datenow['year'] +
1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
1078 return get_string('tomorrow', 'calendar');
1086 * return the formatted representation time
1088 * @param int $time the timestamp in UTC, as obtained from the database
1089 * @return string the formatted date/time
1091 function calendar_time_representation($time) {
1092 static $langtimeformat = NULL;
1093 if($langtimeformat === NULL) {
1094 $langtimeformat = get_string('strftimetime');
1096 $timeformat = get_user_preferences('calendar_timeformat');
1097 if(empty($timeformat)){
1098 $timeformat = get_config(NULL,'calendar_site_timeformat');
1100 // The ? is needed because the preference might be present, but empty
1101 return userdate($time, empty($timeformat) ?
$langtimeformat : $timeformat);
1105 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1107 * @param string|moodle_url $linkbase
1108 * @param int $d The number of the day.
1109 * @param int $m The number of the month.
1110 * @param int $y The number of the year.
1111 * @return moodle_url|null $linkbase
1113 function calendar_get_link_href($linkbase, $d, $m, $y) {
1114 if (empty($linkbase)) {
1117 if (!($linkbase instanceof moodle_url
)) {
1118 $linkbase = new moodle_url($linkbase);
1121 $linkbase->param('cal_d', $d);
1124 $linkbase->param('cal_m', $m);
1127 $linkbase->param('cal_y', $y);
1133 * Build and return a previous month HTML link, with an arrow.
1135 * @param string $text The text label.
1136 * @param string|moodle_url $linkbase The URL stub.
1137 * @param int $d The number of the date.
1138 * @param int $m The number of the month.
1139 * @param int $y year The number of the year.
1140 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1141 * @return string HTML string.
1143 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide=false) {
1144 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1148 return link_arrow_left($text, (string)$href, $accesshide, 'previous');
1152 * Build and return a next month HTML link, with an arrow.
1154 * @param string $text The text label.
1155 * @param string|moodle_url $linkbase The URL stub.
1156 * @param int $d the number of the Day
1157 * @param int $m The number of the month.
1158 * @param int $y The number of the year.
1159 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1160 * @return string HTML string.
1162 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide=false) {
1163 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1167 return link_arrow_right($text, (string)$href, $accesshide, 'next');
1171 * Return the name of the weekday
1173 * @param string $englishname
1174 * @return string of the weekeday
1176 function calendar_wday_name($englishname) {
1177 return get_string(strtolower($englishname), 'calendar');
1181 * Return the number of days in month
1183 * @param int $month the number of the month.
1184 * @param int $year the number of the year
1187 function calendar_days_in_month($month, $year) {
1188 return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
1192 * Get the upcoming event block
1194 * @param array $events list of events
1195 * @param moodle_url|string $linkhref link to event referer
1196 * @return string|null $content html block content
1198 function calendar_get_block_upcoming($events, $linkhref = NULL) {
1200 $lines = count($events);
1205 for ($i = 0; $i < $lines; ++
$i) {
1206 if (!isset($events[$i]->time
)) { // Just for robustness
1209 $events[$i] = calendar_add_event_metadata($events[$i]);
1210 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon
.'</span>';
1211 if (!empty($events[$i]->referer
)) {
1212 // That's an activity event, so let's provide the hyperlink
1213 $content .= $events[$i]->referer
;
1215 if(!empty($linkhref)) {
1216 $ed = usergetdate($events[$i]->timestart
);
1217 $href = calendar_get_link_href(new moodle_url(CALENDAR_URL
.$linkhref), $ed['mday'], $ed['mon'], $ed['year']);
1218 $href->set_anchor('event_'.$events[$i]->id
);
1219 $content .= html_writer
::link($href, $events[$i]->name
);
1222 $content .= $events[$i]->name
;
1225 $events[$i]->time
= str_replace('»', '<br />»', $events[$i]->time
);
1226 $content .= '<div class="date">'.$events[$i]->time
.'</div></div>';
1227 if ($i < $lines - 1) $content .= '<hr />';
1234 * Get the next following month
1236 * If the current month is December, it will get the first month of the following year.
1239 * @param int $month the number of the month.
1240 * @param int $year the number of the year.
1241 * @return array the following month
1243 function calendar_add_month($month, $year) {
1245 return array(1, $year +
1);
1248 return array($month +
1, $year);
1253 * Get the previous month
1255 * If the current month is January, it will get the last month of the previous year.
1257 * @param int $month the number of the month.
1258 * @param int $year the number of the year.
1259 * @return array previous month
1261 function calendar_sub_month($month, $year) {
1263 return array(12, $year - 1);
1266 return array($month - 1, $year);
1271 * Get per-day basis events
1273 * @param array $events list of events
1274 * @param int $month the number of the month
1275 * @param int $year the number of the year
1276 * @param array $eventsbyday event on specific day
1277 * @param array $durationbyday duration of the event in days
1278 * @param array $typesbyday event type (eg: global, course, user, or group)
1279 * @param array $courses list of courses
1282 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1283 $eventsbyday = array();
1284 $typesbyday = array();
1285 $durationbyday = array();
1287 if($events === false) {
1291 foreach($events as $event) {
1293 $startdate = usergetdate($event->timestart
);
1294 // Set end date = start date if no duration
1295 if ($event->timeduration
) {
1296 $enddate = usergetdate($event->timestart +
$event->timeduration
- 1);
1298 $enddate = $startdate;
1301 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
1302 if(!($startdate['year'] * 13 +
$startdate['mon'] <= $year * 13 +
$month) && ($enddate['year'] * 13 +
$enddate['mon'] >= $year * 13 +
$month)) {
1307 $eventdaystart = intval($startdate['mday']);
1309 if($startdate['mon'] == $month && $startdate['year'] == $year) {
1310 // Give the event to its day
1311 $eventsbyday[$eventdaystart][] = $event->id
;
1313 // Mark the day as having such an event
1314 if($event->courseid
== SITEID
&& $event->groupid
== 0) {
1315 $typesbyday[$eventdaystart]['startglobal'] = true;
1316 // Set event class for global event
1317 $events[$event->id
]->class = 'calendar_event_global';
1319 else if($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) {
1320 $typesbyday[$eventdaystart]['startcourse'] = true;
1321 // Set event class for course event
1322 $events[$event->id
]->class = 'calendar_event_course';
1324 else if($event->groupid
) {
1325 $typesbyday[$eventdaystart]['startgroup'] = true;
1326 // Set event class for group event
1327 $events[$event->id
]->class = 'calendar_event_group';
1329 else if($event->userid
) {
1330 $typesbyday[$eventdaystart]['startuser'] = true;
1331 // Set event class for user event
1332 $events[$event->id
]->class = 'calendar_event_user';
1336 if($event->timeduration
== 0) {
1337 // Proceed with the next
1341 // The event starts on $month $year or before. So...
1342 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ?
intval($startdate['mday']) : 0;
1344 // Also, it ends on $month $year or later...
1345 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ?
intval($enddate['mday']) : calendar_days_in_month($month, $year);
1347 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1348 for($i = $lowerbound +
1; $i <= $upperbound; ++
$i) {
1349 $durationbyday[$i][] = $event->id
;
1350 if($event->courseid
== SITEID
&& $event->groupid
== 0) {
1351 $typesbyday[$i]['durationglobal'] = true;
1353 else if($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) {
1354 $typesbyday[$i]['durationcourse'] = true;
1356 else if($event->groupid
) {
1357 $typesbyday[$i]['durationgroup'] = true;
1359 else if($event->userid
) {
1360 $typesbyday[$i]['durationuser'] = true;
1369 * Get current module cache
1371 * @param array $coursecache list of course cache
1372 * @param string $modulename name of the module
1373 * @param int $instance module instance number
1374 * @return stdClass|bool $module information
1376 function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1377 $module = get_coursemodule_from_instance($modulename, $instance);
1379 if($module === false) return false;
1380 if(!calendar_get_course_cached($coursecache, $module->course
)) {
1387 * Get current course cache
1389 * @param array $coursecache list of course cache
1390 * @param int $courseid id of the course
1391 * @return stdClass $coursecache[$courseid] return the specific course cache
1393 function calendar_get_course_cached(&$coursecache, $courseid) {
1394 global $COURSE, $DB;
1396 if (!isset($coursecache[$courseid])) {
1397 if ($courseid == $COURSE->id
) {
1398 $coursecache[$courseid] = $COURSE;
1400 $coursecache[$courseid] = $DB->get_record('course', array('id'=>$courseid));
1403 return $coursecache[$courseid];
1407 * Returns the courses to load events for, the
1409 * @param array $courseeventsfrom An array of courses to load calendar events for
1410 * @param bool $ignorefilters specify the use of filters, false is set as default
1411 * @return array An array of courses, groups, and user to load calendar events for based upon filters
1413 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
1414 global $USER, $CFG, $DB;
1416 // For backwards compatability we have to check whether the courses array contains
1417 // just id's in which case we need to load course objects.
1418 $coursestoload = array();
1419 foreach ($courseeventsfrom as $id => $something) {
1420 if (!is_object($something)) {
1421 $coursestoload[] = $id;
1422 unset($courseeventsfrom[$id]);
1425 if (!empty($coursestoload)) {
1426 // TODO remove this in 2.2
1427 debugging('calendar_set_filters now preferes an array of course objects with preloaded contexts', DEBUG_DEVELOPER
);
1428 $courseeventsfrom = array_merge($courseeventsfrom, $DB->get_records_list('course', 'id', $coursestoload));
1435 // capabilities that allow seeing group events from all groups
1436 // TODO: rewrite so that moodle/calendar:manageentries is not necessary here
1437 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
1439 $isloggedin = isloggedin();
1441 if ($ignorefilters ||
calendar_show_event_type(CALENDAR_EVENT_COURSE
)) {
1442 $courses = array_keys($courseeventsfrom);
1444 if ($ignorefilters ||
calendar_show_event_type(CALENDAR_EVENT_GLOBAL
)) {
1445 $courses[] = SITEID
;
1447 $courses = array_unique($courses);
1450 if (!empty($courses) && in_array(SITEID
, $courses)) {
1451 // Sort courses for consistent colour highlighting
1452 // Effectively ignoring SITEID as setting as last course id
1453 $key = array_search(SITEID
, $courses);
1454 unset($courses[$key]);
1455 $courses[] = SITEID
;
1458 if ($ignorefilters ||
($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER
))) {
1462 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP
) ||
$ignorefilters)) {
1464 if (count($courseeventsfrom)==1) {
1465 $course = reset($courseeventsfrom);
1466 if (has_any_capability($allgroupscaps, context_course
::instance($course->id
))) {
1467 $coursegroups = groups_get_all_groups($course->id
, 0, 0, 'g.id');
1468 $group = array_keys($coursegroups);
1471 if ($group === false) {
1472 if (!empty($CFG->calendar_adminseesall
) && has_any_capability($allgroupscaps, get_system_context())) {
1474 } else if ($isloggedin) {
1475 $groupids = array();
1477 // We already have the courses to examine in $courses
1478 // For each course...
1479 foreach ($courseeventsfrom as $courseid => $course) {
1480 // If the user is an editing teacher in there,
1481 if (!empty($USER->groupmember
[$course->id
])) {
1482 // We've already cached the users groups for this course so we can just use that
1483 $groupids = array_merge($groupids, $USER->groupmember
[$course->id
]);
1484 } else if ($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
1485 // If this course has groups, show events from all of those related to the current user
1486 $coursegroups = groups_get_user_groups($course->id
, $USER->id
);
1487 $groupids = array_merge($groupids, $coursegroups['0']);
1490 if (!empty($groupids)) {
1496 if (empty($courses)) {
1500 return array($courses, $group, $user);
1504 * Return the capability for editing calendar event
1506 * @param calendar_event $event event object
1507 * @return bool capability to edit event
1509 function calendar_edit_event_allowed($event) {
1512 // Must be logged in
1513 if (!isloggedin()) {
1517 // can not be using guest account
1518 if (isguestuser()) {
1522 // You cannot edit calendar subscription events presently.
1523 if (!empty($event->subscriptionid
)) {
1527 $sitecontext = context_system
::instance();
1528 // if user has manageentries at site level, return true
1529 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1533 // if groupid is set, it's definitely a group event
1534 if (!empty($event->groupid
)) {
1535 // Allow users to add/edit group events if:
1536 // 1) They have manageentries (= entries for whole course)
1537 // 2) They have managegroupentries AND are in the group
1538 $group = $DB->get_record('groups', array('id'=>$event->groupid
));
1540 has_capability('moodle/calendar:manageentries', $event->context
) ||
1541 (has_capability('moodle/calendar:managegroupentries', $event->context
)
1542 && groups_is_member($event->groupid
)));
1543 } else if (!empty($event->courseid
)) {
1544 // if groupid is not set, but course is set,
1545 // it's definiely a course event
1546 return has_capability('moodle/calendar:manageentries', $event->context
);
1547 } else if (!empty($event->userid
) && $event->userid
== $USER->id
) {
1548 // if course is not set, but userid id set, it's a user event
1549 return (has_capability('moodle/calendar:manageownentries', $event->context
));
1550 } else if (!empty($event->userid
)) {
1551 return (has_capability('moodle/calendar:manageentries', $event->context
));
1557 * Returns the default courses to display on the calendar when there isn't a specific
1558 * course to display.
1560 * @return array $courses Array of courses to display
1562 function calendar_get_default_courses() {
1565 if (!isloggedin()) {
1570 if (!empty($CFG->calendar_adminseesall
) && has_capability('moodle/calendar:manageentries', context_system
::instance())) {
1571 list ($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
1572 $sql = "SELECT c.* $select
1575 WHERE EXISTS (SELECT 1 FROM {event} e WHERE e.courseid = c.id)
1577 $courses = $DB->get_records_sql($sql, null, 0, 20);
1578 foreach ($courses as $course) {
1579 context_helper
::preload_from_record($course);
1584 $courses = enrol_get_my_courses();
1590 * Display calendar preference button
1592 * @param stdClass $course course object
1593 * @return string return preference button in html
1595 function calendar_preferences_button(stdClass
$course) {
1598 // Guests have no preferences
1599 if (!isloggedin() ||
isguestuser()) {
1603 return $OUTPUT->single_button(new moodle_url('/calendar/preferences.php', array('course' => $course->id
)), get_string("preferences", "calendar"));
1607 * Get event format time
1609 * @param calendar_event $event event object
1610 * @param int $now current time in gmt
1611 * @param array $linkparams list of params for event link
1612 * @param bool $usecommonwords the words as formatted date/time.
1613 * @param int $showtime determine the show time GMT timestamp
1614 * @return string $eventtime link/string for event time
1616 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime=0) {
1617 $startdate = usergetdate($event->timestart
);
1618 $enddate = usergetdate($event->timestart +
$event->timeduration
);
1619 $usermidnightstart = usergetmidnight($event->timestart
);
1621 if($event->timeduration
) {
1622 // To avoid doing the math if one IF is enough :)
1623 $usermidnightend = usergetmidnight($event->timestart +
$event->timeduration
);
1626 $usermidnightend = $usermidnightstart;
1629 if (empty($linkparams) ||
!is_array($linkparams)) {
1630 $linkparams = array();
1632 $linkparams['view'] = 'day';
1634 // OK, now to get a meaningful display...
1635 // First of all we have to construct a human-readable date/time representation
1637 if($event->timeduration
) {
1638 // It has a duration
1639 if($usermidnightstart == $usermidnightend ||
1640 ($event->timestart
== $usermidnightstart) && ($event->timeduration
== 86400 ||
$event->timeduration
== 86399) ||
1641 ($event->timestart +
$event->timeduration
<= $usermidnightstart +
86400)) {
1642 // But it's all on the same day
1643 $timestart = calendar_time_representation($event->timestart
);
1644 $timeend = calendar_time_representation($event->timestart +
$event->timeduration
);
1645 $time = $timestart.' <strong>»</strong> '.$timeend;
1647 if ($event->timestart
== $usermidnightstart && ($event->timeduration
== 86400 ||
$event->timeduration
== 86399)) {
1648 $time = get_string('allday', 'calendar');
1651 // Set printable representation
1653 $day = calendar_day_representation($event->timestart
, $now, $usecommonwords);
1654 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1655 $eventtime = html_writer
::link($url, $day).', '.$time;
1660 // It spans two or more days
1661 $daystart = calendar_day_representation($event->timestart
, $now, $usecommonwords).', ';
1662 if ($showtime == $usermidnightstart) {
1665 $timestart = calendar_time_representation($event->timestart
);
1666 $dayend = calendar_day_representation($event->timestart +
$event->timeduration
, $now, $usecommonwords).', ';
1667 if ($showtime == $usermidnightend) {
1670 $timeend = calendar_time_representation($event->timestart +
$event->timeduration
);
1672 // Set printable representation
1673 if ($now >= $usermidnightstart && $now < ($usermidnightstart +
86400)) {
1674 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1675 $eventtime = $timestart.' <strong>»</strong> '.html_writer
::link($url, $dayend).$timeend;
1677 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1678 $eventtime = html_writer
::link($url, $daystart).$timestart.' <strong>»</strong> ';
1680 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1681 $eventtime .= html_writer
::link($url, $dayend).$timeend;
1685 $time = calendar_time_representation($event->timestart
);
1687 // Set printable representation
1689 $day = calendar_day_representation($event->timestart
, $now, $usecommonwords);
1690 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1691 $eventtime = html_writer
::link($url, $day).', '.trim($time);
1697 if($event->timestart +
$event->timeduration
< $now) {
1699 $eventtime = '<span class="dimmed_text">'.str_replace(' href=', ' class="dimmed" href=', $eventtime).'</span>';
1706 * Display month selector options
1708 * @param string $name for the select element
1709 * @param string|array $selected options for select elements
1711 function calendar_print_month_selector($name, $selected) {
1713 for ($i=1; $i<=12; $i++
) {
1714 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
1716 echo html_writer
::label(get_string('months'), 'menu'. $name, false, array('class' => 'accesshide'));
1717 echo html_writer
::select($months, $name, $selected, false);
1721 * Checks to see if the requested type of event should be shown for the given user.
1723 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
1724 * The type to check the display for (default is to display all)
1725 * @param stdClass|int|null $user The user to check for - by default the current user
1726 * @return bool True if the tyep should be displayed false otherwise
1728 function calendar_show_event_type($type, $user = null) {
1729 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER
;
1730 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
1732 if (!isset($SESSION->calendarshoweventtype
)) {
1733 $SESSION->calendarshoweventtype
= $default;
1735 return $SESSION->calendarshoweventtype
& $type;
1737 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
1742 * Sets the display of the event type given $display.
1744 * If $display = true the event type will be shown.
1745 * If $display = false the event type will NOT be shown.
1746 * If $display = null the current value will be toggled and saved.
1748 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type object of CALENDAR_EVENT_XXX
1749 * @param bool $display option to display event type
1750 * @param stdClass|int $user moodle user object or id, null means current user
1752 function calendar_set_event_type_display($type, $display = null, $user = null) {
1753 $persist = get_user_preferences('calendar_persistflt', 0, $user);
1754 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER
;
1755 if ($persist === 0) {
1757 if (!isset($SESSION->calendarshoweventtype
)) {
1758 $SESSION->calendarshoweventtype
= $default;
1760 $preference = $SESSION->calendarshoweventtype
;
1762 $preference = get_user_preferences('calendar_savedflt', $default, $user);
1764 $current = $preference & $type;
1765 if ($display === null) {
1766 $display = !$current;
1768 if ($display && !$current) {
1769 $preference +
= $type;
1770 } else if (!$display && $current) {
1771 $preference -= $type;
1773 if ($persist === 0) {
1774 $SESSION->calendarshoweventtype
= $preference;
1776 if ($preference == $default) {
1777 unset_user_preference('calendar_savedflt', $user);
1779 set_user_preference('calendar_savedflt', $preference, $user);
1785 * Get calendar's allowed types
1787 * @param stdClass $allowed list of allowed edit for event type
1788 * @param stdClass|int $course object of a course or course id
1790 function calendar_get_allowed_types(&$allowed, $course = null) {
1791 global $USER, $CFG, $DB;
1792 $allowed = new stdClass();
1793 $allowed->user
= has_capability('moodle/calendar:manageownentries', get_system_context());
1794 $allowed->groups
= false; // This may change just below
1795 $allowed->courses
= false; // This may change just below
1796 $allowed->site
= has_capability('moodle/calendar:manageentries', context_course
::instance(SITEID
));
1798 if (!empty($course)) {
1799 if (!is_object($course)) {
1800 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST
);
1802 if ($course->id
!= SITEID
) {
1803 $coursecontext = context_course
::instance($course->id
);
1804 $allowed->user
= has_capability('moodle/calendar:manageownentries', $coursecontext);
1806 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
1807 $allowed->courses
= array($course->id
=> 1);
1809 if ($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
1810 if (has_capability('moodle/site:accessallgroups', $coursecontext)) {
1811 $allowed->groups
= groups_get_all_groups($course->id
);
1813 $allowed->groups
= groups_get_all_groups($course->id
, $USER->id
);
1816 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
1817 if($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
1818 if (has_capability('moodle/site:accessallgroups', $coursecontext)) {
1819 $allowed->groups
= groups_get_all_groups($course->id
);
1821 $allowed->groups
= groups_get_all_groups($course->id
, $USER->id
);
1830 * See if user can add calendar entries at all
1831 * used to print the "New Event" button
1833 * @param stdClass $course object of a course or course id
1834 * @return bool has the capability to add at least one event type
1836 function calendar_user_can_add_event($course) {
1837 if (!isloggedin() ||
isguestuser()) {
1840 calendar_get_allowed_types($allowed, $course);
1841 return (bool)($allowed->user ||
$allowed->groups ||
$allowed->courses ||
$allowed->site
);
1845 * Check wether the current user is permitted to add events
1847 * @param stdClass $event object of event
1848 * @return bool has the capability to add event
1850 function calendar_add_event_allowed($event) {
1853 // can not be using guest account
1854 if (!isloggedin() or isguestuser()) {
1858 $sitecontext = context_system
::instance();
1859 // if user has manageentries at site level, always return true
1860 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1864 switch ($event->eventtype
) {
1866 return has_capability('moodle/calendar:manageentries', $event->context
);
1869 // Allow users to add/edit group events if:
1870 // 1) They have manageentries (= entries for whole course)
1871 // 2) They have managegroupentries AND are in the group
1872 $group = $DB->get_record('groups', array('id'=>$event->groupid
));
1874 has_capability('moodle/calendar:manageentries', $event->context
) ||
1875 (has_capability('moodle/calendar:managegroupentries', $event->context
)
1876 && groups_is_member($event->groupid
)));
1879 if ($event->userid
== $USER->id
) {
1880 return (has_capability('moodle/calendar:manageownentries', $event->context
));
1882 //there is no 'break;' intentionally
1885 return has_capability('moodle/calendar:manageentries', $event->context
);
1888 return has_capability('moodle/calendar:manageentries', $event->context
);
1893 * Manage calendar events
1895 * This class provides the required functionality in order to manage calendar events.
1896 * It was introduced as part of Moodle 2.0 and was created in order to provide a
1897 * better framework for dealing with calendar events in particular regard to file
1898 * handling through the new file API
1900 * @package core_calendar
1901 * @category calendar
1902 * @copyright 2009 Sam Hemelryk
1903 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1905 * @property int $id The id within the event table
1906 * @property string $name The name of the event
1907 * @property string $description The description of the event
1908 * @property int $format The format of the description FORMAT_?
1909 * @property int $courseid The course the event is associated with (0 if none)
1910 * @property int $groupid The group the event is associated with (0 if none)
1911 * @property int $userid The user the event is associated with (0 if none)
1912 * @property int $repeatid If this is a repeated event this will be set to the
1913 * id of the original
1914 * @property string $modulename If added by a module this will be the module name
1915 * @property int $instance If added by a module this will be the module instance
1916 * @property string $eventtype The event type
1917 * @property int $timestart The start time as a timestamp
1918 * @property int $timeduration The duration of the event in seconds
1919 * @property int $visible 1 if the event is visible
1920 * @property int $uuid ?
1921 * @property int $sequence ?
1922 * @property int $timemodified The time last modified as a timestamp
1924 class calendar_event
{
1926 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
1927 protected $properties = null;
1930 * @var string The converted event discription with file paths resolved. This gets populated when someone requests description for the first time */
1931 protected $_description = null;
1933 /** @var array The options to use with this description editor */
1934 protected $editoroptions = array(
1936 'forcehttps'=>false,
1939 'trusttext'=>false);
1941 /** @var object The context to use with the description editor */
1942 protected $editorcontext = null;
1945 * Instantiates a new event and optionally populates its properties with the
1948 * @param stdClass $data Optional. An object containing the properties to for
1951 public function __construct($data=null) {
1954 // First convert to object if it is not already (should either be object or assoc array)
1955 if (!is_object($data)) {
1956 $data = (object)$data;
1959 $this->editoroptions
['maxbytes'] = $CFG->maxbytes
;
1961 $data->eventrepeats
= 0;
1963 if (empty($data->id
)) {
1967 if (!empty($data->subscriptionid
)) {
1968 $data->subscription
= calendar_get_subscription($data->subscriptionid
);
1971 // Default to a user event
1972 if (empty($data->eventtype
)) {
1973 $data->eventtype
= 'user';
1976 // Default to the current user
1977 if (empty($data->userid
)) {
1978 $data->userid
= $USER->id
;
1981 if (!empty($data->timeduration
) && is_array($data->timeduration
)) {
1982 $data->timeduration
= make_timestamp($data->timeduration
['year'], $data->timeduration
['month'], $data->timeduration
['day'], $data->timeduration
['hour'], $data->timeduration
['minute']) - $data->timestart
;
1984 if (!empty($data->description
) && is_array($data->description
)) {
1985 $data->format
= $data->description
['format'];
1986 $data->description
= $data->description
['text'];
1987 } else if (empty($data->description
)) {
1988 $data->description
= '';
1989 $data->format
= editors_get_preferred_format();
1991 // Ensure form is defaulted correctly
1992 if (empty($data->format
)) {
1993 $data->format
= editors_get_preferred_format();
1996 if (empty($data->context
)) {
1997 $data->context
= $this->calculate_context($data);
1999 $this->properties
= $data;
2003 * Magic property method
2005 * Attempts to call a set_$key method if one exists otherwise falls back
2006 * to simply set the property
2008 * @param string $key property name
2009 * @param mixed $value value of the property
2011 public function __set($key, $value) {
2012 if (method_exists($this, 'set_'.$key)) {
2013 $this->{'set_'.$key}($value);
2015 $this->properties
->{$key} = $value;
2021 * Attempts to call a get_$key method to return the property and ralls over
2022 * to return the raw property
2024 * @param string $key property name
2025 * @return mixed property value
2027 public function __get($key) {
2028 if (method_exists($this, 'get_'.$key)) {
2029 return $this->{'get_'.$key}();
2031 if (!isset($this->properties
->{$key})) {
2032 throw new coding_exception('Undefined property requested');
2034 return $this->properties
->{$key};
2038 * Stupid PHP needs an isset magic method if you use the get magic method and
2039 * still want empty calls to work.... blah ~!
2041 * @param string $key $key property name
2042 * @return bool|mixed property value, false if property is not exist
2044 public function __isset($key) {
2045 return !empty($this->properties
->{$key});
2049 * Calculate the context value needed for calendar_event.
2050 * Event's type can be determine by the available value store in $data
2051 * It is important to check for the existence of course/courseid to determine
2053 * Default value is set to CONTEXT_USER
2055 * @param stdClass $data information about event
2056 * @return stdClass The context object.
2058 protected function calculate_context(stdClass
$data) {
2062 if (isset($data->courseid
) && $data->courseid
> 0) {
2063 $context = context_course
::instance($data->courseid
);
2064 } else if (isset($data->course
) && $data->course
> 0) {
2065 $context = context_course
::instance($data->course
);
2066 } else if (isset($data->groupid
) && $data->groupid
> 0) {
2067 $group = $DB->get_record('groups', array('id'=>$data->groupid
));
2068 $context = context_course
::instance($group->courseid
);
2069 } else if (isset($data->userid
) && $data->userid
> 0 && $data->userid
== $USER->id
) {
2070 $context = context_user
::instance($data->userid
);
2071 } else if (isset($data->userid
) && $data->userid
> 0 && $data->userid
!= $USER->id
&&
2072 isset($data->instance
) && $data->instance
> 0) {
2073 $cm = get_coursemodule_from_instance($data->modulename
, $data->instance
, 0, false, MUST_EXIST
);
2074 $context = context_course
::instance($cm->course
);
2076 $context = context_user
::instance($data->userid
);
2083 * Returns an array of editoroptions for this event: Called by __get
2084 * Please use $blah = $event->editoroptions;
2086 * @return array event editor options
2088 protected function get_editoroptions() {
2089 return $this->editoroptions
;
2093 * Returns an event description: Called by __get
2094 * Please use $blah = $event->description;
2096 * @return string event description
2098 protected function get_description() {
2101 require_once($CFG->libdir
. '/filelib.php');
2103 if ($this->_description
=== null) {
2104 // Check if we have already resolved the context for this event
2105 if ($this->editorcontext
=== null) {
2106 // Switch on the event type to decide upon the appropriate context
2107 // to use for this event
2108 $this->editorcontext
= $this->properties
->context
;
2109 if ($this->properties
->eventtype
!= 'user' && $this->properties
->eventtype
!= 'course'
2110 && $this->properties
->eventtype
!= 'site' && $this->properties
->eventtype
!= 'group') {
2111 return clean_text($this->properties
->description
, $this->properties
->format
);
2115 // Work out the item id for the editor, if this is a repeated event then the files will
2116 // be associated with the original
2117 if (!empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
2118 $itemid = $this->properties
->repeatid
;
2120 $itemid = $this->properties
->id
;
2123 // Convert file paths in the description so that things display correctly
2124 $this->_description
= file_rewrite_pluginfile_urls($this->properties
->description
, 'pluginfile.php', $this->editorcontext
->id
, 'calendar', 'event_description', $itemid);
2125 // Clean the text so no nasties get through
2126 $this->_description
= clean_text($this->_description
, $this->properties
->format
);
2128 // Finally return the description
2129 return $this->_description
;
2133 * Return the number of repeat events there are in this events series
2135 * @return int number of event repeated
2137 public function count_repeats() {
2139 if (!empty($this->properties
->repeatid
)) {
2140 $this->properties
->eventrepeats
= $DB->count_records('event', array('repeatid'=>$this->properties
->repeatid
));
2141 // We don't want to count ourselves
2142 $this->properties
->eventrepeats
--;
2144 return $this->properties
->eventrepeats
;
2148 * Update or create an event within the database
2150 * Pass in a object containing the event properties and this function will
2151 * insert it into the database and deal with any associated files
2154 * @see update_event()
2156 * @param stdClass $data object of event
2157 * @param bool $checkcapability if moodle should check calendar managing capability or not
2158 * @return bool event updated
2160 public function update($data, $checkcapability=true) {
2161 global $CFG, $DB, $USER;
2163 foreach ($data as $key=>$value) {
2164 $this->properties
->$key = $value;
2167 $this->properties
->timemodified
= time();
2168 $usingeditor = (!empty($this->properties
->description
) && is_array($this->properties
->description
));
2170 if (empty($this->properties
->id
) ||
$this->properties
->id
< 1) {
2172 if ($checkcapability) {
2173 if (!calendar_add_event_allowed($this->properties
)) {
2174 print_error('nopermissiontoupdatecalendar');
2179 switch ($this->properties
->eventtype
) {
2181 $this->properties
->courseid
= 0;
2182 $this->properties
->course
= 0;
2183 $this->properties
->groupid
= 0;
2184 $this->properties
->userid
= $USER->id
;
2187 $this->properties
->courseid
= SITEID
;
2188 $this->properties
->course
= SITEID
;
2189 $this->properties
->groupid
= 0;
2190 $this->properties
->userid
= $USER->id
;
2193 $this->properties
->groupid
= 0;
2194 $this->properties
->userid
= $USER->id
;
2197 $this->properties
->userid
= $USER->id
;
2200 // Ewww we should NEVER get here, but just incase we do lets
2202 $usingeditor = false;
2206 // If we are actually using the editor, we recalculate the context because some default values
2207 // were set when calculate_context() was called from the constructor.
2209 $this->properties
->context
= $this->calculate_context($this->properties
);
2210 $this->editorcontext
= $this->properties
->context
;
2213 $editor = $this->properties
->description
;
2214 $this->properties
->format
= $this->properties
->description
['format'];
2215 $this->properties
->description
= $this->properties
->description
['text'];
2218 // Insert the event into the database
2219 $this->properties
->id
= $DB->insert_record('event', $this->properties
);
2222 $this->properties
->description
= file_save_draft_area_files(
2224 $this->editorcontext
->id
,
2226 'event_description',
2227 $this->properties
->id
,
2228 $this->editoroptions
,
2230 $this->editoroptions
['forcehttps']);
2231 $DB->set_field('event', 'description', $this->properties
->description
, array('id'=>$this->properties
->id
));
2234 // Log the event entry.
2235 add_to_log($this->properties
->courseid
, 'calendar', 'add', 'event.php?action=edit&id='.$this->properties
->id
, $this->properties
->name
);
2237 $repeatedids = array();
2239 if (!empty($this->properties
->repeat
)) {
2240 $this->properties
->repeatid
= $this->properties
->id
;
2241 $DB->set_field('event', 'repeatid', $this->properties
->repeatid
, array('id'=>$this->properties
->id
));
2243 $eventcopy = clone($this->properties
);
2244 unset($eventcopy->id
);
2246 for($i = 1; $i < $eventcopy->repeats
; $i++
) {
2248 $eventcopy->timestart
= ($eventcopy->timestart+WEEKSECS
) +
dst_offset_on($eventcopy->timestart
) - dst_offset_on($eventcopy->timestart+WEEKSECS
);
2250 // Get the event id for the log record.
2251 $eventcopyid = $DB->insert_record('event', $eventcopy);
2253 // If the context has been set delete all associated files
2255 $fs = get_file_storage();
2256 $files = $fs->get_area_files($this->editorcontext
->id
, 'calendar', 'event_description', $this->properties
->id
);
2257 foreach ($files as $file) {
2258 $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
2262 $repeatedids[] = $eventcopyid;
2263 // Log the event entry.
2264 add_to_log($eventcopy->courseid
, 'calendar', 'add', 'event.php?action=edit&id='.$eventcopyid, $eventcopy->name
);
2268 // Hook for tracking added events
2269 self
::calendar_event_hook('add_event', array($this->properties
, $repeatedids));
2273 if ($checkcapability) {
2274 if(!calendar_edit_event_allowed($this->properties
)) {
2275 print_error('nopermissiontoupdatecalendar');
2280 if ($this->editorcontext
!== null) {
2281 $this->properties
->description
= file_save_draft_area_files(
2282 $this->properties
->description
['itemid'],
2283 $this->editorcontext
->id
,
2285 'event_description',
2286 $this->properties
->id
,
2287 $this->editoroptions
,
2288 $this->properties
->description
['text'],
2289 $this->editoroptions
['forcehttps']);
2291 $this->properties
->format
= $this->properties
->description
['format'];
2292 $this->properties
->description
= $this->properties
->description
['text'];
2296 $event = $DB->get_record('event', array('id'=>$this->properties
->id
));
2298 $updaterepeated = (!empty($this->properties
->repeatid
) && !empty($this->properties
->repeateditall
));
2300 if ($updaterepeated) {
2302 if ($this->properties
->timestart
!= $event->timestart
) {
2303 $timestartoffset = $this->properties
->timestart
- $event->timestart
;
2304 $sql = "UPDATE {event}
2307 timestart = timestart + ?,
2310 WHERE repeatid = ?";
2311 $params = array($this->properties
->name
, $this->properties
->description
, $timestartoffset, $this->properties
->timeduration
, time(), $event->repeatid
);
2313 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
2314 $params = array($this->properties
->name
, $this->properties
->description
, $this->properties
->timeduration
, time(), $event->repeatid
);
2316 $DB->execute($sql, $params);
2318 // Log the event update.
2319 add_to_log($this->properties
->courseid
, 'calendar', 'edit all', 'event.php?action=edit&id='.$this->properties
->id
, $this->properties
->name
);
2321 $DB->update_record('event', $this->properties
);
2322 $event = calendar_event
::load($this->properties
->id
);
2323 $this->properties
= $event->properties();
2324 add_to_log($this->properties
->courseid
, 'calendar', 'edit', 'event.php?action=edit&id='.$this->properties
->id
, $this->properties
->name
);
2327 // Hook for tracking event updates
2328 self
::calendar_event_hook('update_event', array($this->properties
, $updaterepeated));
2334 * Deletes an event and if selected an repeated events in the same series
2336 * This function deletes an event, any associated events if $deleterepeated=true,
2337 * and cleans up any files associated with the events.
2339 * @see delete_event()
2341 * @param bool $deleterepeated delete event repeatedly
2342 * @return bool succession of deleting event
2344 public function delete($deleterepeated=false) {
2347 // If $this->properties->id is not set then something is wrong
2348 if (empty($this->properties
->id
)) {
2349 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER
);
2354 $DB->delete_records('event', array('id'=>$this->properties
->id
));
2356 // If we are deleting parent of a repeated event series, promote the next event in the series as parent
2357 if (($this->properties
->id
== $this->properties
->repeatid
) && !$deleterepeated) {
2358 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC", array($this->properties
->id
), IGNORE_MULTIPLE
);
2359 if (!empty($newparent)) {
2360 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?", array($newparent, $this->properties
->id
));
2361 // Get all records where the repeatid is the same as the event being removed
2362 $events = $DB->get_records('event', array('repeatid' => $newparent));
2363 // For each of the returned events trigger the event_update hook.
2364 foreach ($events as $event) {
2365 self
::calendar_event_hook('update_event', array($event, false));
2370 // If the editor context hasn't already been set then set it now
2371 if ($this->editorcontext
=== null) {
2372 $this->editorcontext
= $this->properties
->context
;
2375 // If the context has been set delete all associated files
2376 if ($this->editorcontext
!== null) {
2377 $fs = get_file_storage();
2378 $files = $fs->get_area_files($this->editorcontext
->id
, 'calendar', 'event_description', $this->properties
->id
);
2379 foreach ($files as $file) {
2384 // Fire the event deleted hook
2385 self
::calendar_event_hook('delete_event', array($this->properties
->id
, $deleterepeated));
2387 // If we need to delete repeated events then we will fetch them all and delete one by one
2388 if ($deleterepeated && !empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
2389 // Get all records where the repeatid is the same as the event being removed
2390 $events = $DB->get_records('event', array('repeatid'=>$this->properties
->repeatid
));
2391 // For each of the returned events populate a calendar_event object and call delete
2392 // make sure the arg passed is false as we are already deleting all repeats
2393 foreach ($events as $event) {
2394 $event = new calendar_event($event);
2395 $event->delete(false);
2403 * Fetch all event properties
2405 * This function returns all of the events properties as an object and optionally
2406 * can prepare an editor for the description field at the same time. This is
2407 * designed to work when the properties are going to be used to set the default
2408 * values of a moodle forms form.
2410 * @param bool $prepareeditor If set to true a editor is prepared for use with
2411 * the mforms editor element. (for description)
2412 * @return stdClass Object containing event properties
2414 public function properties($prepareeditor=false) {
2415 global $USER, $CFG, $DB;
2417 // First take a copy of the properties. We don't want to actually change the
2418 // properties or we'd forever be converting back and forwards between an
2419 // editor formatted description and not
2420 $properties = clone($this->properties
);
2421 // Clean the description here
2422 $properties->description
= clean_text($properties->description
, $properties->format
);
2424 // If set to true we need to prepare the properties for use with an editor
2425 // and prepare the file area
2426 if ($prepareeditor) {
2428 // We may or may not have a property id. If we do then we need to work
2429 // out the context so we can copy the existing files to the draft area
2430 if (!empty($properties->id
)) {
2432 if ($properties->eventtype
=== 'site') {
2434 $this->editorcontext
= $this->properties
->context
;
2435 } else if ($properties->eventtype
=== 'user') {
2437 $this->editorcontext
= $this->properties
->context
;
2438 } else if ($properties->eventtype
=== 'group' ||
$properties->eventtype
=== 'course') {
2439 // First check the course is valid
2440 $course = $DB->get_record('course', array('id'=>$properties->courseid
));
2442 print_error('invalidcourse');
2445 $this->editorcontext
= $this->properties
->context
;
2446 // We have a course and are within the course context so we had
2447 // better use the courses max bytes value
2448 $this->editoroptions
['maxbytes'] = $course->maxbytes
;
2450 // If we get here we have a custom event type as used by some
2451 // modules. In this case the event will have been added by
2452 // code and we won't need the editor
2453 $this->editoroptions
['maxbytes'] = 0;
2454 $this->editoroptions
['maxfiles'] = 0;
2457 if (empty($this->editorcontext
) ||
empty($this->editorcontext
->id
)) {
2460 // Get the context id that is what we really want
2461 $contextid = $this->editorcontext
->id
;
2465 // If we get here then this is a new event in which case we don't need a
2466 // context as there is no existing files to copy to the draft area.
2470 // If the contextid === false we don't support files so no preparing
2472 if ($contextid !== false) {
2473 // Just encase it has already been submitted
2474 $draftiddescription = file_get_submitted_draft_itemid('description');
2475 // Prepare the draft area, this copies existing files to the draft area as well
2476 $properties->description
= file_prepare_draft_area($draftiddescription, $contextid, 'calendar', 'event_description', $properties->id
, $this->editoroptions
, $properties->description
);
2478 $draftiddescription = 0;
2481 // Structure the description field as the editor requires
2482 $properties->description
= array('text'=>$properties->description
, 'format'=>$properties->format
, 'itemid'=>$draftiddescription);
2485 // Finally return the properties
2490 * Toggles the visibility of an event
2492 * @param null|bool $force If it is left null the events visibility is flipped,
2493 * If it is false the event is made hidden, if it is true it
2495 * @return bool if event is successfully updated, toggle will be visible
2497 public function toggle_visibility($force=null) {
2500 // Set visible to the default if it is not already set
2501 if (empty($this->properties
->visible
)) {
2502 $this->properties
->visible
= 1;
2505 if ($force === true ||
($force !== false && $this->properties
->visible
== 0)) {
2506 // Make this event visible
2507 $this->properties
->visible
= 1;
2509 self
::calendar_event_hook('show_event', array($this->properties
));
2511 // Make this event hidden
2512 $this->properties
->visible
= 0;
2514 self
::calendar_event_hook('hide_event', array($this->properties
));
2517 // Update the database to reflect this change
2518 return $DB->set_field('event', 'visible', $this->properties
->visible
, array('id'=>$this->properties
->id
));
2522 * Attempts to call the hook for the specified action should a calendar type
2523 * by set $CFG->calendar, and the appopriate function defined
2525 * @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
2526 * @param array $args The args to pass to the hook, usually the event is the first element
2527 * @return bool attempts to call event hook
2529 public static function calendar_event_hook($action, array $args) {
2531 static $extcalendarinc;
2532 if ($extcalendarinc === null) {
2533 if (!empty($CFG->calendar
)) {
2534 if (is_readable($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
2535 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
2536 $extcalendarinc = true;
2538 debugging("Calendar lib file missing or not readable at /calendar/{$CFG->calendar}/lib.php.",
2540 $extcalendarinc = false;
2543 $extcalendarinc = false;
2546 if($extcalendarinc === false) {
2549 $hook = $CFG->calendar
.'_'.$action;
2550 if (function_exists($hook)) {
2551 call_user_func_array($hook, $args);
2558 * Returns a calendar_event object when provided with an event id
2560 * This function makes use of MUST_EXIST, if the event id passed in is invalid
2561 * it will result in an exception being thrown
2563 * @param int|object $param event object or event id
2564 * @return calendar_event|false status for loading calendar_event
2566 public static function load($param) {
2568 if (is_object($param)) {
2569 $event = new calendar_event($param);
2571 $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST
);
2572 $event = new calendar_event($event);
2578 * Creates a new event and returns a calendar_event object
2580 * @param object|array $properties An object containing event properties
2581 * @return calendar_event|false The event object or false if it failed
2583 public static function create($properties) {
2584 if (is_array($properties)) {
2585 $properties = (object)$properties;
2587 if (!is_object($properties)) {
2588 throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2590 $event = new calendar_event($properties);
2591 if ($event->update($properties)) {
2600 * Calendar information class
2602 * This class is used simply to organise the information pertaining to a calendar
2603 * and is used primarily to make information easily available.
2605 * @package core_calendar
2606 * @category calendar
2607 * @copyright 2010 Sam Hemelryk
2608 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2610 class calendar_information
{
2611 /** @var int The day */
2614 /** @var int The month */
2617 /** @var int The year */
2620 /** @var int A course id */
2621 public $courseid = null;
2623 /** @var array An array of courses */
2624 public $courses = array();
2626 /** @var array An array of groups */
2627 public $groups = array();
2629 /** @var array An array of users */
2630 public $users = array();
2633 * Creates a new instance
2635 * @param int $day the number of the day
2636 * @param int $month the number of the month
2637 * @param int $year the number of the year
2639 public function __construct($day=0, $month=0, $year=0) {
2641 $date = usergetdate(time());
2644 $day = $date['mday'];
2647 if (empty($month)) {
2648 $month = $date['mon'];
2652 $year = $date['year'];
2656 $this->month
= $month;
2657 $this->year
= $year;
2661 * Initialize calendar information
2663 * @param stdClass $course object
2664 * @param array $coursestoload An array of courses [$course->id => $course]
2665 * @param bool $ignorefilters options to use filter
2667 public function prepare_for_view(stdClass
$course, array $coursestoload, $ignorefilters = false) {
2668 $this->courseid
= $course->id
;
2669 $this->course
= $course;
2670 list($courses, $group, $user) = calendar_set_filters($coursestoload, $ignorefilters);
2671 $this->courses
= $courses;
2672 $this->groups
= $group;
2673 $this->users
= $user;
2677 * Ensures the date for the calendar is correct and either sets it to now
2678 * or throws a moodle_exception if not
2680 * @param bool $defaultonow use current time
2681 * @throws moodle_exception
2682 * @return bool validation of checkdate
2684 public function checkdate($defaultonow = true) {
2685 if (!checkdate($this->month
, $this->day
, $this->year
)) {
2687 $now = usergetdate(time());
2688 $this->day
= intval($now['mday']);
2689 $this->month
= intval($now['mon']);
2690 $this->year
= intval($now['year']);
2693 throw new moodle_exception('invaliddate');
2699 * Gets todays timestamp for the calendar
2701 * @return int today timestamp
2703 public function timestamp_today() {
2704 return make_timestamp($this->year
, $this->month
, $this->day
);
2707 * Gets tomorrows timestamp for the calendar
2709 * @return int tomorrow timestamp
2711 public function timestamp_tomorrow() {
2712 return make_timestamp($this->year
, $this->month
, $this->day+
1);
2715 * Adds the pretend blocks for the calendar
2717 * @param core_calendar_renderer $renderer
2718 * @param bool $showfilters display filters, false is set as default
2719 * @param string|null $view preference view options (eg: day, month, upcoming)
2721 public function add_sidecalendar_blocks(core_calendar_renderer
$renderer, $showfilters=false, $view=null) {
2723 $filters = new block_contents();
2724 $filters->content
= $renderer->fake_block_filters($this->courseid
, $this->day
, $this->month
, $this->year
, $view, $this->courses
);
2725 $filters->footer
= '';
2726 $filters->title
= get_string('eventskey', 'calendar');
2727 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT
);
2729 $block = new block_contents
;
2730 $block->content
= $renderer->fake_block_threemonths($this);
2731 $block->footer
= '';
2732 $block->title
= get_string('monthlyview', 'calendar');
2733 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT
);
2738 * Returns option list for the poll interval setting.
2740 * @return array An array of poll interval options. Interval => description.
2742 function calendar_get_pollinterval_choices() {
2744 '0' => new lang_string('never', 'calendar'),
2745 '3600' => new lang_string('hourly', 'calendar'),
2746 '86400' => new lang_string('daily', 'calendar'),
2747 '604800' => new lang_string('weekly', 'calendar'),
2748 '2628000' => new lang_string('monthly', 'calendar'),
2749 '31536000' => new lang_string('annually', 'calendar')
2754 * Returns option list of available options for the calendar event type, given the current user and course.
2756 * @param int $courseid The id of the course
2757 * @return array An array containing the event types the user can create.
2759 function calendar_get_eventtype_choices($courseid) {
2761 $allowed = new stdClass
;
2762 calendar_get_allowed_types($allowed, $courseid);
2764 if ($allowed->user
) {
2765 $choices['user'] = get_string('userevents', 'calendar');
2767 if ($allowed->site
) {
2768 $choices['site'] = get_string('siteevents', 'calendar');
2770 if (!empty($allowed->courses
)) {
2771 $choices['course'] = get_string('courseevents', 'calendar');
2773 if (!empty($allowed->groups
) and is_array($allowed->groups
)) {
2774 $choices['group'] = get_string('group');
2777 return array($choices, $allowed->groups
);
2781 * Add an iCalendar subscription to the database.
2783 * @param stdClass $sub The subscription object (e.g. from the form)
2784 * @return int The insert ID, if any.
2786 function calendar_add_subscription($sub) {
2787 global $DB, $USER, $SITE;
2789 if ($sub->eventtype
=== 'site') {
2790 $sub->courseid
= $SITE->id
;
2791 } else if ($sub->eventtype
=== 'group' ||
$sub->eventtype
=== 'course') {
2792 $sub->courseid
= $sub->course
;
2797 $sub->userid
= $USER->id
;
2799 // File subscriptions never update.
2800 if (empty($sub->url
)) {
2801 $sub->pollinterval
= 0;
2804 if (!empty($sub->name
)) {
2805 if (empty($sub->id
)) {
2806 $id = $DB->insert_record('event_subscriptions', $sub);
2807 // we cannot cache the data here because $sub is not complete.
2810 // Why are we doing an update here?
2811 calendar_update_subscription($sub);
2815 print_error('errorbadsubscription', 'importcalendar');
2820 * Add an iCalendar event to the Moodle calendar.
2822 * @param object $event The RFC-2445 iCalendar event
2823 * @param int $courseid The course ID
2824 * @param int $subscriptionid The iCalendar subscription ID
2825 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2826 * @return int Code: 1=updated, 2=inserted, 0=error
2828 function calendar_add_icalendar_event($event, $courseid, $subscriptionid) {
2831 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2832 if (empty($event->properties
['SUMMARY'])) {
2836 $name = $event->properties
['SUMMARY'][0]->value
;
2837 $name = str_replace('\n', '<br />', $name);
2838 $name = str_replace('\\', '', $name);
2839 $name = preg_replace('/\s+/', ' ', $name);
2841 $eventrecord = new stdClass
;
2842 $eventrecord->name
= clean_param($name, PARAM_NOTAGS
);
2844 if (empty($event->properties
['DESCRIPTION'][0]->value
)) {
2847 $description = $event->properties
['DESCRIPTION'][0]->value
;
2848 $description = str_replace('\n', '<br />', $description);
2849 $description = str_replace('\\', '', $description);
2850 $description = preg_replace('/\s+/', ' ', $description);
2852 $eventrecord->description
= clean_param($description, PARAM_NOTAGS
);
2854 // Probably a repeating event with RRULE etc. TODO: skip for now.
2855 if (empty($event->properties
['DTSTART'][0]->value
)) {
2859 $eventrecord->timestart
= strtotime($event->properties
['DTSTART'][0]->value
);
2860 if (empty($event->properties
['DTEND'])) {
2861 $eventrecord->timeduration
= 3600; // one hour if no end time specified
2863 $eventrecord->timeduration
= strtotime($event->properties
['DTEND'][0]->value
) - $eventrecord->timestart
;
2865 $eventrecord->uuid
= $event->properties
['UID'][0]->value
;
2866 $eventrecord->timemodified
= time();
2868 // Add the iCal subscription details if required.
2869 // We should never do anything with an event without a subscription reference.
2870 $sub = calendar_get_subscription($subscriptionid);
2871 $eventrecord->subscriptionid
= $subscriptionid;
2872 $eventrecord->userid
= $sub->userid
;
2873 $eventrecord->groupid
= $sub->groupid
;
2874 $eventrecord->courseid
= $sub->courseid
;
2875 $eventrecord->eventtype
= $sub->eventtype
;
2877 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid
))) {
2878 $eventrecord->id
= $updaterecord->id
;
2879 if ($DB->update_record('event', $eventrecord)) {
2880 return CALENDAR_IMPORT_EVENT_UPDATED
;
2885 if ($DB->insert_record('event', $eventrecord)) {
2886 return CALENDAR_IMPORT_EVENT_INSERTED
;
2894 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2896 * @param int $subscriptionid The ID of the subscription we are acting upon.
2897 * @param int $pollinterval The poll interval to use.
2898 * @param int $action The action to be performed. One of update or remove.
2899 * @throws dml_exception if invalid subscriptionid is provided
2900 * @return string A log of the import progress, including errors
2902 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2905 // Fetch the subscription from the database making sure it exists.
2906 $sub = calendar_get_subscription($subscriptionid);
2908 $strupdate = get_string('update');
2909 $strremove = get_string('remove');
2911 // Update or remove the subscription, based on action.
2914 // Skip updating file subscriptions.
2915 if (empty($sub->url
)) {
2918 $sub->pollinterval
= $pollinterval;
2919 calendar_update_subscription($sub);
2921 // Update the events.
2922 return "<p>".get_string('subscriptionupdated', 'calendar', $sub->name
)."</p>" . calendar_update_subscription_events($subscriptionid);
2925 calendar_delete_subscription($subscriptionid);
2926 return get_string('subscriptionremoved', 'calendar', $sub->name
);
2936 * Delete subscription and all related events.
2938 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
2940 function calendar_delete_subscription($subscription) {
2943 if (is_object($subscription)) {
2944 $subscription = $subscription->id
;
2946 // Delete subscription and related events.
2947 $DB->delete_records('event', array('subscriptionid' => $subscription));
2948 $DB->delete_records('event_subscriptions', array('id' => $subscription));
2949 cache_helper
::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription));
2952 * From a URL, fetch the calendar and return an iCalendar object.
2954 * @param string $url The iCalendar URL
2955 * @return stdClass The iCalendar object
2957 function calendar_get_icalendar($url) {
2960 require_once($CFG->libdir
.'/filelib.php');
2963 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
2964 $calendar = $curl->get($url);
2965 // Http code validation should actually be the job of curl class.
2966 if (!$calendar ||
$curl->info
['http_code'] != 200 ||
!empty($curl->errorno
)) {
2967 throw new moodle_exception('errorinvalidicalurl', 'calendar');
2970 $ical = new iCalendar();
2971 $ical->unserialize($calendar);
2976 * Import events from an iCalendar object into a course calendar.
2978 * @param stdClass $ical The iCalendar object.
2979 * @param int $courseid The course ID for the calendar.
2980 * @param int $subscriptionid The subscription ID.
2981 * @return string A log of the import progress, including errors.
2983 function calendar_import_icalendar_events($ical, $courseid, $subscriptionid = null) {
2989 // Large calendars take a while...
2990 set_time_limit(300);
2992 // Mark all events in a subscription with a zero timestamp.
2993 if (!empty($subscriptionid)) {
2994 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
2995 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
2997 foreach ($ical->components
['VEVENT'] as $event) {
2998 $res = calendar_add_icalendar_event($event, $courseid, $subscriptionid);
3000 case CALENDAR_IMPORT_EVENT_UPDATED
:
3003 case CALENDAR_IMPORT_EVENT_INSERTED
:
3007 $return .= '<p>'.get_string('erroraddingevent', 'calendar').': '.(empty($event->properties
['SUMMARY'])?
'('.get_string('notitle', 'calendar').')':$event->properties
['SUMMARY'][0]->value
)." </p>\n";
3011 $return .= "<p> ".get_string('eventsimported', 'calendar', $eventcount)."</p>";
3012 $return .= "<p> ".get_string('eventsupdated', 'calendar', $updatecount)."</p>";
3014 // Delete remaining zero-marked events since they're not in remote calendar.
3015 if (!empty($subscriptionid)) {
3016 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3017 if (!empty($deletecount)) {
3018 $sql = "DELETE FROM {event} WHERE timemodified = :time AND subscriptionid = :id";
3019 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3020 $return .= "<p> ".get_string('eventsdeleted', 'calendar').": {$deletecount} </p>\n";
3028 * Fetch a calendar subscription and update the events in the calendar.
3030 * @param int $subscriptionid The course ID for the calendar.
3031 * @return string A log of the import progress, including errors.
3033 function calendar_update_subscription_events($subscriptionid) {
3036 $sub = calendar_get_subscription($subscriptionid);
3037 // Don't update a file subscription. TODO: Update from a new uploaded file.
3038 if (empty($sub->url
)) {
3039 return 'File subscription not updated.';
3041 $ical = calendar_get_icalendar($sub->url
);
3042 $return = calendar_import_icalendar_events($ical, $sub->courseid
, $subscriptionid);
3043 $sub->lastupdated
= time();
3044 calendar_update_subscription($sub);
3049 * Update a calendar subscription. Also updates the associated cache.
3051 * @param stdClass|array $subscription Subscription record.
3052 * @throws coding_exception If something goes wrong
3055 function calendar_update_subscription($subscription) {
3058 if (is_array($subscription)) {
3059 $subscription = (object)$subscription;
3061 if (empty($subscription->id
) ||
!$DB->record_exists('event_subscriptions', array('id' => $subscription->id
))) {
3062 throw new coding_exception('Cannot update a subscription without a valid id');
3065 $DB->update_record('event_subscriptions', $subscription);
3067 $cache = cache
::make('core', 'calendar_subscriptions');
3068 $cache->set($subscription->id
, $subscription);
3072 * Checks to see if the user can edit a given subscription feed.
3074 * @param mixed $subscriptionorid Subscription object or id
3075 * @return bool true if current user can edit the subscription else false
3077 function calendar_can_edit_subscription($subscriptionorid) {
3080 if (is_array($subscriptionorid)) {
3081 $subscription = (object)$subscriptionorid;
3082 } else if (is_object($subscriptionorid)) {
3083 $subscription = $subscriptionorid;
3085 $subscription = calendar_get_subscription($subscriptionorid);
3087 $allowed = new stdClass
;
3088 $courseid = $subscription->courseid
;
3089 $groupid = $subscription->groupid
;
3090 calendar_get_allowed_types($allowed, $courseid);
3091 switch ($subscription->eventtype
) {
3093 return $allowed->user
;
3095 if (isset($allowed->courses
[$courseid])) {
3096 return $allowed->courses
[$courseid];
3101 return $allowed->site
;
3103 if (isset($allowed->groups
[$groupid])) {
3104 return $allowed->groups
[$groupid];
3114 * Update calendar subscriptions.
3118 function calendar_cron() {
3121 // In order to execute this we need bennu.
3122 require_once($CFG->libdir
.'/bennu/bennu.inc.php');
3124 mtrace('Updating calendar subscriptions:');
3125 cron_trace_time_and_memory();
3128 $subscriptions = $DB->get_records_sql('SELECT * FROM {event_subscriptions} WHERE pollinterval > 0 AND lastupdated + pollinterval < ?', array($time));
3129 foreach ($subscriptions as $sub) {
3130 mtrace("Updating calendar subscription {$sub->name} in course {$sub->courseid}");
3132 $log = calendar_update_subscription_events($sub->id
);
3133 } catch (moodle_exception
$ex) {
3136 mtrace(trim(strip_tags($log)));
3139 mtrace('Finished updating calendar subscriptions.');