2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * @package core_calendar
21 * @copyright 2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 if (!defined('MOODLE_INTERNAL')) {
27 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
31 * These are read by the administration component to provide default values
35 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
37 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
40 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
42 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
45 * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
47 define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
49 // This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
50 // Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
53 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
55 define('CALENDAR_DEFAULT_WEEKEND', 65);
58 * CALENDAR_URL - path to calendar's folder
60 define('CALENDAR_URL', $CFG->wwwroot
.'/calendar/');
63 * CALENDAR_TF_24 - Calendar time in 24 hours format
65 define('CALENDAR_TF_24', '%H:%M');
68 * CALENDAR_TF_12 - Calendar time in 12 hours format
70 define('CALENDAR_TF_12', '%I:%M %p');
73 * CALENDAR_EVENT_GLOBAL - Global calendar event types
75 define('CALENDAR_EVENT_GLOBAL', 1);
78 * CALENDAR_EVENT_COURSE - Course calendar event types
80 define('CALENDAR_EVENT_COURSE', 2);
83 * CALENDAR_EVENT_GROUP - group calendar event types
85 define('CALENDAR_EVENT_GROUP', 4);
88 * CALENDAR_EVENT_USER - user calendar event types
90 define('CALENDAR_EVENT_USER', 8);
94 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
96 define('CALENDAR_IMPORT_FROM_FILE', 0);
99 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
101 define('CALENDAR_IMPORT_FROM_URL', 1);
104 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
106 define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
109 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
111 define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
114 * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
116 define('CALENDAR_SUBSCRIPTION_UPDATE', 1);
119 * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
121 define('CALENDAR_SUBSCRIPTION_REMOVE', 2);
124 * Return the days of the week
126 * @return array array of days
128 function calendar_get_days() {
129 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
130 return $calendartype->get_weekdays();
134 * Get the subscription from a given id
137 * @param int $id id of the subscription
138 * @return stdClass Subscription record from DB
139 * @throws moodle_exception for an invalid id
141 function calendar_get_subscription($id) {
144 $cache = cache
::make('core', 'calendar_subscriptions');
145 $subscription = $cache->get($id);
146 if (empty($subscription)) {
147 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST
);
149 $cache->set($id, $subscription);
151 return $subscription;
155 * Gets the first day of the week
157 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
161 function calendar_get_starting_weekday() {
162 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
163 return $calendartype->get_starting_weekday();
167 * Generates the HTML for a miniature calendar
169 * @param array $courses list of course to list events from
170 * @param array $groups list of group
171 * @param array $users user's info
172 * @param int|bool $calmonth calendar month in numeric, default is set to false
173 * @param int|bool $calyear calendar month in numeric, default is set to false
174 * @param string|bool $placement the place/page the calendar is set to appear - passed on the the controls function
175 * @param int|bool $courseid id of the course the calendar is displayed on - passed on the the controls function
176 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
177 * and $calyear to support multiple calendars
178 * @return string $content return html table for mini calendar
180 function calendar_get_mini($courses, $groups, $users, $calmonth = false, $calyear = false, $placement = false,
181 $courseid = false, $time = 0) {
182 global $CFG, $OUTPUT, $PAGE;
184 // Get the calendar type we are using.
185 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
187 $display = new stdClass
;
189 // Assume we are not displaying this month for now.
190 $display->thismonth
= false;
194 // Do this check for backwards compatibility. The core should be passing a timestamp rather than month and year.
195 // If a month and year are passed they will be in Gregorian.
196 if (!empty($calmonth) && !empty($calyear)) {
197 // Ensure it is a valid date, else we will just set it to the current timestamp.
198 if (checkdate($calmonth, 1, $calyear)) {
199 $time = make_timestamp($calyear, $calmonth, 1);
203 $date = usergetdate($time);
204 if ($calmonth == $date['mon'] && $calyear == $date['year']) {
205 $display->thismonth
= true;
207 // We can overwrite date now with the date used by the calendar type, if it is not Gregorian, otherwise
208 // there is no need as it is already in Gregorian.
209 if ($calendartype->get_name() != 'gregorian') {
210 $date = $calendartype->timestamp_to_date_array($time);
212 } else if (!empty($time)) {
213 // Get the specified date in the calendar type being used.
214 $date = $calendartype->timestamp_to_date_array($time);
215 $thisdate = $calendartype->timestamp_to_date_array(time());
216 if ($date['month'] == $thisdate['month'] && $date['year'] == $thisdate['year']) {
217 $display->thismonth
= true;
218 // If we are the current month we want to set the date to the current date, not the start of the month.
222 // Get the current date in the calendar type being used.
224 $date = $calendartype->timestamp_to_date_array($time);
225 $display->thismonth
= true;
228 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display.
230 // Get Gregorian date for the start of the month.
231 $gregoriandate = $calendartype->convert_to_gregorian($date['year'], $date['mon'], 1);
233 // Store the gregorian date values to be used later.
234 list($gy, $gm, $gd, $gh, $gmin) = array($gregoriandate['year'], $gregoriandate['month'], $gregoriandate['day'],
235 $gregoriandate['hour'], $gregoriandate['minute']);
237 // Get the max number of days in this month for this calendar type.
238 $display->maxdays
= calendar_days_in_month($m, $y);
239 // Get the starting week day for this month.
240 $startwday = dayofweek(1, $m, $y);
241 // Get the days in a week.
242 $daynames = calendar_get_days();
243 // Store the number of days in a week.
244 $numberofdaysinweek = $calendartype->get_num_weekdays();
246 // Set the min and max weekday.
247 $display->minwday
= calendar_get_starting_weekday();
248 $display->maxwday
= $display->minwday +
($numberofdaysinweek - 1);
250 // These are used for DB queries, so we want unixtime, so we need to use Gregorian dates.
251 $display->tstart
= make_timestamp($gy, $gm, $gd, $gh, $gmin, 0);
252 $display->tend
= $display->tstart +
($display->maxdays
* DAYSECS
) - 1;
254 // Align the starting weekday to fall in our display range
255 // This is simple, not foolproof.
256 if ($startwday < $display->minwday
) {
257 $startwday +
= $numberofdaysinweek;
260 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
261 $events = calendar_get_events($display->tstart
, $display->tend
, $users, $groups, $courses);
263 // Set event course class for course events
264 if (!empty($events)) {
265 foreach ($events as $eventid => $event) {
266 if (!empty($event->modulename
)) {
267 $cm = get_coursemodule_from_instance($event->modulename
, $event->instance
);
268 if (!\core_availability\info_module
::is_user_visible($cm, 0, false)) {
269 unset($events[$eventid]);
275 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
276 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
277 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
278 // arguments to this function.
279 $hrefparams = array();
280 if(!empty($courses)) {
281 $courses = array_diff($courses, array(SITEID
));
282 if(count($courses) == 1) {
283 $hrefparams['course'] = reset($courses);
287 // We want to have easy access by day, since the display is on a per-day basis.
288 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
290 // Accessibility: added summary and <abbr> elements.
291 $summary = get_string('calendarheading', 'calendar', userdate($display->tstart
, get_string('strftimemonthyear')));
293 $content .= '<table class="minicalendar calendartable" summary="' . $summary . '">';
294 if (($placement !== false) && ($courseid !== false)) {
295 $content .= '<caption>'. calendar_top_controls($placement, array('id' => $courseid, 'time' => $time)) .'</caption>';
297 $content .= '<tr class="weekdays">'; // Header row: day names
299 // Print out the names of the weekdays.
300 for ($i = $display->minwday
; $i <= $display->maxwday
; ++
$i) {
301 $pos = $i %
$numberofdaysinweek;
302 $content .= '<th scope="col"><abbr title="'. $daynames[$pos]['fullname'] .'">'.
303 $daynames[$pos]['shortname'] ."</abbr></th>\n";
306 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
308 // For the table display. $week is the row; $dayweek is the column.
309 $dayweek = $startwday;
311 // Paddding (the first week may have blank days in the beginning)
312 for($i = $display->minwday
; $i < $startwday; ++
$i) {
313 $content .= '<td class="dayblank"> </td>'."\n";
316 $weekend = CALENDAR_DEFAULT_WEEKEND
;
317 if (isset($CFG->calendar_weekend
)) {
318 $weekend = intval($CFG->calendar_weekend
);
321 // Now display all the calendar
322 $daytime = strtotime('-1 day', $display->tstart
);
323 for($day = 1; $day <= $display->maxdays
; ++
$day, ++
$dayweek) {
324 $cellattributes = array();
325 $daytime = strtotime('+1 day', $daytime);
326 if($dayweek > $display->maxwday
) {
327 // We need to change week (table row)
328 $content .= '</tr><tr>';
329 $dayweek = $display->minwday
;
333 if ($weekend & (1 << ($dayweek %
$numberofdaysinweek))) {
334 // Weekend. This is true no matter what the exact range is.
335 $class = 'weekend day';
337 // Normal working day.
341 if (isset($eventsbyday[$day])) {
342 // There is at least one event on this day.
344 $class .= ' hasevent';
345 $hrefparams['view'] = 'day';
346 $dayhref = calendar_get_link_href(new moodle_url(CALENDAR_URL
. 'view.php', $hrefparams), 0, 0, 0, $daytime);
349 foreach($eventsbyday[$day] as $eventid) {
350 if (!isset($events[$eventid])) {
353 $event = new calendar_event($events[$eventid]);
355 $component = 'moodle';
356 if (!empty($event->modulename
)) {
358 $popupalt = $event->modulename
;
359 $component = $event->modulename
;
360 } else if ($event->courseid
== SITEID
) { // Site event.
361 $popupicon = 'i/siteevent';
362 } else if ($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) { // Course event.
363 $popupicon = 'i/courseevent';
364 } else if ($event->groupid
) { // Group event.
365 $popupicon = 'i/groupevent';
366 } else { // Must be a user event.
367 $popupicon = 'i/userevent';
370 $dayhref->set_anchor('event_'.$event->id
);
372 $popupcontent .= html_writer
::start_tag('div');
373 $popupcontent .= $OUTPUT->pix_icon($popupicon, $popupalt, $component);
374 $name = format_string($event->name
, true);
375 // Show ical source if needed.
376 if (!empty($event->subscription
) && $CFG->calendar_showicalsource
) {
379 $a->source
= $event->subscription
->name
;
380 $name = get_string('namewithsource', 'calendar', $a);
382 $popupcontent .= html_writer
::link($dayhref, $name);
383 $popupcontent .= html_writer
::end_tag('div');
386 if ($display->thismonth
&& $day == $d) {
387 $popupdata = calendar_get_popup(true, $events[$eventid]->timestart
, $popupcontent);
389 $popupdata = calendar_get_popup(false, $events[$eventid]->timestart
, $popupcontent);
391 $cellattributes = array_merge($cellattributes, $popupdata);
393 // Class and cell content
394 if(isset($typesbyday[$day]['startglobal'])) {
395 $class .= ' calendar_event_global';
396 } else if(isset($typesbyday[$day]['startcourse'])) {
397 $class .= ' calendar_event_course';
398 } else if(isset($typesbyday[$day]['startgroup'])) {
399 $class .= ' calendar_event_group';
400 } else if(isset($typesbyday[$day]['startuser'])) {
401 $class .= ' calendar_event_user';
403 $cell = html_writer
::link($dayhref, $day);
408 $durationclass = false;
409 if (isset($typesbyday[$day]['durationglobal'])) {
410 $durationclass = ' duration_global';
411 } else if(isset($typesbyday[$day]['durationcourse'])) {
412 $durationclass = ' duration_course';
413 } else if(isset($typesbyday[$day]['durationgroup'])) {
414 $durationclass = ' duration_group';
415 } else if(isset($typesbyday[$day]['durationuser'])) {
416 $durationclass = ' duration_user';
418 if ($durationclass) {
419 $class .= ' duration '.$durationclass;
422 // If event has a class set then add it to the table day <td> tag
423 // Note: only one colour for minicalendar
424 if(isset($eventsbyday[$day])) {
425 foreach($eventsbyday[$day] as $eventid) {
426 if (!isset($events[$eventid])) {
429 $event = $events[$eventid];
430 if (!empty($event->class)) {
431 $class .= ' '.$event->class;
437 if ($display->thismonth
&& $day == $d) {
438 // The current cell is for today - add appropriate classes and additional information for styling.
440 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
442 if (!isset($eventsbyday[$day])) {
443 $class .= ' eventnone';
444 $popupdata = calendar_get_popup(true, false);
445 $cellattributes = array_merge($cellattributes, $popupdata);
446 $cell = html_writer
::link('#', $day);
448 $cell = get_accesshide($today . ' ') . $cell;
452 $cellattributes['class'] = $class;
453 $content .= html_writer
::tag('td', $cell, $cellattributes);
456 // Paddding (the last week may have blank days at the end)
457 for($i = $dayweek; $i <= $display->maxwday
; ++
$i) {
458 $content .= '<td class="dayblank"> </td>';
460 $content .= '</tr>'; // Last row ends
462 $content .= '</table>'; // Tabular display of days ends
464 static $jsincluded = false;
466 $PAGE->requires
->yui_module('moodle-calendar-info', 'Y.M.core_calendar.info.init');
473 * Gets the calendar popup
475 * It called at multiple points in from calendar_get_mini.
476 * Copied and modified from calendar_get_mini.
478 * @param bool $is_today false except when called on the current day.
479 * @param mixed $event_timestart $events[$eventid]->timestart, OR false if there are no events.
480 * @param string $popupcontent content for the popup window/layout.
481 * @return string eventid for the calendar_tooltip popup window/layout.
483 function calendar_get_popup($today = false, $timestart, $popupcontent = '') {
488 $popupcaption = get_string('today', 'calendar') . ' ';
491 if (false === $timestart) {
492 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
493 $popupcontent = get_string('eventnone', 'calendar');
496 $popupcaption .= get_string('eventsfor', 'calendar', userdate($timestart, get_string('strftimedayshort')));
500 'data-core_calendar-title' => $popupcaption,
501 'data-core_calendar-popupcontent' => $popupcontent,
506 * Gets the calendar upcoming event
508 * @param array $courses array of courses
509 * @param array|int|bool $groups array of groups, group id or boolean for all/no group events
510 * @param array|int|bool $users array of users, user id or boolean for all/no user events
511 * @param int $daysinfuture number of days in the future we 'll look
512 * @param int $maxevents maximum number of events
513 * @param int $fromtime start time
514 * @return array $output array of upcoming events
516 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
517 global $CFG, $COURSE, $DB;
519 $display = new stdClass
;
520 $display->range
= $daysinfuture; // How many days in the future we 'll look
521 $display->maxevents
= $maxevents;
525 // Prepare "course caching", since it may save us a lot of queries
526 $coursecache = array();
529 $now = time(); // We 'll need this later
530 $usermidnighttoday = usergetmidnight($now);
533 $display->tstart
= $fromtime;
535 $display->tstart
= $usermidnighttoday;
538 // This works correctly with respect to the user's DST, but it is accurate
539 // only because $fromtime is always the exact midnight of some day!
540 $display->tend
= usergetmidnight($display->tstart + DAYSECS
* $display->range +
3 * HOURSECS
) - 1;
542 // Get the events matching our criteria
543 $events = calendar_get_events($display->tstart
, $display->tend
, $users, $groups, $courses);
545 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
546 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
547 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
548 // arguments to this function.
550 $hrefparams = array();
551 if(!empty($courses)) {
552 $courses = array_diff($courses, array(SITEID
));
553 if(count($courses) == 1) {
554 $hrefparams['course'] = reset($courses);
558 if ($events !== false) {
560 $modinfo = get_fast_modinfo($COURSE);
562 foreach($events as $event) {
565 if (!empty($event->modulename
)) {
566 if ($event->courseid
== $COURSE->id
) {
567 if (isset($modinfo->instances
[$event->modulename
][$event->instance
])) {
568 $cm = $modinfo->instances
[$event->modulename
][$event->instance
];
569 if (!$cm->uservisible
) {
574 if (!$cm = get_coursemodule_from_instance($event->modulename
, $event->instance
)) {
577 if (!\core_availability\info_module
::is_user_visible($cm, 0, false)) {
583 if ($processed >= $display->maxevents
) {
587 $event->time
= calendar_format_event_time($event, $now, $hrefparams);
597 * Get a HTML link to a course.
599 * @param int $courseid the course id
600 * @return string a link to the course (as HTML); empty if the course id is invalid
602 function calendar_get_courselink($courseid) {
608 calendar_get_course_cached($coursecache, $courseid);
609 $context = context_course
::instance($courseid);
610 $fullname = format_string($coursecache[$courseid]->fullname
, true, array('context' => $context));
611 $url = new moodle_url('/course/view.php', array('id' => $courseid));
612 $link = html_writer
::link($url, $fullname);
619 * Add calendar event metadata
621 * @param stdClass $event event info
622 * @return stdClass $event metadata
624 function calendar_add_event_metadata($event) {
625 global $CFG, $OUTPUT;
627 //Support multilang in event->name
628 $event->name
= format_string($event->name
,true);
630 if(!empty($event->modulename
)) { // Activity event
631 // The module name is set. I will assume that it has to be displayed, and
632 // also that it is an automatically-generated event. And of course that the
633 // fields for get_coursemodule_from_instance are set correctly.
634 $module = calendar_get_module_cached($coursecache, $event->modulename
, $event->instance
);
636 if ($module === false) {
640 $modulename = get_string('modulename', $event->modulename
);
641 if (get_string_manager()->string_exists($event->eventtype
, $event->modulename
)) {
642 // will be used as alt text if the event icon
643 $eventtype = get_string($event->eventtype
, $event->modulename
);
647 $icon = $OUTPUT->pix_url('icon', $event->modulename
) . '';
649 $event->icon
= '<img src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" class="icon" />';
650 $event->referer
= '<a href="'.$CFG->wwwroot
.'/mod/'.$event->modulename
.'/view.php?id='.$module->id
.'">'.$event->name
.'</a>';
651 $event->courselink
= calendar_get_courselink($module->course
);
652 $event->cmid
= $module->id
;
654 } else if($event->courseid
== SITEID
) { // Site event
655 $event->icon
= '<img src="'.$OUTPUT->pix_url('i/siteevent') . '" alt="'.get_string('globalevent', 'calendar').'" class="icon" />';
656 $event->cssclass
= 'calendar_event_global';
657 } else if($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) { // Course event
658 $event->icon
= '<img src="'.$OUTPUT->pix_url('i/courseevent') . '" alt="'.get_string('courseevent', 'calendar').'" class="icon" />';
659 $event->courselink
= calendar_get_courselink($event->courseid
);
660 $event->cssclass
= 'calendar_event_course';
661 } else if ($event->groupid
) { // Group event
662 if ($group = calendar_get_group_cached($event->groupid
)) {
663 $groupname = format_string($group->name
, true, context_course
::instance($group->courseid
));
667 $event->icon
= html_writer
::empty_tag('image', array('src' => $OUTPUT->pix_url('i/groupevent'),
668 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
669 $event->courselink
= calendar_get_courselink($event->courseid
) . ', ' . $groupname;
670 $event->cssclass
= 'calendar_event_group';
671 } else if($event->userid
) { // User event
672 $event->icon
= '<img src="'.$OUTPUT->pix_url('i/userevent') . '" alt="'.get_string('userevent', 'calendar').'" class="icon" />';
673 $event->cssclass
= 'calendar_event_user';
679 * Get calendar events
681 * @param int $tstart Start time of time range for events
682 * @param int $tend End time of time range for events
683 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
684 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
685 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
686 * @param boolean $withduration whether only events starting within time range selected
687 * or events in progress/already started selected as well
688 * @param boolean $ignorehidden whether to select only visible events or all events
689 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
691 function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
697 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
701 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
702 // Events from a number of users
703 if(!empty($whereclause)) $whereclause .= ' OR';
704 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED
);
705 $whereclause .= " (userid $insqlusers AND courseid = 0 AND groupid = 0)";
706 $params = array_merge($params, $inparamsusers);
707 } else if($users === true) {
708 // Events from ALL users
709 if(!empty($whereclause)) $whereclause .= ' OR';
710 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
711 } else if($users === false) {
712 // No user at all, do nothing
715 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
716 // Events from a number of groups
717 if(!empty($whereclause)) $whereclause .= ' OR';
718 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED
);
719 $whereclause .= " groupid $insqlgroups ";
720 $params = array_merge($params, $inparamsgroups);
721 } else if($groups === true) {
722 // Events from ALL groups
723 if(!empty($whereclause)) $whereclause .= ' OR ';
724 $whereclause .= ' groupid != 0';
726 // boolean false (no groups at all): we don't need to do anything
728 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
729 if(!empty($whereclause)) $whereclause .= ' OR';
730 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED
);
731 $whereclause .= " (groupid = 0 AND courseid $insqlcourses)";
732 $params = array_merge($params, $inparamscourses);
733 } else if ($courses === true) {
734 // Events from ALL courses
735 if(!empty($whereclause)) $whereclause .= ' OR';
736 $whereclause .= ' (groupid = 0 AND courseid != 0)';
739 // Security check: if, by now, we have NOTHING in $whereclause, then it means
740 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
741 // events no matter what. Allowing the code to proceed might return a completely
742 // valid query with only time constraints, thus selecting ALL events in that time frame!
743 if(empty($whereclause)) {
748 $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
751 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
753 if(!empty($whereclause)) {
754 // We have additional constraints
755 $whereclause = $timeclause.' AND ('.$whereclause.')';
758 // Just basic time filtering
759 $whereclause = $timeclause;
763 $whereclause .= ' AND visible = 1';
766 $events = $DB->get_records_select('event', $whereclause, $params, 'timestart');
767 if ($events === false) {
773 /** Get calendar events by id
776 * @param array $eventids list of event ids
777 * @return array Array of event entries, empty array if nothing found
780 function calendar_get_events_by_id($eventids) {
783 if (!is_array($eventids) ||
empty($eventids)) {
786 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
787 $wheresql = "id $wheresql";
789 return $DB->get_records_select('event', $wheresql, $params);
793 * Get control options for Calendar
795 * @param string $type of calendar
796 * @param array $data calendar information
797 * @return string $content return available control for the calender in html
799 function calendar_top_controls($type, $data) {
800 global $PAGE, $OUTPUT;
802 // Get the calendar type we are using.
803 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
807 // Ensure course id passed if relevant.
809 if (!empty($data['id'])) {
810 $courseid = '&course='.$data['id'];
813 // If we are passing a month and year then we need to convert this to a timestamp to
814 // support multiple calendars. No where in core should these be passed, this logic
815 // here is for third party plugins that may use this function.
816 if (!empty($data['m']) && !empty($date['y'])) {
817 if (!isset($data['d'])) {
820 if (!checkdate($data['m'], $data['d'], $data['y'])) {
823 $time = make_timestamp($data['y'], $data['m'], $data['d']);
825 } else if (!empty($data['time'])) {
826 $time = $data['time'];
831 // Get the date for the calendar type.
832 $date = $calendartype->timestamp_to_date_array($time);
834 $urlbase = $PAGE->url
;
836 // We need to get the previous and next months in certain cases.
837 if ($type == 'frontpage' ||
$type == 'course' ||
$type == 'month') {
838 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
839 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
840 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
841 $prevmonthtime['hour'], $prevmonthtime['minute']);
843 $nextmonth = calendar_add_month($date['mon'], $date['year']);
844 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
845 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
846 $nextmonthtime['hour'], $nextmonthtime['minute']);
851 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false, true, $prevmonthtime);
852 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true, $nextmonthtime);
853 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', array('view' => 'month')), false, false, false, $time);
855 if (!empty($data['id'])) {
856 $calendarlink->param('course', $data['id']);
859 if (right_to_left()) {
867 $content .= html_writer
::start_tag('div', array('class'=>'calendar-controls'));
868 $content .= $left.'<span class="hide"> | </span>';
869 $content .= html_writer
::tag('span', html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
870 $content .= '<span class="hide"> | </span>'. $right;
871 $content .= "<span class=\"clearer\"><!-- --></span>\n";
872 $content .= html_writer
::end_tag('div');
876 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false, true, $prevmonthtime);
877 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true, $nextmonthtime);
878 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', array('view' => 'month')), false, false, false, $time);
880 if (!empty($data['id'])) {
881 $calendarlink->param('course', $data['id']);
884 if (right_to_left()) {
892 $content .= html_writer
::start_tag('div', array('class'=>'calendar-controls'));
893 $content .= $left.'<span class="hide"> | </span>';
894 $content .= html_writer
::tag('span', html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
895 $content .= '<span class="hide"> | </span>'. $right;
896 $content .= "<span class=\"clearer\"><!-- --></span>";
897 $content .= html_writer
::end_tag('div');
900 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', array('view' => 'upcoming')), false, false, false, $time);
901 if (!empty($data['id'])) {
902 $calendarlink->param('course', $data['id']);
904 $calendarlink = html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
905 $content .= html_writer
::tag('div', $calendarlink, array('class'=>'centered'));
908 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', array('view' => 'month')), false, false, false, $time);
909 if (!empty($data['id'])) {
910 $calendarlink->param('course', $data['id']);
912 $calendarlink = html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
913 $content .= html_writer
::tag('h3', $calendarlink);
916 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&', false, false, false, false, $prevmonthtime);
917 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&', false, false, false, false, $nextmonthtime);
919 if (right_to_left()) {
927 $content .= html_writer
::start_tag('div', array('class'=>'calendar-controls'));
928 $content .= $left . '<span class="hide"> | </span>';
929 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
930 $content .= '<span class="hide"> | </span>' . $right;
931 $content .= '<span class="clearer"><!-- --></span>';
932 $content .= html_writer
::end_tag('div')."\n";
935 $days = calendar_get_days();
937 $prevtimestamp = strtotime('-1 day', $time);
938 $nexttimestamp = strtotime('+1 day', $time);
940 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
941 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
943 $prevname = $days[$prevdate['wday']]['fullname'];
944 $nextname = $days[$nextdate['wday']]['fullname'];
945 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&', false, false, false, false, $prevtimestamp);
946 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&', false, false, false, false, $nexttimestamp);
948 if (right_to_left()) {
956 $content .= html_writer
::start_tag('div', array('class'=>'calendar-controls'));
958 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimedaydate')).'</span>';
959 $content .= '<span class="hide"> | </span>'. $right;
960 $content .= "<span class=\"clearer\"><!-- --></span>";
961 $content .= html_writer
::end_tag('div')."\n";
969 * Formats a filter control element.
971 * @param moodle_url $url of the filter
972 * @param int $type constant defining the type filter
973 * @return string html content of the element
975 function calendar_filter_controls_element(moodle_url
$url, $type) {
978 case CALENDAR_EVENT_GLOBAL
:
979 $typeforhumans = 'global';
980 $class = 'calendar_event_global';
982 case CALENDAR_EVENT_COURSE
:
983 $typeforhumans = 'course';
984 $class = 'calendar_event_course';
986 case CALENDAR_EVENT_GROUP
:
987 $typeforhumans = 'groups';
988 $class = 'calendar_event_group';
990 case CALENDAR_EVENT_USER
:
991 $typeforhumans = 'user';
992 $class = 'calendar_event_user';
995 if (calendar_show_event_type($type)) {
996 $icon = $OUTPUT->pix_icon('t/hide', get_string('hide'));
997 $str = get_string('hide'.$typeforhumans.'events', 'calendar');
999 $icon = $OUTPUT->pix_icon('t/show', get_string('show'));
1000 $str = get_string('show'.$typeforhumans.'events', 'calendar');
1002 $content = html_writer
::start_tag('li', array('class' => 'calendar_event'));
1003 $content .= html_writer
::start_tag('a', array('href' => $url, 'rel' => 'nofollow'));
1004 $content .= html_writer
::tag('span', $icon, array('class' => $class));
1005 $content .= html_writer
::tag('span', $str, array('class' => 'eventname'));
1006 $content .= html_writer
::end_tag('a');
1007 $content .= html_writer
::end_tag('li');
1012 * Get the controls filter for calendar.
1014 * Filter is used to hide calendar info from the display page
1016 * @param moodle_url $returnurl return-url for filter controls
1017 * @return string $content return filter controls in html
1019 function calendar_filter_controls(moodle_url
$returnurl) {
1020 global $CFG, $USER, $OUTPUT;
1022 $groupevents = true;
1023 $id = optional_param( 'id',0,PARAM_INT
);
1024 $seturl = new moodle_url('/calendar/set.php', array('return' => base64_encode($returnurl->out_as_local_url(false)), 'sesskey'=>sesskey()));
1025 $content = html_writer
::start_tag('ul');
1027 $seturl->param('var', 'showglobal');
1028 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GLOBAL
);
1030 $seturl->param('var', 'showcourses');
1031 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_COURSE
);
1033 if (isloggedin() && !isguestuser()) {
1035 // This course MIGHT have group events defined, so show the filter
1036 $seturl->param('var', 'showgroups');
1037 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GROUP
);
1039 // This course CANNOT have group events, so lose the filter
1041 $seturl->param('var', 'showuser');
1042 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_USER
);
1044 $content .= html_writer
::end_tag('ul');
1050 * Return the representation day
1052 * @param int $tstamp Timestamp in GMT
1053 * @param int $now current Unix timestamp
1054 * @param bool $usecommonwords
1055 * @return string the formatted date/time
1057 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1059 static $shortformat;
1060 if(empty($shortformat)) {
1061 $shortformat = get_string('strftimedayshort');
1064 if($now === false) {
1068 // To have it in one place, if a change is needed
1069 $formal = userdate($tstamp, $shortformat);
1071 $datestamp = usergetdate($tstamp);
1072 $datenow = usergetdate($now);
1074 if($usecommonwords == false) {
1075 // We don't want words, just a date
1078 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1080 return get_string('today', 'calendar');
1083 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1084 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
1087 return get_string('yesterday', 'calendar');
1090 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] +
1 ) ||
1091 ($datestamp['year'] == $datenow['year'] +
1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
1094 return get_string('tomorrow', 'calendar');
1102 * return the formatted representation time
1104 * @param int $time the timestamp in UTC, as obtained from the database
1105 * @return string the formatted date/time
1107 function calendar_time_representation($time) {
1108 static $langtimeformat = NULL;
1109 if($langtimeformat === NULL) {
1110 $langtimeformat = get_string('strftimetime');
1112 $timeformat = get_user_preferences('calendar_timeformat');
1113 if(empty($timeformat)){
1114 $timeformat = get_config(NULL,'calendar_site_timeformat');
1116 // The ? is needed because the preference might be present, but empty
1117 return userdate($time, empty($timeformat) ?
$langtimeformat : $timeformat);
1121 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1123 * @param string|moodle_url $linkbase
1124 * @param int $d The number of the day.
1125 * @param int $m The number of the month.
1126 * @param int $y The number of the year.
1127 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1128 * $m and $y are kept for backwards compatibility.
1129 * @return moodle_url|null $linkbase
1131 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1132 if (empty($linkbase)) {
1135 if (!($linkbase instanceof moodle_url
)) {
1136 $linkbase = new moodle_url($linkbase);
1139 // If a day, month and year were passed then convert it to a timestamp. If these were passed
1140 // then we can assume the day, month and year are passed as Gregorian, as no where in core
1141 // should we be passing these values rather than the time.
1142 if (!empty($d) && !empty($m) && !empty($y)) {
1143 if (checkdate($m, $d, $y)) {
1144 $time = make_timestamp($y, $m, $d);
1148 } else if (empty($time)) {
1152 $linkbase->param('time', $time);
1158 * Build and return a previous month HTML link, with an arrow.
1160 * @param string $text The text label.
1161 * @param string|moodle_url $linkbase The URL stub.
1162 * @param int $d The number of the date.
1163 * @param int $m The number of the month.
1164 * @param int $y year The number of the year.
1165 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1166 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1167 * $m and $y are kept for backwards compatibility.
1168 * @return string HTML string.
1170 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1171 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y, $time);
1175 return link_arrow_left($text, (string)$href, $accesshide, 'previous');
1179 * Build and return a next month HTML link, with an arrow.
1181 * @param string $text The text label.
1182 * @param string|moodle_url $linkbase The URL stub.
1183 * @param int $d the number of the Day
1184 * @param int $m The number of the month.
1185 * @param int $y The number of the year.
1186 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1187 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1188 * $m and $y are kept for backwards compatibility.
1189 * @return string HTML string.
1191 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1192 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y, $time);
1196 return link_arrow_right($text, (string)$href, $accesshide, 'next');
1200 * Return the name of the weekday
1202 * @param string $englishname
1203 * @return string of the weekeday
1205 function calendar_wday_name($englishname) {
1206 return get_string(strtolower($englishname), 'calendar');
1210 * Return the number of days in month
1212 * @param int $month the number of the month.
1213 * @param int $year the number of the year
1216 function calendar_days_in_month($month, $year) {
1217 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1218 return $calendartype->get_num_days_in_month($year, $month);
1222 * Get the upcoming event block
1224 * @param array $events list of events
1225 * @param moodle_url|string $linkhref link to event referer
1226 * @param boolean $showcourselink whether links to courses should be shown
1227 * @return string|null $content html block content
1229 function calendar_get_block_upcoming($events, $linkhref = NULL, $showcourselink = false) {
1231 $lines = count($events);
1236 for ($i = 0; $i < $lines; ++
$i) {
1237 if (!isset($events[$i]->time
)) { // Just for robustness
1240 $events[$i] = calendar_add_event_metadata($events[$i]);
1241 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon
.'</span>';
1242 if (!empty($events[$i]->referer
)) {
1243 // That's an activity event, so let's provide the hyperlink
1244 $content .= $events[$i]->referer
;
1246 if(!empty($linkhref)) {
1247 $href = calendar_get_link_href(new moodle_url(CALENDAR_URL
. $linkhref), 0, 0, 0, $events[$i]->timestart
);
1248 $href->set_anchor('event_'.$events[$i]->id
);
1249 $content .= html_writer
::link($href, $events[$i]->name
);
1252 $content .= $events[$i]->name
;
1255 $events[$i]->time
= str_replace('»', '<br />»', $events[$i]->time
);
1256 if ($showcourselink && !empty($events[$i]->courselink
)) {
1257 $content .= html_writer
::div($events[$i]->courselink
, 'course');
1259 $content .= '<div class="date">'.$events[$i]->time
.'</div></div>';
1260 if ($i < $lines - 1) $content .= '<hr />';
1267 * Get the next following month
1269 * @param int $month the number of the month.
1270 * @param int $year the number of the year.
1271 * @return array the following month
1273 function calendar_add_month($month, $year) {
1274 // Get the calendar type we are using.
1275 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1276 return $calendartype->get_next_month($year, $month);
1280 * Get the previous month.
1282 * @param int $month the number of the month.
1283 * @param int $year the number of the year.
1284 * @return array previous month
1286 function calendar_sub_month($month, $year) {
1287 // Get the calendar type we are using.
1288 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1289 return $calendartype->get_prev_month($year, $month);
1293 * Get per-day basis events
1295 * @param array $events list of events
1296 * @param int $month the number of the month
1297 * @param int $year the number of the year
1298 * @param array $eventsbyday event on specific day
1299 * @param array $durationbyday duration of the event in days
1300 * @param array $typesbyday event type (eg: global, course, user, or group)
1301 * @param array $courses list of courses
1304 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1305 // Get the calendar type we are using.
1306 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1308 $eventsbyday = array();
1309 $typesbyday = array();
1310 $durationbyday = array();
1312 if($events === false) {
1316 foreach ($events as $event) {
1317 $startdate = $calendartype->timestamp_to_date_array($event->timestart
);
1318 // Set end date = start date if no duration
1319 if ($event->timeduration
) {
1320 $enddate = $calendartype->timestamp_to_date_array($event->timestart +
$event->timeduration
- 1);
1322 $enddate = $startdate;
1325 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
1326 if(!($startdate['year'] * 13 +
$startdate['mon'] <= $year * 13 +
$month) && ($enddate['year'] * 13 +
$enddate['mon'] >= $year * 13 +
$month)) {
1331 $eventdaystart = intval($startdate['mday']);
1333 if($startdate['mon'] == $month && $startdate['year'] == $year) {
1334 // Give the event to its day
1335 $eventsbyday[$eventdaystart][] = $event->id
;
1337 // Mark the day as having such an event
1338 if($event->courseid
== SITEID
&& $event->groupid
== 0) {
1339 $typesbyday[$eventdaystart]['startglobal'] = true;
1340 // Set event class for global event
1341 $events[$event->id
]->class = 'calendar_event_global';
1343 else if($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) {
1344 $typesbyday[$eventdaystart]['startcourse'] = true;
1345 // Set event class for course event
1346 $events[$event->id
]->class = 'calendar_event_course';
1348 else if($event->groupid
) {
1349 $typesbyday[$eventdaystart]['startgroup'] = true;
1350 // Set event class for group event
1351 $events[$event->id
]->class = 'calendar_event_group';
1353 else if($event->userid
) {
1354 $typesbyday[$eventdaystart]['startuser'] = true;
1355 // Set event class for user event
1356 $events[$event->id
]->class = 'calendar_event_user';
1360 if($event->timeduration
== 0) {
1361 // Proceed with the next
1365 // The event starts on $month $year or before. So...
1366 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ?
intval($startdate['mday']) : 0;
1368 // Also, it ends on $month $year or later...
1369 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ?
intval($enddate['mday']) : calendar_days_in_month($month, $year);
1371 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1372 for($i = $lowerbound +
1; $i <= $upperbound; ++
$i) {
1373 $durationbyday[$i][] = $event->id
;
1374 if($event->courseid
== SITEID
&& $event->groupid
== 0) {
1375 $typesbyday[$i]['durationglobal'] = true;
1377 else if($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) {
1378 $typesbyday[$i]['durationcourse'] = true;
1380 else if($event->groupid
) {
1381 $typesbyday[$i]['durationgroup'] = true;
1383 else if($event->userid
) {
1384 $typesbyday[$i]['durationuser'] = true;
1393 * Get current module cache
1395 * @param array $coursecache list of course cache
1396 * @param string $modulename name of the module
1397 * @param int $instance module instance number
1398 * @return stdClass|bool $module information
1400 function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1401 $module = get_coursemodule_from_instance($modulename, $instance);
1403 if($module === false) return false;
1404 if(!calendar_get_course_cached($coursecache, $module->course
)) {
1411 * Get current course cache
1413 * @param array $coursecache list of course cache
1414 * @param int $courseid id of the course
1415 * @return stdClass $coursecache[$courseid] return the specific course cache
1417 function calendar_get_course_cached(&$coursecache, $courseid) {
1418 if (!isset($coursecache[$courseid])) {
1419 $coursecache[$courseid] = get_course($courseid);
1421 return $coursecache[$courseid];
1425 * Get group from groupid for calendar display
1427 * @param int $groupid
1428 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1430 function calendar_get_group_cached($groupid) {
1431 static $groupscache = array();
1432 if (!isset($groupscache[$groupid])) {
1433 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1435 return $groupscache[$groupid];
1439 * Returns the courses to load events for, the
1441 * @param array $courseeventsfrom An array of courses to load calendar events for
1442 * @param bool $ignorefilters specify the use of filters, false is set as default
1443 * @return array An array of courses, groups, and user to load calendar events for based upon filters
1445 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
1446 global $USER, $CFG, $DB;
1448 // For backwards compatability we have to check whether the courses array contains
1449 // just id's in which case we need to load course objects.
1450 $coursestoload = array();
1451 foreach ($courseeventsfrom as $id => $something) {
1452 if (!is_object($something)) {
1453 $coursestoload[] = $id;
1454 unset($courseeventsfrom[$id]);
1457 if (!empty($coursestoload)) {
1458 // TODO remove this in 2.2
1459 debugging('calendar_set_filters now preferes an array of course objects with preloaded contexts', DEBUG_DEVELOPER
);
1460 $courseeventsfrom = array_merge($courseeventsfrom, $DB->get_records_list('course', 'id', $coursestoload));
1467 // capabilities that allow seeing group events from all groups
1468 // TODO: rewrite so that moodle/calendar:manageentries is not necessary here
1469 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
1471 $isloggedin = isloggedin();
1473 if ($ignorefilters ||
calendar_show_event_type(CALENDAR_EVENT_COURSE
)) {
1474 $courses = array_keys($courseeventsfrom);
1476 if ($ignorefilters ||
calendar_show_event_type(CALENDAR_EVENT_GLOBAL
)) {
1477 $courses[] = SITEID
;
1479 $courses = array_unique($courses);
1482 if (!empty($courses) && in_array(SITEID
, $courses)) {
1483 // Sort courses for consistent colour highlighting
1484 // Effectively ignoring SITEID as setting as last course id
1485 $key = array_search(SITEID
, $courses);
1486 unset($courses[$key]);
1487 $courses[] = SITEID
;
1490 if ($ignorefilters ||
($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER
))) {
1494 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP
) ||
$ignorefilters)) {
1496 if (count($courseeventsfrom)==1) {
1497 $course = reset($courseeventsfrom);
1498 if (has_any_capability($allgroupscaps, context_course
::instance($course->id
))) {
1499 $coursegroups = groups_get_all_groups($course->id
, 0, 0, 'g.id');
1500 $group = array_keys($coursegroups);
1503 if ($group === false) {
1504 if (!empty($CFG->calendar_adminseesall
) && has_any_capability($allgroupscaps, context_system
::instance())) {
1506 } else if ($isloggedin) {
1507 $groupids = array();
1509 // We already have the courses to examine in $courses
1510 // For each course...
1511 foreach ($courseeventsfrom as $courseid => $course) {
1512 // If the user is an editing teacher in there,
1513 if (!empty($USER->groupmember
[$course->id
])) {
1514 // We've already cached the users groups for this course so we can just use that
1515 $groupids = array_merge($groupids, $USER->groupmember
[$course->id
]);
1516 } else if ($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
1517 // If this course has groups, show events from all of those related to the current user
1518 $coursegroups = groups_get_user_groups($course->id
, $USER->id
);
1519 $groupids = array_merge($groupids, $coursegroups['0']);
1522 if (!empty($groupids)) {
1528 if (empty($courses)) {
1532 return array($courses, $group, $user);
1536 * Return the capability for editing calendar event
1538 * @param calendar_event $event event object
1539 * @return bool capability to edit event
1541 function calendar_edit_event_allowed($event) {
1544 // Must be logged in
1545 if (!isloggedin()) {
1549 // can not be using guest account
1550 if (isguestuser()) {
1554 // You cannot edit calendar subscription events presently.
1555 if (!empty($event->subscriptionid
)) {
1559 $sitecontext = context_system
::instance();
1560 // if user has manageentries at site level, return true
1561 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1565 // if groupid is set, it's definitely a group event
1566 if (!empty($event->groupid
)) {
1567 // Allow users to add/edit group events if:
1568 // 1) They have manageentries (= entries for whole course)
1569 // 2) They have managegroupentries AND are in the group
1570 $group = $DB->get_record('groups', array('id'=>$event->groupid
));
1572 has_capability('moodle/calendar:manageentries', $event->context
) ||
1573 (has_capability('moodle/calendar:managegroupentries', $event->context
)
1574 && groups_is_member($event->groupid
)));
1575 } else if (!empty($event->courseid
)) {
1576 // if groupid is not set, but course is set,
1577 // it's definiely a course event
1578 return has_capability('moodle/calendar:manageentries', $event->context
);
1579 } else if (!empty($event->userid
) && $event->userid
== $USER->id
) {
1580 // if course is not set, but userid id set, it's a user event
1581 return (has_capability('moodle/calendar:manageownentries', $event->context
));
1582 } else if (!empty($event->userid
)) {
1583 return (has_capability('moodle/calendar:manageentries', $event->context
));
1589 * Returns the default courses to display on the calendar when there isn't a specific
1590 * course to display.
1592 * @return array $courses Array of courses to display
1594 function calendar_get_default_courses() {
1597 if (!isloggedin()) {
1602 if (!empty($CFG->calendar_adminseesall
) && has_capability('moodle/calendar:manageentries', context_system
::instance())) {
1603 $select = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
1604 $join = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1605 $sql = "SELECT c.* $select
1608 WHERE EXISTS (SELECT 1 FROM {event} e WHERE e.courseid = c.id)
1610 $courses = $DB->get_records_sql($sql, array('contextlevel' => CONTEXT_COURSE
), 0, 20);
1611 foreach ($courses as $course) {
1612 context_helper
::preload_from_record($course);
1617 $courses = enrol_get_my_courses();
1623 * Display calendar preference button
1625 * @param stdClass $course course object
1626 * @return string return preference button in html
1628 function calendar_preferences_button(stdClass
$course) {
1631 // Guests have no preferences
1632 if (!isloggedin() ||
isguestuser()) {
1636 return $OUTPUT->single_button(new moodle_url('/calendar/preferences.php', array('course' => $course->id
)), get_string("preferences", "calendar"));
1640 * Get event format time
1642 * @param calendar_event $event event object
1643 * @param int $now current time in gmt
1644 * @param array $linkparams list of params for event link
1645 * @param bool $usecommonwords the words as formatted date/time.
1646 * @param int $showtime determine the show time GMT timestamp
1647 * @return string $eventtime link/string for event time
1649 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
1650 $starttime = $event->timestart
;
1651 $endtime = $event->timestart +
$event->timeduration
;
1653 if (empty($linkparams) ||
!is_array($linkparams)) {
1654 $linkparams = array();
1657 $linkparams['view'] = 'day';
1659 // OK, now to get a meaningful display...
1660 // Check if there is a duration for this event.
1661 if ($event->timeduration
) {
1662 // Get the midnight of the day the event will start.
1663 $usermidnightstart = usergetmidnight($starttime);
1664 // Get the midnight of the day the event will end.
1665 $usermidnightend = usergetmidnight($endtime);
1666 // Check if we will still be on the same day.
1667 if ($usermidnightstart == $usermidnightend) {
1668 // Check if we are running all day.
1669 if ($event->timeduration
== DAYSECS
) {
1670 $time = get_string('allday', 'calendar');
1671 } else { // Specify the time we will be running this from.
1672 $datestart = calendar_time_representation($starttime);
1673 $dateend = calendar_time_representation($endtime);
1674 $time = $datestart . ' <strong>»</strong> ' . $dateend;
1677 // Set printable representation.
1679 $day = calendar_day_representation($event->timestart
, $now, $usecommonwords);
1680 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $endtime);
1681 $eventtime = html_writer
::link($url, $day) . ', ' . $time;
1685 } else { // It must spans two or more days.
1686 $daystart = calendar_day_representation($event->timestart
, $now, $usecommonwords) . ', ';
1687 if ($showtime == $usermidnightstart) {
1690 $timestart = calendar_time_representation($event->timestart
);
1691 $dayend = calendar_day_representation($event->timestart +
$event->timeduration
, $now, $usecommonwords) . ', ';
1692 if ($showtime == $usermidnightend) {
1695 $timeend = calendar_time_representation($event->timestart +
$event->timeduration
);
1697 // Set printable representation.
1698 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
1699 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $endtime);
1700 $eventtime = $timestart . ' <strong>»</strong> ' . html_writer
::link($url, $dayend) . $timeend;
1702 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $endtime);
1703 $eventtime = html_writer
::link($url, $daystart) . $timestart . ' <strong>»</strong> ';
1705 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $starttime);
1706 $eventtime .= html_writer
::link($url, $dayend) . $timeend;
1709 } else { // There is no time duration.
1710 $time = calendar_time_representation($event->timestart
);
1711 // Set printable representation.
1713 $day = calendar_day_representation($event->timestart
, $now, $usecommonwords);
1714 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $starttime);
1715 $eventtime = html_writer
::link($url, $day) . ', ' . trim($time);
1721 // Check if It has expired.
1722 if ($event->timestart +
$event->timeduration
< $now) {
1723 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
1730 * Display month selector options
1732 * @param string $name for the select element
1733 * @param string|array $selected options for select elements
1735 function calendar_print_month_selector($name, $selected) {
1737 for ($i=1; $i<=12; $i++
) {
1738 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
1740 echo html_writer
::label(get_string('months'), 'menu'. $name, false, array('class' => 'accesshide'));
1741 echo html_writer
::select($months, $name, $selected, false);
1745 * Checks to see if the requested type of event should be shown for the given user.
1747 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
1748 * The type to check the display for (default is to display all)
1749 * @param stdClass|int|null $user The user to check for - by default the current user
1750 * @return bool True if the tyep should be displayed false otherwise
1752 function calendar_show_event_type($type, $user = null) {
1753 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER
;
1754 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
1756 if (!isset($SESSION->calendarshoweventtype
)) {
1757 $SESSION->calendarshoweventtype
= $default;
1759 return $SESSION->calendarshoweventtype
& $type;
1761 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
1766 * Sets the display of the event type given $display.
1768 * If $display = true the event type will be shown.
1769 * If $display = false the event type will NOT be shown.
1770 * If $display = null the current value will be toggled and saved.
1772 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type object of CALENDAR_EVENT_XXX
1773 * @param bool $display option to display event type
1774 * @param stdClass|int $user moodle user object or id, null means current user
1776 function calendar_set_event_type_display($type, $display = null, $user = null) {
1777 $persist = get_user_preferences('calendar_persistflt', 0, $user);
1778 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER
;
1779 if ($persist === 0) {
1781 if (!isset($SESSION->calendarshoweventtype
)) {
1782 $SESSION->calendarshoweventtype
= $default;
1784 $preference = $SESSION->calendarshoweventtype
;
1786 $preference = get_user_preferences('calendar_savedflt', $default, $user);
1788 $current = $preference & $type;
1789 if ($display === null) {
1790 $display = !$current;
1792 if ($display && !$current) {
1793 $preference +
= $type;
1794 } else if (!$display && $current) {
1795 $preference -= $type;
1797 if ($persist === 0) {
1798 $SESSION->calendarshoweventtype
= $preference;
1800 if ($preference == $default) {
1801 unset_user_preference('calendar_savedflt', $user);
1803 set_user_preference('calendar_savedflt', $preference, $user);
1809 * Get calendar's allowed types
1811 * @param stdClass $allowed list of allowed edit for event type
1812 * @param stdClass|int $course object of a course or course id
1814 function calendar_get_allowed_types(&$allowed, $course = null) {
1815 global $USER, $CFG, $DB;
1816 $allowed = new stdClass();
1817 $allowed->user
= has_capability('moodle/calendar:manageownentries', context_system
::instance());
1818 $allowed->groups
= false; // This may change just below
1819 $allowed->courses
= false; // This may change just below
1820 $allowed->site
= has_capability('moodle/calendar:manageentries', context_course
::instance(SITEID
));
1822 if (!empty($course)) {
1823 if (!is_object($course)) {
1824 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST
);
1826 if ($course->id
!= SITEID
) {
1827 $coursecontext = context_course
::instance($course->id
);
1828 $allowed->user
= has_capability('moodle/calendar:manageownentries', $coursecontext);
1830 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
1831 $allowed->courses
= array($course->id
=> 1);
1833 if ($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
1834 if (has_capability('moodle/site:accessallgroups', $coursecontext)) {
1835 $allowed->groups
= groups_get_all_groups($course->id
);
1837 $allowed->groups
= groups_get_all_groups($course->id
, $USER->id
);
1840 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
1841 if($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
1842 if (has_capability('moodle/site:accessallgroups', $coursecontext)) {
1843 $allowed->groups
= groups_get_all_groups($course->id
);
1845 $allowed->groups
= groups_get_all_groups($course->id
, $USER->id
);
1854 * See if user can add calendar entries at all
1855 * used to print the "New Event" button
1857 * @param stdClass $course object of a course or course id
1858 * @return bool has the capability to add at least one event type
1860 function calendar_user_can_add_event($course) {
1861 if (!isloggedin() ||
isguestuser()) {
1864 calendar_get_allowed_types($allowed, $course);
1865 return (bool)($allowed->user ||
$allowed->groups ||
$allowed->courses ||
$allowed->site
);
1869 * Check wether the current user is permitted to add events
1871 * @param stdClass $event object of event
1872 * @return bool has the capability to add event
1874 function calendar_add_event_allowed($event) {
1877 // can not be using guest account
1878 if (!isloggedin() or isguestuser()) {
1882 $sitecontext = context_system
::instance();
1883 // if user has manageentries at site level, always return true
1884 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1888 switch ($event->eventtype
) {
1890 return has_capability('moodle/calendar:manageentries', $event->context
);
1893 // Allow users to add/edit group events if:
1894 // 1) They have manageentries (= entries for whole course)
1895 // 2) They have managegroupentries AND are in the group
1896 $group = $DB->get_record('groups', array('id'=>$event->groupid
));
1898 has_capability('moodle/calendar:manageentries', $event->context
) ||
1899 (has_capability('moodle/calendar:managegroupentries', $event->context
)
1900 && groups_is_member($event->groupid
)));
1903 if ($event->userid
== $USER->id
) {
1904 return (has_capability('moodle/calendar:manageownentries', $event->context
));
1906 //there is no 'break;' intentionally
1909 return has_capability('moodle/calendar:manageentries', $event->context
);
1912 return has_capability('moodle/calendar:manageentries', $event->context
);
1917 * Manage calendar events
1919 * This class provides the required functionality in order to manage calendar events.
1920 * It was introduced as part of Moodle 2.0 and was created in order to provide a
1921 * better framework for dealing with calendar events in particular regard to file
1922 * handling through the new file API
1924 * @package core_calendar
1925 * @category calendar
1926 * @copyright 2009 Sam Hemelryk
1927 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1929 * @property int $id The id within the event table
1930 * @property string $name The name of the event
1931 * @property string $description The description of the event
1932 * @property int $format The format of the description FORMAT_?
1933 * @property int $courseid The course the event is associated with (0 if none)
1934 * @property int $groupid The group the event is associated with (0 if none)
1935 * @property int $userid The user the event is associated with (0 if none)
1936 * @property int $repeatid If this is a repeated event this will be set to the
1937 * id of the original
1938 * @property string $modulename If added by a module this will be the module name
1939 * @property int $instance If added by a module this will be the module instance
1940 * @property string $eventtype The event type
1941 * @property int $timestart The start time as a timestamp
1942 * @property int $timeduration The duration of the event in seconds
1943 * @property int $visible 1 if the event is visible
1944 * @property int $uuid ?
1945 * @property int $sequence ?
1946 * @property int $timemodified The time last modified as a timestamp
1948 class calendar_event
{
1950 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
1951 protected $properties = null;
1954 * @var string The converted event discription with file paths resolved. This gets populated when someone requests description for the first time */
1955 protected $_description = null;
1957 /** @var array The options to use with this description editor */
1958 protected $editoroptions = array(
1960 'forcehttps'=>false,
1963 'trusttext'=>false);
1965 /** @var object The context to use with the description editor */
1966 protected $editorcontext = null;
1969 * Instantiates a new event and optionally populates its properties with the
1972 * @param stdClass $data Optional. An object containing the properties to for
1975 public function __construct($data=null) {
1978 // First convert to object if it is not already (should either be object or assoc array)
1979 if (!is_object($data)) {
1980 $data = (object)$data;
1983 $this->editoroptions
['maxbytes'] = $CFG->maxbytes
;
1985 $data->eventrepeats
= 0;
1987 if (empty($data->id
)) {
1991 if (!empty($data->subscriptionid
)) {
1992 $data->subscription
= calendar_get_subscription($data->subscriptionid
);
1995 // Default to a user event
1996 if (empty($data->eventtype
)) {
1997 $data->eventtype
= 'user';
2000 // Default to the current user
2001 if (empty($data->userid
)) {
2002 $data->userid
= $USER->id
;
2005 if (!empty($data->timeduration
) && is_array($data->timeduration
)) {
2006 $data->timeduration
= make_timestamp($data->timeduration
['year'], $data->timeduration
['month'], $data->timeduration
['day'], $data->timeduration
['hour'], $data->timeduration
['minute']) - $data->timestart
;
2008 if (!empty($data->description
) && is_array($data->description
)) {
2009 $data->format
= $data->description
['format'];
2010 $data->description
= $data->description
['text'];
2011 } else if (empty($data->description
)) {
2012 $data->description
= '';
2013 $data->format
= editors_get_preferred_format();
2015 // Ensure form is defaulted correctly
2016 if (empty($data->format
)) {
2017 $data->format
= editors_get_preferred_format();
2020 if (empty($data->context
)) {
2021 $data->context
= $this->calculate_context($data);
2023 $this->properties
= $data;
2027 * Magic property method
2029 * Attempts to call a set_$key method if one exists otherwise falls back
2030 * to simply set the property
2032 * @param string $key property name
2033 * @param mixed $value value of the property
2035 public function __set($key, $value) {
2036 if (method_exists($this, 'set_'.$key)) {
2037 $this->{'set_'.$key}($value);
2039 $this->properties
->{$key} = $value;
2045 * Attempts to call a get_$key method to return the property and ralls over
2046 * to return the raw property
2048 * @param string $key property name
2049 * @return mixed property value
2051 public function __get($key) {
2052 if (method_exists($this, 'get_'.$key)) {
2053 return $this->{'get_'.$key}();
2055 if (!isset($this->properties
->{$key})) {
2056 throw new coding_exception('Undefined property requested');
2058 return $this->properties
->{$key};
2062 * Stupid PHP needs an isset magic method if you use the get magic method and
2063 * still want empty calls to work.... blah ~!
2065 * @param string $key $key property name
2066 * @return bool|mixed property value, false if property is not exist
2068 public function __isset($key) {
2069 return !empty($this->properties
->{$key});
2073 * Calculate the context value needed for calendar_event.
2074 * Event's type can be determine by the available value store in $data
2075 * It is important to check for the existence of course/courseid to determine
2077 * Default value is set to CONTEXT_USER
2079 * @param stdClass $data information about event
2080 * @return stdClass The context object.
2082 protected function calculate_context(stdClass
$data) {
2086 if (isset($data->courseid
) && $data->courseid
> 0) {
2087 $context = context_course
::instance($data->courseid
);
2088 } else if (isset($data->course
) && $data->course
> 0) {
2089 $context = context_course
::instance($data->course
);
2090 } else if (isset($data->groupid
) && $data->groupid
> 0) {
2091 $group = $DB->get_record('groups', array('id'=>$data->groupid
));
2092 $context = context_course
::instance($group->courseid
);
2093 } else if (isset($data->userid
) && $data->userid
> 0 && $data->userid
== $USER->id
) {
2094 $context = context_user
::instance($data->userid
);
2095 } else if (isset($data->userid
) && $data->userid
> 0 && $data->userid
!= $USER->id
&&
2096 isset($data->instance
) && $data->instance
> 0) {
2097 $cm = get_coursemodule_from_instance($data->modulename
, $data->instance
, 0, false, MUST_EXIST
);
2098 $context = context_course
::instance($cm->course
);
2100 $context = context_user
::instance($data->userid
);
2107 * Returns an array of editoroptions for this event: Called by __get
2108 * Please use $blah = $event->editoroptions;
2110 * @return array event editor options
2112 protected function get_editoroptions() {
2113 return $this->editoroptions
;
2117 * Returns an event description: Called by __get
2118 * Please use $blah = $event->description;
2120 * @return string event description
2122 protected function get_description() {
2125 require_once($CFG->libdir
. '/filelib.php');
2127 if ($this->_description
=== null) {
2128 // Check if we have already resolved the context for this event
2129 if ($this->editorcontext
=== null) {
2130 // Switch on the event type to decide upon the appropriate context
2131 // to use for this event
2132 $this->editorcontext
= $this->properties
->context
;
2133 if ($this->properties
->eventtype
!= 'user' && $this->properties
->eventtype
!= 'course'
2134 && $this->properties
->eventtype
!= 'site' && $this->properties
->eventtype
!= 'group') {
2135 return clean_text($this->properties
->description
, $this->properties
->format
);
2139 // Work out the item id for the editor, if this is a repeated event then the files will
2140 // be associated with the original
2141 if (!empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
2142 $itemid = $this->properties
->repeatid
;
2144 $itemid = $this->properties
->id
;
2147 // Convert file paths in the description so that things display correctly
2148 $this->_description
= file_rewrite_pluginfile_urls($this->properties
->description
, 'pluginfile.php', $this->editorcontext
->id
, 'calendar', 'event_description', $itemid);
2149 // Clean the text so no nasties get through
2150 $this->_description
= clean_text($this->_description
, $this->properties
->format
);
2152 // Finally return the description
2153 return $this->_description
;
2157 * Return the number of repeat events there are in this events series
2159 * @return int number of event repeated
2161 public function count_repeats() {
2163 if (!empty($this->properties
->repeatid
)) {
2164 $this->properties
->eventrepeats
= $DB->count_records('event', array('repeatid'=>$this->properties
->repeatid
));
2165 // We don't want to count ourselves
2166 $this->properties
->eventrepeats
--;
2168 return $this->properties
->eventrepeats
;
2172 * Update or create an event within the database
2174 * Pass in a object containing the event properties and this function will
2175 * insert it into the database and deal with any associated files
2177 * @see self::create()
2178 * @see self::update()
2180 * @param stdClass $data object of event
2181 * @param bool $checkcapability if moodle should check calendar managing capability or not
2182 * @return bool event updated
2184 public function update($data, $checkcapability=true) {
2187 foreach ($data as $key=>$value) {
2188 $this->properties
->$key = $value;
2191 $this->properties
->timemodified
= time();
2192 $usingeditor = (!empty($this->properties
->description
) && is_array($this->properties
->description
));
2194 // Prepare event data.
2196 'context' => $this->properties
->context
,
2197 'objectid' => $this->properties
->id
,
2199 'repeatid' => empty($this->properties
->repeatid
) ?
0 : $this->properties
->repeatid
,
2200 'timestart' => $this->properties
->timestart
,
2201 'name' => $this->properties
->name
2205 if (empty($this->properties
->id
) ||
$this->properties
->id
< 1) {
2207 if ($checkcapability) {
2208 if (!calendar_add_event_allowed($this->properties
)) {
2209 print_error('nopermissiontoupdatecalendar');
2214 switch ($this->properties
->eventtype
) {
2216 $this->properties
->courseid
= 0;
2217 $this->properties
->course
= 0;
2218 $this->properties
->groupid
= 0;
2219 $this->properties
->userid
= $USER->id
;
2222 $this->properties
->courseid
= SITEID
;
2223 $this->properties
->course
= SITEID
;
2224 $this->properties
->groupid
= 0;
2225 $this->properties
->userid
= $USER->id
;
2228 $this->properties
->groupid
= 0;
2229 $this->properties
->userid
= $USER->id
;
2232 $this->properties
->userid
= $USER->id
;
2235 // Ewww we should NEVER get here, but just incase we do lets
2237 $usingeditor = false;
2241 // If we are actually using the editor, we recalculate the context because some default values
2242 // were set when calculate_context() was called from the constructor.
2244 $this->properties
->context
= $this->calculate_context($this->properties
);
2245 $this->editorcontext
= $this->properties
->context
;
2248 $editor = $this->properties
->description
;
2249 $this->properties
->format
= $this->properties
->description
['format'];
2250 $this->properties
->description
= $this->properties
->description
['text'];
2253 // Insert the event into the database
2254 $this->properties
->id
= $DB->insert_record('event', $this->properties
);
2257 $this->properties
->description
= file_save_draft_area_files(
2259 $this->editorcontext
->id
,
2261 'event_description',
2262 $this->properties
->id
,
2263 $this->editoroptions
,
2265 $this->editoroptions
['forcehttps']);
2266 $DB->set_field('event', 'description', $this->properties
->description
, array('id'=>$this->properties
->id
));
2269 // Log the event entry.
2270 $eventargs['objectid'] = $this->properties
->id
;
2271 $eventargs['context'] = $this->properties
->context
;
2272 $event = \core\event\calendar_event_created
::create($eventargs);
2275 $repeatedids = array();
2277 if (!empty($this->properties
->repeat
)) {
2278 $this->properties
->repeatid
= $this->properties
->id
;
2279 $DB->set_field('event', 'repeatid', $this->properties
->repeatid
, array('id'=>$this->properties
->id
));
2281 $eventcopy = clone($this->properties
);
2282 unset($eventcopy->id
);
2284 $timestart = new DateTime('@' . $eventcopy->timestart
);
2285 $timestart->setTimezone(core_date
::get_user_timezone_object());
2287 for($i = 1; $i < $eventcopy->repeats
; $i++
) {
2289 $timestart->add(new DateInterval('P7D'));
2290 $eventcopy->timestart
= $timestart->getTimestamp();
2292 // Get the event id for the log record.
2293 $eventcopyid = $DB->insert_record('event', $eventcopy);
2295 // If the context has been set delete all associated files
2297 $fs = get_file_storage();
2298 $files = $fs->get_area_files($this->editorcontext
->id
, 'calendar', 'event_description', $this->properties
->id
);
2299 foreach ($files as $file) {
2300 $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
2304 $repeatedids[] = $eventcopyid;
2306 // Trigger an event.
2307 $eventargs['objectid'] = $eventcopyid;
2308 $eventargs['other']['timestart'] = $eventcopy->timestart
;
2309 $event = \core\event\calendar_event_created
::create($eventargs);
2314 // Hook for tracking added events
2315 self
::calendar_event_hook('add_event', array($this->properties
, $repeatedids));
2319 if ($checkcapability) {
2320 if(!calendar_edit_event_allowed($this->properties
)) {
2321 print_error('nopermissiontoupdatecalendar');
2326 if ($this->editorcontext
!== null) {
2327 $this->properties
->description
= file_save_draft_area_files(
2328 $this->properties
->description
['itemid'],
2329 $this->editorcontext
->id
,
2331 'event_description',
2332 $this->properties
->id
,
2333 $this->editoroptions
,
2334 $this->properties
->description
['text'],
2335 $this->editoroptions
['forcehttps']);
2337 $this->properties
->format
= $this->properties
->description
['format'];
2338 $this->properties
->description
= $this->properties
->description
['text'];
2342 $event = $DB->get_record('event', array('id'=>$this->properties
->id
));
2344 $updaterepeated = (!empty($this->properties
->repeatid
) && !empty($this->properties
->repeateditall
));
2346 if ($updaterepeated) {
2348 if ($this->properties
->timestart
!= $event->timestart
) {
2349 $timestartoffset = $this->properties
->timestart
- $event->timestart
;
2350 $sql = "UPDATE {event}
2353 timestart = timestart + ?,
2356 WHERE repeatid = ?";
2357 $params = array($this->properties
->name
, $this->properties
->description
, $timestartoffset, $this->properties
->timeduration
, time(), $event->repeatid
);
2359 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
2360 $params = array($this->properties
->name
, $this->properties
->description
, $this->properties
->timeduration
, time(), $event->repeatid
);
2362 $DB->execute($sql, $params);
2364 // Trigger an update event for each of the calendar event.
2365 $events = $DB->get_records('event', array('repeatid' => $event->repeatid
), '', 'id,timestart');
2366 foreach ($events as $event) {
2367 $eventargs['objectid'] = $event->id
;
2368 $eventargs['other']['timestart'] = $event->timestart
;
2369 $event = \core\event\calendar_event_updated
::create($eventargs);
2373 $DB->update_record('event', $this->properties
);
2374 $event = calendar_event
::load($this->properties
->id
);
2375 $this->properties
= $event->properties();
2377 // Trigger an update event.
2378 $event = \core\event\calendar_event_updated
::create($eventargs);
2382 // Hook for tracking event updates
2383 self
::calendar_event_hook('update_event', array($this->properties
, $updaterepeated));
2389 * Deletes an event and if selected an repeated events in the same series
2391 * This function deletes an event, any associated events if $deleterepeated=true,
2392 * and cleans up any files associated with the events.
2394 * @see self::delete()
2396 * @param bool $deleterepeated delete event repeatedly
2397 * @return bool succession of deleting event
2399 public function delete($deleterepeated=false) {
2402 // If $this->properties->id is not set then something is wrong
2403 if (empty($this->properties
->id
)) {
2404 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER
);
2407 $calevent = $DB->get_record('event', array('id' => $this->properties
->id
), '*', MUST_EXIST
);
2409 $DB->delete_records('event', array('id'=>$this->properties
->id
));
2411 // Trigger an event for the delete action.
2413 'context' => $this->properties
->context
,
2414 'objectid' => $this->properties
->id
,
2416 'repeatid' => empty($this->properties
->repeatid
) ?
0 : $this->properties
->repeatid
,
2417 'timestart' => $this->properties
->timestart
,
2418 'name' => $this->properties
->name
2420 $event = \core\event\calendar_event_deleted
::create($eventargs);
2421 $event->add_record_snapshot('event', $calevent);
2424 // If we are deleting parent of a repeated event series, promote the next event in the series as parent
2425 if (($this->properties
->id
== $this->properties
->repeatid
) && !$deleterepeated) {
2426 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC", array($this->properties
->id
), IGNORE_MULTIPLE
);
2427 if (!empty($newparent)) {
2428 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?", array($newparent, $this->properties
->id
));
2429 // Get all records where the repeatid is the same as the event being removed
2430 $events = $DB->get_records('event', array('repeatid' => $newparent));
2431 // For each of the returned events trigger the event_update hook and an update event.
2432 foreach ($events as $event) {
2433 // Trigger an event for the update.
2434 $eventargs['objectid'] = $event->id
;
2435 $eventargs['other']['timestart'] = $event->timestart
;
2436 $event = \core\event\calendar_event_updated
::create($eventargs);
2439 self
::calendar_event_hook('update_event', array($event, false));
2444 // If the editor context hasn't already been set then set it now
2445 if ($this->editorcontext
=== null) {
2446 $this->editorcontext
= $this->properties
->context
;
2449 // If the context has been set delete all associated files
2450 if ($this->editorcontext
!== null) {
2451 $fs = get_file_storage();
2452 $files = $fs->get_area_files($this->editorcontext
->id
, 'calendar', 'event_description', $this->properties
->id
);
2453 foreach ($files as $file) {
2458 // Fire the event deleted hook
2459 self
::calendar_event_hook('delete_event', array($this->properties
->id
, $deleterepeated));
2461 // If we need to delete repeated events then we will fetch them all and delete one by one
2462 if ($deleterepeated && !empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
2463 // Get all records where the repeatid is the same as the event being removed
2464 $events = $DB->get_records('event', array('repeatid'=>$this->properties
->repeatid
));
2465 // For each of the returned events populate a calendar_event object and call delete
2466 // make sure the arg passed is false as we are already deleting all repeats
2467 foreach ($events as $event) {
2468 $event = new calendar_event($event);
2469 $event->delete(false);
2477 * Fetch all event properties
2479 * This function returns all of the events properties as an object and optionally
2480 * can prepare an editor for the description field at the same time. This is
2481 * designed to work when the properties are going to be used to set the default
2482 * values of a moodle forms form.
2484 * @param bool $prepareeditor If set to true a editor is prepared for use with
2485 * the mforms editor element. (for description)
2486 * @return stdClass Object containing event properties
2488 public function properties($prepareeditor=false) {
2489 global $USER, $CFG, $DB;
2491 // First take a copy of the properties. We don't want to actually change the
2492 // properties or we'd forever be converting back and forwards between an
2493 // editor formatted description and not
2494 $properties = clone($this->properties
);
2495 // Clean the description here
2496 $properties->description
= clean_text($properties->description
, $properties->format
);
2498 // If set to true we need to prepare the properties for use with an editor
2499 // and prepare the file area
2500 if ($prepareeditor) {
2502 // We may or may not have a property id. If we do then we need to work
2503 // out the context so we can copy the existing files to the draft area
2504 if (!empty($properties->id
)) {
2506 if ($properties->eventtype
=== 'site') {
2508 $this->editorcontext
= $this->properties
->context
;
2509 } else if ($properties->eventtype
=== 'user') {
2511 $this->editorcontext
= $this->properties
->context
;
2512 } else if ($properties->eventtype
=== 'group' ||
$properties->eventtype
=== 'course') {
2513 // First check the course is valid
2514 $course = $DB->get_record('course', array('id'=>$properties->courseid
));
2516 print_error('invalidcourse');
2519 $this->editorcontext
= $this->properties
->context
;
2520 // We have a course and are within the course context so we had
2521 // better use the courses max bytes value
2522 $this->editoroptions
['maxbytes'] = $course->maxbytes
;
2524 // If we get here we have a custom event type as used by some
2525 // modules. In this case the event will have been added by
2526 // code and we won't need the editor
2527 $this->editoroptions
['maxbytes'] = 0;
2528 $this->editoroptions
['maxfiles'] = 0;
2531 if (empty($this->editorcontext
) ||
empty($this->editorcontext
->id
)) {
2534 // Get the context id that is what we really want
2535 $contextid = $this->editorcontext
->id
;
2539 // If we get here then this is a new event in which case we don't need a
2540 // context as there is no existing files to copy to the draft area.
2544 // If the contextid === false we don't support files so no preparing
2546 if ($contextid !== false) {
2547 // Just encase it has already been submitted
2548 $draftiddescription = file_get_submitted_draft_itemid('description');
2549 // Prepare the draft area, this copies existing files to the draft area as well
2550 $properties->description
= file_prepare_draft_area($draftiddescription, $contextid, 'calendar', 'event_description', $properties->id
, $this->editoroptions
, $properties->description
);
2552 $draftiddescription = 0;
2555 // Structure the description field as the editor requires
2556 $properties->description
= array('text'=>$properties->description
, 'format'=>$properties->format
, 'itemid'=>$draftiddescription);
2559 // Finally return the properties
2564 * Toggles the visibility of an event
2566 * @param null|bool $force If it is left null the events visibility is flipped,
2567 * If it is false the event is made hidden, if it is true it
2569 * @return bool if event is successfully updated, toggle will be visible
2571 public function toggle_visibility($force=null) {
2574 // Set visible to the default if it is not already set
2575 if (empty($this->properties
->visible
)) {
2576 $this->properties
->visible
= 1;
2579 if ($force === true ||
($force !== false && $this->properties
->visible
== 0)) {
2580 // Make this event visible
2581 $this->properties
->visible
= 1;
2583 self
::calendar_event_hook('show_event', array($this->properties
));
2585 // Make this event hidden
2586 $this->properties
->visible
= 0;
2588 self
::calendar_event_hook('hide_event', array($this->properties
));
2591 // Update the database to reflect this change
2592 return $DB->set_field('event', 'visible', $this->properties
->visible
, array('id'=>$this->properties
->id
));
2596 * Attempts to call the hook for the specified action should a calendar type
2597 * by set $CFG->calendar, and the appopriate function defined
2599 * @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
2600 * @param array $args The args to pass to the hook, usually the event is the first element
2601 * @return bool attempts to call event hook
2603 public static function calendar_event_hook($action, array $args) {
2605 static $extcalendarinc;
2606 if ($extcalendarinc === null) {
2607 if (!empty($CFG->calendar
)) {
2608 if (is_readable($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
2609 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
2610 $extcalendarinc = true;
2612 debugging("Calendar lib file missing or not readable at /calendar/{$CFG->calendar}/lib.php.",
2614 $extcalendarinc = false;
2617 $extcalendarinc = false;
2620 if($extcalendarinc === false) {
2623 $hook = $CFG->calendar
.'_'.$action;
2624 if (function_exists($hook)) {
2625 call_user_func_array($hook, $args);
2632 * Returns a calendar_event object when provided with an event id
2634 * This function makes use of MUST_EXIST, if the event id passed in is invalid
2635 * it will result in an exception being thrown
2637 * @param int|object $param event object or event id
2638 * @return calendar_event|false status for loading calendar_event
2640 public static function load($param) {
2642 if (is_object($param)) {
2643 $event = new calendar_event($param);
2645 $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST
);
2646 $event = new calendar_event($event);
2652 * Creates a new event and returns a calendar_event object
2654 * @param stdClass|array $properties An object containing event properties
2655 * @param bool $checkcapability Check caps or not
2656 * @throws coding_exception
2658 * @return calendar_event|bool The event object or false if it failed
2660 public static function create($properties, $checkcapability = true) {
2661 if (is_array($properties)) {
2662 $properties = (object)$properties;
2664 if (!is_object($properties)) {
2665 throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2667 $event = new calendar_event($properties);
2668 if ($event->update($properties, $checkcapability)) {
2677 * Calendar information class
2679 * This class is used simply to organise the information pertaining to a calendar
2680 * and is used primarily to make information easily available.
2682 * @package core_calendar
2683 * @category calendar
2684 * @copyright 2010 Sam Hemelryk
2685 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2687 class calendar_information
{
2690 * @var int The timestamp
2692 * Rather than setting the day, month and year we will set a timestamp which will be able
2693 * to be used by multiple calendars.
2697 /** @var int A course id */
2698 public $courseid = null;
2700 /** @var array An array of courses */
2701 public $courses = array();
2703 /** @var array An array of groups */
2704 public $groups = array();
2706 /** @var array An array of users */
2707 public $users = array();
2710 * Creates a new instance
2712 * @param int $day the number of the day
2713 * @param int $month the number of the month
2714 * @param int $year the number of the year
2715 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
2716 * and $calyear to support multiple calendars
2718 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
2719 // If a day, month and year were passed then convert it to a timestamp. If these were passed
2720 // then we can assume the day, month and year are passed as Gregorian, as no where in core
2721 // should we be passing these values rather than the time. This is done for BC.
2722 if (!empty($day) ||
!empty($month) ||
!empty($year)) {
2723 $date = usergetdate(time());
2725 $day = $date['mday'];
2727 if (empty($month)) {
2728 $month = $date['mon'];
2731 $year = $date['year'];
2733 if (checkdate($month, $day, $year)) {
2734 $this->time
= make_timestamp($year, $month, $day);
2736 $this->time
= time();
2738 } else if (!empty($time)) {
2739 $this->time
= $time;
2741 $this->time
= time();
2746 * Initialize calendar information
2748 * @param stdClass $course object
2749 * @param array $coursestoload An array of courses [$course->id => $course]
2750 * @param bool $ignorefilters options to use filter
2752 public function prepare_for_view(stdClass
$course, array $coursestoload, $ignorefilters = false) {
2753 $this->courseid
= $course->id
;
2754 $this->course
= $course;
2755 list($courses, $group, $user) = calendar_set_filters($coursestoload, $ignorefilters);
2756 $this->courses
= $courses;
2757 $this->groups
= $group;
2758 $this->users
= $user;
2762 * Ensures the date for the calendar is correct and either sets it to now
2763 * or throws a moodle_exception if not
2765 * @param bool $defaultonow use current time
2766 * @throws moodle_exception
2767 * @return bool validation of checkdate
2769 public function checkdate($defaultonow = true) {
2770 if (!checkdate($this->month
, $this->day
, $this->year
)) {
2772 $now = usergetdate(time());
2773 $this->day
= intval($now['mday']);
2774 $this->month
= intval($now['mon']);
2775 $this->year
= intval($now['year']);
2778 throw new moodle_exception('invaliddate');
2785 * Gets todays timestamp for the calendar
2787 * @return int today timestamp
2789 public function timestamp_today() {
2793 * Gets tomorrows timestamp for the calendar
2795 * @return int tomorrow timestamp
2797 public function timestamp_tomorrow() {
2798 return strtotime('+1 day', $this->time
);
2801 * Adds the pretend blocks for the calendar
2803 * @param core_calendar_renderer $renderer
2804 * @param bool $showfilters display filters, false is set as default
2805 * @param string|null $view preference view options (eg: day, month, upcoming)
2807 public function add_sidecalendar_blocks(core_calendar_renderer
$renderer, $showfilters=false, $view=null) {
2809 $filters = new block_contents();
2810 $filters->content
= $renderer->fake_block_filters($this->courseid
, 0, 0, 0, $view, $this->courses
);
2811 $filters->footer
= '';
2812 $filters->title
= get_string('eventskey', 'calendar');
2813 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT
);
2815 $block = new block_contents
;
2816 $block->content
= $renderer->fake_block_threemonths($this);
2817 $block->footer
= '';
2818 $block->title
= get_string('monthlyview', 'calendar');
2819 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT
);
2824 * Returns option list for the poll interval setting.
2826 * @return array An array of poll interval options. Interval => description.
2828 function calendar_get_pollinterval_choices() {
2830 '0' => new lang_string('never', 'calendar'),
2831 HOURSECS
=> new lang_string('hourly', 'calendar'),
2832 DAYSECS
=> new lang_string('daily', 'calendar'),
2833 WEEKSECS
=> new lang_string('weekly', 'calendar'),
2834 '2628000' => new lang_string('monthly', 'calendar'),
2835 YEARSECS
=> new lang_string('annually', 'calendar')
2840 * Returns option list of available options for the calendar event type, given the current user and course.
2842 * @param int $courseid The id of the course
2843 * @return array An array containing the event types the user can create.
2845 function calendar_get_eventtype_choices($courseid) {
2847 $allowed = new stdClass
;
2848 calendar_get_allowed_types($allowed, $courseid);
2850 if ($allowed->user
) {
2851 $choices['user'] = get_string('userevents', 'calendar');
2853 if ($allowed->site
) {
2854 $choices['site'] = get_string('siteevents', 'calendar');
2856 if (!empty($allowed->courses
)) {
2857 $choices['course'] = get_string('courseevents', 'calendar');
2859 if (!empty($allowed->groups
) and is_array($allowed->groups
)) {
2860 $choices['group'] = get_string('group');
2863 return array($choices, $allowed->groups
);
2867 * Add an iCalendar subscription to the database.
2869 * @param stdClass $sub The subscription object (e.g. from the form)
2870 * @return int The insert ID, if any.
2872 function calendar_add_subscription($sub) {
2873 global $DB, $USER, $SITE;
2875 if ($sub->eventtype
=== 'site') {
2876 $sub->courseid
= $SITE->id
;
2877 } else if ($sub->eventtype
=== 'group' ||
$sub->eventtype
=== 'course') {
2878 $sub->courseid
= $sub->course
;
2883 $sub->userid
= $USER->id
;
2885 // File subscriptions never update.
2886 if (empty($sub->url
)) {
2887 $sub->pollinterval
= 0;
2890 if (!empty($sub->name
)) {
2891 if (empty($sub->id
)) {
2892 $id = $DB->insert_record('event_subscriptions', $sub);
2893 // we cannot cache the data here because $sub is not complete.
2896 // Why are we doing an update here?
2897 calendar_update_subscription($sub);
2901 print_error('errorbadsubscription', 'importcalendar');
2906 * Add an iCalendar event to the Moodle calendar.
2908 * @param stdClass $event The RFC-2445 iCalendar event
2909 * @param int $courseid The course ID
2910 * @param int $subscriptionid The iCalendar subscription ID
2911 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2912 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2913 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2915 function calendar_add_icalendar_event($event, $courseid, $subscriptionid, $timezone='UTC') {
2918 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2919 if (empty($event->properties
['SUMMARY'])) {
2923 $name = $event->properties
['SUMMARY'][0]->value
;
2924 $name = str_replace('\n', '<br />', $name);
2925 $name = str_replace('\\', '', $name);
2926 $name = preg_replace('/\s+/u', ' ', $name);
2928 $eventrecord = new stdClass
;
2929 $eventrecord->name
= clean_param($name, PARAM_NOTAGS
);
2931 if (empty($event->properties
['DESCRIPTION'][0]->value
)) {
2934 $description = $event->properties
['DESCRIPTION'][0]->value
;
2935 $description = clean_param($description, PARAM_NOTAGS
);
2936 $description = str_replace('\n', '<br />', $description);
2937 $description = str_replace('\\', '', $description);
2938 $description = preg_replace('/\s+/u', ' ', $description);
2940 $eventrecord->description
= $description;
2942 // Probably a repeating event with RRULE etc. TODO: skip for now.
2943 if (empty($event->properties
['DTSTART'][0]->value
)) {
2947 $tz = isset($event->properties
['DTSTART'][0]->parameters
['TZID']) ?
$event->properties
['DTSTART'][0]->parameters
['TZID'] :
2949 $tz = core_date
::normalise_timezone($tz);
2950 $eventrecord->timestart
= strtotime($event->properties
['DTSTART'][0]->value
. ' ' . $tz);
2951 if (empty($event->properties
['DTEND'])) {
2952 $eventrecord->timeduration
= 0; // no duration if no end time specified
2954 $endtz = isset($event->properties
['DTEND'][0]->parameters
['TZID']) ?
$event->properties
['DTEND'][0]->parameters
['TZID'] :
2956 $endtz = core_date
::normalise_timezone($endtz);
2957 $eventrecord->timeduration
= strtotime($event->properties
['DTEND'][0]->value
. ' ' . $endtz) - $eventrecord->timestart
;
2960 // Check to see if it should be treated as an all day event.
2961 if ($eventrecord->timeduration
== DAYSECS
) {
2962 // Check to see if the event started at Midnight on the imported calendar.
2963 date_default_timezone_set($timezone);
2964 if (date('H:i:s', $eventrecord->timestart
) === "00:00:00") {
2965 // This event should be an all day event.
2966 $eventrecord->timeduration
= 0;
2968 core_date
::set_default_server_timezone();
2971 $eventrecord->uuid
= $event->properties
['UID'][0]->value
;
2972 $eventrecord->timemodified
= time();
2974 // Add the iCal subscription details if required.
2975 // We should never do anything with an event without a subscription reference.
2976 $sub = calendar_get_subscription($subscriptionid);
2977 $eventrecord->subscriptionid
= $subscriptionid;
2978 $eventrecord->userid
= $sub->userid
;
2979 $eventrecord->groupid
= $sub->groupid
;
2980 $eventrecord->courseid
= $sub->courseid
;
2981 $eventrecord->eventtype
= $sub->eventtype
;
2983 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid
))) {
2984 $eventrecord->id
= $updaterecord->id
;
2985 $return = CALENDAR_IMPORT_EVENT_UPDATED
; // Update.
2987 $return = CALENDAR_IMPORT_EVENT_INSERTED
; // Insert.
2989 if ($createdevent = calendar_event
::create($eventrecord, false)) {
2990 if (!empty($event->properties
['RRULE'])) {
2991 // Repeating events.
2992 date_default_timezone_set($tz); // Change time zone to parse all events.
2993 $rrule = new \core_calendar\rrule_manager
($event->properties
['RRULE'][0]->value
);
2994 $rrule->parse_rrule();
2995 $rrule->create_events($createdevent);
2996 core_date
::set_default_server_timezone(); // Change time zone back to what it was.
3005 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
3007 * @param int $subscriptionid The ID of the subscription we are acting upon.
3008 * @param int $pollinterval The poll interval to use.
3009 * @param int $action The action to be performed. One of update or remove.
3010 * @throws dml_exception if invalid subscriptionid is provided
3011 * @return string A log of the import progress, including errors
3013 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
3015 // Fetch the subscription from the database making sure it exists.
3016 $sub = calendar_get_subscription($subscriptionid);
3018 // Update or remove the subscription, based on action.
3020 case CALENDAR_SUBSCRIPTION_UPDATE
:
3021 // Skip updating file subscriptions.
3022 if (empty($sub->url
)) {
3025 $sub->pollinterval
= $pollinterval;
3026 calendar_update_subscription($sub);
3028 // Update the events.
3029 return "<p>".get_string('subscriptionupdated', 'calendar', $sub->name
)."</p>" . calendar_update_subscription_events($subscriptionid);
3031 case CALENDAR_SUBSCRIPTION_REMOVE
:
3032 calendar_delete_subscription($subscriptionid);
3033 return get_string('subscriptionremoved', 'calendar', $sub->name
);
3043 * Delete subscription and all related events.
3045 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
3047 function calendar_delete_subscription($subscription) {
3050 if (is_object($subscription)) {
3051 $subscription = $subscription->id
;
3053 // Delete subscription and related events.
3054 $DB->delete_records('event', array('subscriptionid' => $subscription));
3055 $DB->delete_records('event_subscriptions', array('id' => $subscription));
3056 cache_helper
::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription));
3059 * From a URL, fetch the calendar and return an iCalendar object.
3061 * @param string $url The iCalendar URL
3062 * @return stdClass The iCalendar object
3064 function calendar_get_icalendar($url) {
3067 require_once($CFG->libdir
.'/filelib.php');
3070 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
3071 $calendar = $curl->get($url);
3072 // Http code validation should actually be the job of curl class.
3073 if (!$calendar ||
$curl->info
['http_code'] != 200 ||
!empty($curl->errorno
)) {
3074 throw new moodle_exception('errorinvalidicalurl', 'calendar');
3077 $ical = new iCalendar();
3078 $ical->unserialize($calendar);
3083 * Import events from an iCalendar object into a course calendar.
3085 * @param stdClass $ical The iCalendar object.
3086 * @param int $courseid The course ID for the calendar.
3087 * @param int $subscriptionid The subscription ID.
3088 * @return string A log of the import progress, including errors.
3090 function calendar_import_icalendar_events($ical, $courseid, $subscriptionid = null) {
3096 // Large calendars take a while...
3098 core_php_time_limit
::raise(300);
3101 // Mark all events in a subscription with a zero timestamp.
3102 if (!empty($subscriptionid)) {
3103 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
3104 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3106 // Grab the timezone from the iCalendar file to be used later.
3107 if (isset($ical->properties
['X-WR-TIMEZONE'][0]->value
)) {
3108 $timezone = $ical->properties
['X-WR-TIMEZONE'][0]->value
;
3112 foreach ($ical->components
['VEVENT'] as $event) {
3113 $res = calendar_add_icalendar_event($event, $courseid, $subscriptionid, $timezone);
3115 case CALENDAR_IMPORT_EVENT_UPDATED
:
3118 case CALENDAR_IMPORT_EVENT_INSERTED
:
3122 $return .= '<p>'.get_string('erroraddingevent', 'calendar').': '.(empty($event->properties
['SUMMARY'])?
'('.get_string('notitle', 'calendar').')':$event->properties
['SUMMARY'][0]->value
)." </p>\n";
3126 $return .= "<p> ".get_string('eventsimported', 'calendar', $eventcount)."</p>";
3127 $return .= "<p> ".get_string('eventsupdated', 'calendar', $updatecount)."</p>";
3129 // Delete remaining zero-marked events since they're not in remote calendar.
3130 if (!empty($subscriptionid)) {
3131 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3132 if (!empty($deletecount)) {
3133 $sql = "DELETE FROM {event} WHERE timemodified = :time AND subscriptionid = :id";
3134 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3135 $return .= "<p> ".get_string('eventsdeleted', 'calendar').": {$deletecount} </p>\n";
3143 * Fetch a calendar subscription and update the events in the calendar.
3145 * @param int $subscriptionid The course ID for the calendar.
3146 * @return string A log of the import progress, including errors.
3148 function calendar_update_subscription_events($subscriptionid) {
3151 $sub = calendar_get_subscription($subscriptionid);
3152 // Don't update a file subscription. TODO: Update from a new uploaded file.
3153 if (empty($sub->url
)) {
3154 return 'File subscription not updated.';
3156 $ical = calendar_get_icalendar($sub->url
);
3157 $return = calendar_import_icalendar_events($ical, $sub->courseid
, $subscriptionid);
3158 $sub->lastupdated
= time();
3159 calendar_update_subscription($sub);
3164 * Update a calendar subscription. Also updates the associated cache.
3166 * @param stdClass|array $subscription Subscription record.
3167 * @throws coding_exception If something goes wrong
3170 function calendar_update_subscription($subscription) {
3173 if (is_array($subscription)) {
3174 $subscription = (object)$subscription;
3176 if (empty($subscription->id
) ||
!$DB->record_exists('event_subscriptions', array('id' => $subscription->id
))) {
3177 throw new coding_exception('Cannot update a subscription without a valid id');
3180 $DB->update_record('event_subscriptions', $subscription);
3182 $cache = cache
::make('core', 'calendar_subscriptions');
3183 $cache->set($subscription->id
, $subscription);
3187 * Checks to see if the user can edit a given subscription feed.
3189 * @param mixed $subscriptionorid Subscription object or id
3190 * @return bool true if current user can edit the subscription else false
3192 function calendar_can_edit_subscription($subscriptionorid) {
3195 if (is_array($subscriptionorid)) {
3196 $subscription = (object)$subscriptionorid;
3197 } else if (is_object($subscriptionorid)) {
3198 $subscription = $subscriptionorid;
3200 $subscription = calendar_get_subscription($subscriptionorid);
3202 $allowed = new stdClass
;
3203 $courseid = $subscription->courseid
;
3204 $groupid = $subscription->groupid
;
3205 calendar_get_allowed_types($allowed, $courseid);
3206 switch ($subscription->eventtype
) {
3208 return $allowed->user
;
3210 if (isset($allowed->courses
[$courseid])) {
3211 return $allowed->courses
[$courseid];
3216 return $allowed->site
;
3218 if (isset($allowed->groups
[$groupid])) {
3219 return $allowed->groups
[$groupid];
3229 * Update calendar subscriptions.
3233 function calendar_cron() {
3236 // In order to execute this we need bennu.
3237 require_once($CFG->libdir
.'/bennu/bennu.inc.php');
3239 mtrace('Updating calendar subscriptions:');
3240 cron_trace_time_and_memory();
3243 $subscriptions = $DB->get_records_sql('SELECT * FROM {event_subscriptions} WHERE pollinterval > 0 AND lastupdated + pollinterval < ?', array($time));
3244 foreach ($subscriptions as $sub) {
3245 mtrace("Updating calendar subscription {$sub->name} in course {$sub->courseid}");
3247 $log = calendar_update_subscription_events($sub->id
);
3248 mtrace(trim(strip_tags($log)));
3249 } catch (moodle_exception
$ex) {
3250 mtrace('Error updating calendar subscription: ' . $ex->getMessage());
3254 mtrace('Finished updating calendar subscriptions.');