MDL-81412 calendar: Sanitise calendar event names
[moodle.git] / calendar / lib.php
blob7c48489f432b8d5a262910d786bb179845300e31
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Calendar extension
20 * @package core_calendar
21 * @copyright 2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
22 * Avgoustos Tsinakos
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 use core_external\external_api;
28 if (!defined('MOODLE_INTERNAL')) {
29 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
32 /**
33 * These are read by the administration component to provide default values
36 /**
37 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
39 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
41 /**
42 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
44 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
46 /**
47 * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
49 define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
51 // This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
52 // Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
54 /**
55 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
57 define('CALENDAR_DEFAULT_WEEKEND', 65);
59 /**
60 * CALENDAR_URL - path to calendar's folder
62 define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
64 /**
65 * CALENDAR_TF_24 - Calendar time in 24 hours format
67 define('CALENDAR_TF_24', '%H:%M');
69 /**
70 * CALENDAR_TF_12 - Calendar time in 12 hours format
72 define('CALENDAR_TF_12', '%I:%M %p');
74 /**
75 * CALENDAR_EVENT_SITE - Site calendar event types
77 define('CALENDAR_EVENT_SITE', 1);
79 /**
80 * CALENDAR_EVENT_COURSE - Course calendar event types
82 define('CALENDAR_EVENT_COURSE', 2);
84 /**
85 * CALENDAR_EVENT_GROUP - group calendar event types
87 define('CALENDAR_EVENT_GROUP', 4);
89 /**
90 * CALENDAR_EVENT_USER - user calendar event types
92 define('CALENDAR_EVENT_USER', 8);
94 /**
95 * CALENDAR_EVENT_COURSECAT - Course category calendar event types
97 define('CALENDAR_EVENT_COURSECAT', 16);
99 /**
100 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
102 define('CALENDAR_IMPORT_FROM_FILE', 0);
105 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
107 define('CALENDAR_IMPORT_FROM_URL', 1);
110 * CALENDAR_IMPORT_EVENT_UPDATED_SKIPPED - imported event was skipped
112 define('CALENDAR_IMPORT_EVENT_SKIPPED', -1);
115 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
117 define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
120 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
122 define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
125 * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
127 define('CALENDAR_SUBSCRIPTION_UPDATE', 1);
130 * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
132 define('CALENDAR_SUBSCRIPTION_REMOVE', 2);
135 * CALENDAR_EVENT_USER_OVERRIDE_PRIORITY - Constant for the user override priority.
137 define('CALENDAR_EVENT_USER_OVERRIDE_PRIORITY', 0);
140 * CALENDAR_EVENT_TYPE_STANDARD - Standard events.
142 define('CALENDAR_EVENT_TYPE_STANDARD', 0);
145 * CALENDAR_EVENT_TYPE_ACTION - Action events.
147 define('CALENDAR_EVENT_TYPE_ACTION', 1);
150 * Manage calendar events.
152 * This class provides the required functionality in order to manage calendar events.
153 * It was introduced as part of Moodle 2.0 and was created in order to provide a
154 * better framework for dealing with calendar events in particular regard to file
155 * handling through the new file API.
157 * @package core_calendar
158 * @category calendar
159 * @copyright 2009 Sam Hemelryk
160 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
162 * @property int $id The id within the event table
163 * @property string $name The name of the event
164 * @property string $description The description of the event
165 * @property int $format The format of the description FORMAT_?
166 * @property int $courseid The course the event is associated with (0 if none)
167 * @property int $groupid The group the event is associated with (0 if none)
168 * @property int $userid The user the event is associated with (0 if none)
169 * @property int $repeatid If this is a repeated event this will be set to the
170 * id of the original
171 * @property string $component If created by a plugin/component (other than module), the full frankenstyle name of a component
172 * @property string $modulename If added by a module this will be the module name
173 * @property int $instance If added by a module this will be the module instance
174 * @property string $eventtype The event type
175 * @property int $timestart The start time as a timestamp
176 * @property int $timeduration The duration of the event in seconds
177 * @property int $timeusermidnight User midnight for the event
178 * @property int $visible 1 if the event is visible
179 * @property int $uuid ?
180 * @property int $sequence ?
181 * @property int $timemodified The time last modified as a timestamp
183 class calendar_event {
185 /** @var stdClass An object containing the event properties can be accessed via the magic __get/set methods */
186 protected $properties = null;
188 /** @var string The converted event discription with file paths resolved.
189 * This gets populated when someone requests description for the first time */
190 protected $_description = null;
192 /** @var array The options to use with this description editor */
193 protected $editoroptions = array(
194 'subdirs' => false,
195 'forcehttps' => false,
196 'maxfiles' => -1,
197 'maxbytes' => null,
198 'trusttext' => false);
200 /** @var object The context to use with the description editor */
201 protected $editorcontext = null;
204 * Instantiates a new event and optionally populates its properties with the data provided.
206 * @param \stdClass $data Optional. An object containing the properties to for
207 * an event
209 public function __construct($data = null) {
210 global $CFG, $USER;
212 // First convert to object if it is not already (should either be object or assoc array).
213 if (!is_object($data)) {
214 $data = (object) $data;
217 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
219 $data->eventrepeats = 0;
221 if (empty($data->id)) {
222 $data->id = null;
225 if (!empty($data->subscriptionid)) {
226 $data->subscription = calendar_get_subscription($data->subscriptionid);
229 // Default to a user event.
230 if (empty($data->eventtype)) {
231 $data->eventtype = 'user';
234 // Default to the current user.
235 if (empty($data->userid)) {
236 $data->userid = $USER->id;
239 if (!empty($data->timeduration) && is_array($data->timeduration)) {
240 $data->timeduration = make_timestamp(
241 $data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'],
242 $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
245 if (!empty($data->description) && is_array($data->description)) {
246 $data->format = $data->description['format'];
247 $data->description = $data->description['text'];
248 } else if (empty($data->description)) {
249 $data->description = '';
250 $data->format = editors_get_preferred_format();
253 // Ensure form is defaulted correctly.
254 if (empty($data->format)) {
255 $data->format = editors_get_preferred_format();
258 if (empty($data->component)) {
259 $data->component = null;
262 $this->properties = $data;
266 * Magic set method.
268 * Attempts to call a set_$key method if one exists otherwise falls back
269 * to simply set the property.
271 * @param string $key property name
272 * @param mixed $value value of the property
274 public function __set($key, $value) {
275 if (method_exists($this, 'set_'.$key)) {
276 $this->{'set_'.$key}($value);
278 $this->properties->{$key} = $value;
282 * Magic get method.
284 * Attempts to call a get_$key method to return the property and ralls over
285 * to return the raw property.
287 * @param string $key property name
288 * @return mixed property value
289 * @throws \coding_exception
291 public function __get($key) {
292 if (method_exists($this, 'get_'.$key)) {
293 return $this->{'get_'.$key}();
295 if (!property_exists($this->properties, $key)) {
296 throw new \coding_exception('Undefined property requested');
298 return $this->properties->{$key};
302 * Magic isset method.
304 * PHP needs an isset magic method if you use the get magic method and
305 * still want empty calls to work.
307 * @param string $key $key property name
308 * @return bool|mixed property value, false if property is not exist
310 public function __isset($key) {
311 return !empty($this->properties->{$key});
315 * Calculate the context value needed for an event.
317 * Event's type can be determine by the available value store in $data
318 * It is important to check for the existence of course/courseid to determine
319 * the course event.
320 * Default value is set to CONTEXT_USER
322 * @return \stdClass The context object.
324 protected function calculate_context() {
325 global $USER, $DB;
327 $context = null;
328 if (isset($this->properties->categoryid) && $this->properties->categoryid > 0) {
329 $context = \context_coursecat::instance($this->properties->categoryid);
330 } else if (isset($this->properties->courseid) && $this->properties->courseid > 0) {
331 $context = \context_course::instance($this->properties->courseid);
332 } else if (isset($this->properties->course) && $this->properties->course > 0) {
333 $context = \context_course::instance($this->properties->course);
334 } else if (isset($this->properties->groupid) && $this->properties->groupid > 0) {
335 $group = $DB->get_record('groups', array('id' => $this->properties->groupid));
336 $context = \context_course::instance($group->courseid);
337 } else if (isset($this->properties->userid) && $this->properties->userid > 0
338 && $this->properties->userid == $USER->id) {
339 $context = \context_user::instance($this->properties->userid);
340 } else if (isset($this->properties->userid) && $this->properties->userid > 0
341 && $this->properties->userid != $USER->id &&
342 !empty($this->properties->modulename) &&
343 isset($this->properties->instance) && $this->properties->instance > 0) {
344 $cm = get_coursemodule_from_instance($this->properties->modulename, $this->properties->instance, 0,
345 false, MUST_EXIST);
346 $context = \context_course::instance($cm->course);
347 } else {
348 $context = \context_user::instance($this->properties->userid);
351 return $context;
355 * Returns the context for this event. The context is calculated
356 * the first time is is requested and then stored in a member
357 * variable to be returned each subsequent time.
359 * This is a magical getter function that will be called when
360 * ever the context property is accessed, e.g. $event->context.
362 * @return context
364 protected function get_context() {
365 if (!isset($this->properties->context)) {
366 $this->properties->context = $this->calculate_context();
369 return $this->properties->context;
373 * Returns an array of editoroptions for this event.
375 * @return array event editor options
377 protected function get_editoroptions() {
378 return $this->editoroptions;
382 * Returns an event description: Called by __get
383 * Please use $blah = $event->description;
385 * @return string event description
387 protected function get_description() {
388 global $CFG;
390 require_once($CFG->libdir . '/filelib.php');
392 if ($this->_description === null) {
393 // Check if we have already resolved the context for this event.
394 if ($this->editorcontext === null) {
395 // Switch on the event type to decide upon the appropriate context to use for this event.
396 $this->editorcontext = $this->get_context();
397 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
398 return clean_text($this->properties->description, $this->properties->format);
402 // Work out the item id for the editor, if this is a repeated event
403 // then the files will be associated with the original.
404 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
405 $itemid = $this->properties->repeatid;
406 } else {
407 $itemid = $this->properties->id;
410 // Convert file paths in the description so that things display correctly.
411 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php',
412 $this->editorcontext->id, 'calendar', 'event_description', $itemid);
413 // Clean the text so no nasties get through.
414 $this->_description = clean_text($this->_description, $this->properties->format);
417 // Finally return the description.
418 return $this->_description;
422 * Return the number of repeat events there are in this events series.
424 * @return int number of event repeated
426 public function count_repeats() {
427 global $DB;
428 if (!empty($this->properties->repeatid)) {
429 $this->properties->eventrepeats = $DB->count_records('event',
430 array('repeatid' => $this->properties->repeatid));
431 // We don't want to count ourselves.
432 $this->properties->eventrepeats--;
434 return $this->properties->eventrepeats;
438 * Update or create an event within the database
440 * Pass in a object containing the event properties and this function will
441 * insert it into the database and deal with any associated files
443 * Capability checking should be performed if the user is directly manipulating the event
444 * and no other capability has been tested. However if the event is not being manipulated
445 * directly by the user and another capability has been checked for them to do this then
446 * capabilites should not be checked.
448 * For example if a user is editing an event in the calendar the check should be true,
449 * but if you are updating an event in an activities settings are changed then the calendar
450 * capabilites should not be checked.
452 * @see self::create()
453 * @see self::update()
455 * @param \stdClass $data object of event
456 * @param bool $checkcapability If Moodle should check the user can manage the calendar events for this call or not.
457 * @return bool event updated
459 public function update($data, $checkcapability=true) {
460 global $DB, $USER;
462 foreach ($data as $key => $value) {
463 $this->properties->$key = $value;
466 $this->properties->timemodified = time();
467 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
469 // Prepare event data.
470 $eventargs = array(
471 'context' => $this->get_context(),
472 'objectid' => $this->properties->id,
473 'other' => array(
474 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
475 'timestart' => $this->properties->timestart,
476 'name' => $this->properties->name
480 if (empty($this->properties->id) || $this->properties->id < 1) {
481 if ($checkcapability) {
482 if (!calendar_add_event_allowed($this->properties)) {
483 throw new \moodle_exception('nopermissiontoupdatecalendar');
487 if ($usingeditor) {
488 switch ($this->properties->eventtype) {
489 case 'user':
490 $this->properties->courseid = 0;
491 $this->properties->course = 0;
492 $this->properties->groupid = 0;
493 $this->properties->userid = $USER->id;
494 break;
495 case 'site':
496 $this->properties->courseid = SITEID;
497 $this->properties->course = SITEID;
498 $this->properties->groupid = 0;
499 $this->properties->userid = $USER->id;
500 break;
501 case 'course':
502 $this->properties->groupid = 0;
503 $this->properties->userid = $USER->id;
504 break;
505 case 'category':
506 $this->properties->groupid = 0;
507 $this->properties->category = 0;
508 $this->properties->userid = $USER->id;
509 break;
510 case 'group':
511 $this->properties->userid = $USER->id;
512 break;
513 default:
514 // We should NEVER get here, but just incase we do lets fail gracefully.
515 $usingeditor = false;
516 break;
519 // If we are actually using the editor, we recalculate the context because some default values
520 // were set when calculate_context() was called from the constructor.
521 if ($usingeditor) {
522 $this->properties->context = $this->calculate_context();
523 $this->editorcontext = $this->get_context();
526 $editor = $this->properties->description;
527 $this->properties->format = $this->properties->description['format'];
528 $this->properties->description = $this->properties->description['text'];
531 // Insert the event into the database.
532 $this->properties->id = $DB->insert_record('event', $this->properties);
534 if ($usingeditor) {
535 $this->properties->description = file_save_draft_area_files(
536 $editor['itemid'],
537 $this->editorcontext->id,
538 'calendar',
539 'event_description',
540 $this->properties->id,
541 $this->editoroptions,
542 $editor['text'],
543 $this->editoroptions['forcehttps']);
544 $DB->set_field('event', 'description', $this->properties->description,
545 array('id' => $this->properties->id));
548 // Log the event entry.
549 $eventargs['objectid'] = $this->properties->id;
550 $eventargs['context'] = $this->get_context();
551 $event = \core\event\calendar_event_created::create($eventargs);
552 $event->trigger();
554 $repeatedids = array();
556 if (!empty($this->properties->repeat)) {
557 $this->properties->repeatid = $this->properties->id;
558 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id' => $this->properties->id));
560 $eventcopy = clone($this->properties);
561 unset($eventcopy->id);
563 $timestart = new \DateTime('@' . $eventcopy->timestart);
564 $timestart->setTimezone(\core_date::get_user_timezone_object());
566 for ($i = 1; $i < $eventcopy->repeats; $i++) {
568 $timestart->add(new \DateInterval('P7D'));
569 $eventcopy->timestart = $timestart->getTimestamp();
571 // Get the event id for the log record.
572 $eventcopyid = $DB->insert_record('event', $eventcopy);
574 // If the context has been set delete all associated files.
575 if ($usingeditor) {
576 $fs = get_file_storage();
577 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description',
578 $this->properties->id);
579 foreach ($files as $file) {
580 $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
584 $repeatedids[] = $eventcopyid;
586 // Trigger an event.
587 $eventargs['objectid'] = $eventcopyid;
588 $eventargs['other']['timestart'] = $eventcopy->timestart;
589 $event = \core\event\calendar_event_created::create($eventargs);
590 $event->trigger();
594 return true;
595 } else {
597 if ($checkcapability) {
598 if (!calendar_edit_event_allowed($this->properties)) {
599 throw new \moodle_exception('nopermissiontoupdatecalendar');
603 if ($usingeditor) {
604 if ($this->editorcontext !== null) {
605 $this->properties->description = file_save_draft_area_files(
606 $this->properties->description['itemid'],
607 $this->editorcontext->id,
608 'calendar',
609 'event_description',
610 $this->properties->id,
611 $this->editoroptions,
612 $this->properties->description['text'],
613 $this->editoroptions['forcehttps']);
614 } else {
615 $this->properties->format = $this->properties->description['format'];
616 $this->properties->description = $this->properties->description['text'];
620 $event = $DB->get_record('event', array('id' => $this->properties->id));
622 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
624 if ($updaterepeated) {
626 $sqlset = 'name = ?,
627 description = ?,
628 timeduration = ?,
629 timemodified = ?,
630 groupid = ?,
631 courseid = ?';
633 // Note: Group and course id may not be set. If not, keep their current values.
634 $params = [
635 $this->properties->name,
636 $this->properties->description,
637 $this->properties->timeduration,
638 time(),
639 isset($this->properties->groupid) ? $this->properties->groupid : $event->groupid,
640 isset($this->properties->courseid) ? $this->properties->courseid : $event->courseid,
643 // Note: Only update start date, if it was changed by the user.
644 if ($this->properties->timestart != $event->timestart) {
645 $timestartoffset = $this->properties->timestart - $event->timestart;
646 $sqlset .= ', timestart = timestart + ?';
647 $params[] = $timestartoffset;
650 // Note: Only update location, if it was changed by the user.
651 $updatelocation = (!empty($this->properties->location) && $this->properties->location !== $event->location);
652 if ($updatelocation) {
653 $sqlset .= ', location = ?';
654 $params[] = $this->properties->location;
657 // Update all.
658 $sql = "UPDATE {event}
659 SET $sqlset
660 WHERE repeatid = ?";
662 $params[] = $event->repeatid;
663 $DB->execute($sql, $params);
665 // Trigger an update event for each of the calendar event.
666 $events = $DB->get_records('event', array('repeatid' => $event->repeatid), '', '*');
667 foreach ($events as $calendarevent) {
668 $eventargs['objectid'] = $calendarevent->id;
669 $eventargs['other']['timestart'] = $calendarevent->timestart;
670 $event = \core\event\calendar_event_updated::create($eventargs);
671 $event->add_record_snapshot('event', $calendarevent);
672 $event->trigger();
674 } else {
675 $DB->update_record('event', $this->properties);
676 $event = self::load($this->properties->id);
677 $this->properties = $event->properties();
679 // Trigger an update event.
680 $event = \core\event\calendar_event_updated::create($eventargs);
681 $event->add_record_snapshot('event', $this->properties);
682 $event->trigger();
685 return true;
690 * Deletes an event and if selected an repeated events in the same series
692 * This function deletes an event, any associated events if $deleterepeated=true,
693 * and cleans up any files associated with the events.
695 * @see self::delete()
697 * @param bool $deleterepeated delete event repeatedly
698 * @return bool succession of deleting event
700 public function delete($deleterepeated = false) {
701 global $DB;
703 // If $this->properties->id is not set then something is wrong.
704 if (empty($this->properties->id)) {
705 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
706 return false;
708 $calevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
709 // Delete the event.
710 $DB->delete_records('event', array('id' => $this->properties->id));
712 // Trigger an event for the delete action.
713 $eventargs = array(
714 'context' => $this->get_context(),
715 'objectid' => $this->properties->id,
716 'other' => array(
717 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
718 'timestart' => $this->properties->timestart,
719 'name' => $this->properties->name
721 $event = \core\event\calendar_event_deleted::create($eventargs);
722 $event->add_record_snapshot('event', $calevent);
723 $event->trigger();
725 // If we are deleting parent of a repeated event series, promote the next event in the series as parent.
726 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
727 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC",
728 array($this->properties->id), IGNORE_MULTIPLE);
729 if (!empty($newparent)) {
730 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?",
731 array($newparent, $this->properties->id));
732 // Get all records where the repeatid is the same as the event being removed.
733 $events = $DB->get_records('event', array('repeatid' => $newparent));
734 // For each of the returned events trigger an update event.
735 foreach ($events as $calendarevent) {
736 // Trigger an event for the update.
737 $eventargs['objectid'] = $calendarevent->id;
738 $eventargs['other']['timestart'] = $calendarevent->timestart;
739 $event = \core\event\calendar_event_updated::create($eventargs);
740 $event->add_record_snapshot('event', $calendarevent);
741 $event->trigger();
746 // If the editor context hasn't already been set then set it now.
747 if ($this->editorcontext === null) {
748 $this->editorcontext = $this->get_context();
751 // If the context has been set delete all associated files.
752 if ($this->editorcontext !== null) {
753 $fs = get_file_storage();
754 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
755 foreach ($files as $file) {
756 $file->delete();
760 // If we need to delete repeated events then we will fetch them all and delete one by one.
761 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
762 // Get all records where the repeatid is the same as the event being removed.
763 $events = $DB->get_records('event', array('repeatid' => $this->properties->repeatid));
764 // For each of the returned events populate an event object and call delete.
765 // make sure the arg passed is false as we are already deleting all repeats.
766 foreach ($events as $event) {
767 $event = new calendar_event($event);
768 $event->delete(false);
772 return true;
776 * Fetch all event properties.
778 * This function returns all of the events properties as an object and optionally
779 * can prepare an editor for the description field at the same time. This is
780 * designed to work when the properties are going to be used to set the default
781 * values of a moodle forms form.
783 * @param bool $prepareeditor If set to true a editor is prepared for use with
784 * the mforms editor element. (for description)
785 * @return \stdClass Object containing event properties
787 public function properties($prepareeditor = false) {
788 global $DB;
790 // First take a copy of the properties. We don't want to actually change the
791 // properties or we'd forever be converting back and forwards between an
792 // editor formatted description and not.
793 $properties = clone($this->properties);
794 // Clean the description here.
795 $properties->description = clean_text($properties->description, $properties->format);
797 // If set to true we need to prepare the properties for use with an editor
798 // and prepare the file area.
799 if ($prepareeditor) {
801 // We may or may not have a property id. If we do then we need to work
802 // out the context so we can copy the existing files to the draft area.
803 if (!empty($properties->id)) {
805 if ($properties->eventtype === 'site') {
806 // Site context.
807 $this->editorcontext = $this->get_context();
808 } else if ($properties->eventtype === 'user') {
809 // User context.
810 $this->editorcontext = $this->get_context();
811 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
812 // First check the course is valid.
813 $course = $DB->get_record('course', array('id' => $properties->courseid));
814 if (!$course) {
815 throw new \moodle_exception('invalidcourse');
817 // Course context.
818 $this->editorcontext = $this->get_context();
819 // We have a course and are within the course context so we had
820 // better use the courses max bytes value.
821 $this->editoroptions['maxbytes'] = $course->maxbytes;
822 } else if ($properties->eventtype === 'category') {
823 // First check the course is valid.
824 \core_course_category::get($properties->categoryid, MUST_EXIST, true);
825 // Course context.
826 $this->editorcontext = $this->get_context();
827 } else {
828 // If we get here we have a custom event type as used by some
829 // modules. In this case the event will have been added by
830 // code and we won't need the editor.
831 $this->editoroptions['maxbytes'] = 0;
832 $this->editoroptions['maxfiles'] = 0;
835 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
836 $contextid = false;
837 } else {
838 // Get the context id that is what we really want.
839 $contextid = $this->editorcontext->id;
841 } else {
843 // If we get here then this is a new event in which case we don't need a
844 // context as there is no existing files to copy to the draft area.
845 $contextid = null;
848 // If the contextid === false we don't support files so no preparing
849 // a draft area.
850 if ($contextid !== false) {
851 // Just encase it has already been submitted.
852 $draftiddescription = file_get_submitted_draft_itemid('description');
853 // Prepare the draft area, this copies existing files to the draft area as well.
854 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar',
855 'event_description', $properties->id, $this->editoroptions, $properties->description);
856 } else {
857 $draftiddescription = 0;
860 // Structure the description field as the editor requires.
861 $properties->description = array('text' => $properties->description, 'format' => $properties->format,
862 'itemid' => $draftiddescription);
865 // Finally return the properties.
866 return $properties;
870 * Toggles the visibility of an event
872 * @param null|bool $force If it is left null the events visibility is flipped,
873 * If it is false the event is made hidden, if it is true it
874 * is made visible.
875 * @return bool if event is successfully updated, toggle will be visible
877 public function toggle_visibility($force = null) {
878 global $DB;
880 // Set visible to the default if it is not already set.
881 if (empty($this->properties->visible)) {
882 $this->properties->visible = 1;
885 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
886 // Make this event visible.
887 $this->properties->visible = 1;
888 } else {
889 // Make this event hidden.
890 $this->properties->visible = 0;
893 // Update the database to reflect this change.
894 $success = $DB->set_field('event', 'visible', $this->properties->visible, array('id' => $this->properties->id));
895 $calendarevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
897 // Prepare event data.
898 $eventargs = array(
899 'context' => $this->get_context(),
900 'objectid' => $this->properties->id,
901 'other' => array(
902 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
903 'timestart' => $this->properties->timestart,
904 'name' => $this->properties->name
907 $event = \core\event\calendar_event_updated::create($eventargs);
908 $event->add_record_snapshot('event', $calendarevent);
909 $event->trigger();
911 return $success;
915 * Returns an event object when provided with an event id.
917 * This function makes use of MUST_EXIST, if the event id passed in is invalid
918 * it will result in an exception being thrown.
920 * @param int|object $param event object or event id
921 * @return calendar_event
923 public static function load($param) {
924 global $DB;
925 if (is_object($param)) {
926 $event = new calendar_event($param);
927 } else {
928 $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST);
929 $event = new calendar_event($event);
931 return $event;
935 * Creates a new event and returns an event object.
937 * Capability checking should be performed if the user is directly creating the event
938 * and no other capability has been tested. However if the event is not being created
939 * directly by the user and another capability has been checked for them to do this then
940 * capabilites should not be checked.
942 * For example if a user is creating an event in the calendar the check should be true,
943 * but if you are creating an event in an activity when it is created then the calendar
944 * capabilites should not be checked.
946 * @param \stdClass|array $properties An object containing event properties
947 * @param bool $checkcapability If Moodle should check the user can manage the calendar events for this call or not.
948 * @throws \coding_exception
950 * @return calendar_event|bool The event object or false if it failed
952 public static function create($properties, $checkcapability = true) {
953 if (is_array($properties)) {
954 $properties = (object)$properties;
956 if (!is_object($properties)) {
957 throw new \coding_exception('When creating an event properties should be either an object or an assoc array');
959 $event = new calendar_event($properties);
960 if ($event->update($properties, $checkcapability)) {
961 return $event;
962 } else {
963 return false;
968 * Format the event name using the external API.
970 * This function should we used when text formatting is required in external functions.
972 * @return string Formatted name.
974 public function format_external_name() {
975 if ($this->editorcontext === null) {
976 // Switch on the event type to decide upon the appropriate context to use for this event.
977 $this->editorcontext = $this->get_context();
980 return \core_external\util::format_string($this->properties->name, $this->editorcontext->id);
984 * Format the text using the external API.
986 * This function should we used when text formatting is required in external functions.
988 * @return array an array containing the text formatted and the text format
990 public function format_external_text() {
992 if ($this->editorcontext === null) {
993 // Switch on the event type to decide upon the appropriate context to use for this event.
994 $this->editorcontext = $this->get_context();
996 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
997 // We don't have a context here, do a normal format_text.
998 return \core_external\util::format_text(
999 $this->properties->description,
1000 $this->properties->format,
1001 $this->editorcontext
1006 // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
1007 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
1008 $itemid = $this->properties->repeatid;
1009 } else {
1010 $itemid = $this->properties->id;
1013 return \core_external\util::format_text(
1014 $this->properties->description,
1015 $this->properties->format,
1016 $this->editorcontext,
1017 'calendar',
1018 'event_description',
1019 $itemid
1025 * Calendar information class
1027 * This class is used simply to organise the information pertaining to a calendar
1028 * and is used primarily to make information easily available.
1030 * @package core_calendar
1031 * @category calendar
1032 * @copyright 2010 Sam Hemelryk
1033 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1035 class calendar_information {
1038 * @var int The timestamp
1040 * Rather than setting the day, month and year we will set a timestamp which will be able
1041 * to be used by multiple calendars.
1043 public $time;
1045 /** @var int A course id */
1046 public $courseid = null;
1048 /** @var array An array of categories */
1049 public $categories = array();
1051 /** @var int The current category */
1052 public $categoryid = null;
1054 /** @var array An array of courses */
1055 public $courses = array();
1057 /** @var array An array of groups */
1058 public $groups = array();
1060 /** @var array An array of users */
1061 public $users = array();
1063 /** @var context The anticipated context that the calendar is viewed in */
1064 public $context = null;
1066 /** @var string The calendar's view mode. */
1067 protected $viewmode;
1069 /** @var \stdClass course data. */
1070 public $course;
1072 /** @var int day. */
1073 protected $day;
1075 /** @var int month. */
1076 protected $month;
1078 /** @var int year. */
1079 protected $year;
1082 * Creates a new instance
1084 * @param int $day the number of the day
1085 * @param int $month the number of the month
1086 * @param int $year the number of the year
1087 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
1088 * and $calyear to support multiple calendars
1090 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
1091 // If a day, month and year were passed then convert it to a timestamp. If these were passed
1092 // then we can assume the day, month and year are passed as Gregorian, as no where in core
1093 // should we be passing these values rather than the time. This is done for BC.
1094 if (!empty($day) || !empty($month) || !empty($year)) {
1095 $date = usergetdate(time());
1096 if (empty($day)) {
1097 $day = $date['mday'];
1099 if (empty($month)) {
1100 $month = $date['mon'];
1102 if (empty($year)) {
1103 $year = $date['year'];
1105 if (checkdate($month, $day, $year)) {
1106 $time = make_timestamp($year, $month, $day);
1107 } else {
1108 $time = time();
1112 $this->set_time($time);
1116 * Creates and set up a instance.
1118 * @param int $time the unixtimestamp representing the date we want to view.
1119 * @param int $courseid The ID of the course the user wishes to view.
1120 * @param int $categoryid The ID of the category the user wishes to view
1121 * If a courseid is specified, this value is ignored.
1122 * @return calendar_information
1124 public static function create($time, int $courseid, int $categoryid = null): calendar_information {
1125 $calendar = new static(0, 0, 0, $time);
1126 if ($courseid != SITEID && !empty($courseid)) {
1127 // Course ID must be valid and existing.
1128 $course = get_course($courseid);
1129 $calendar->context = context_course::instance($course->id);
1131 if (!$course->visible && !is_role_switched($course->id)) {
1132 require_capability('moodle/course:viewhiddencourses', $calendar->context);
1135 $courses = [$course->id => $course];
1136 $category = (\core_course_category::get($course->category, MUST_EXIST, true))->get_db_record();
1137 } else if (!empty($categoryid)) {
1138 $course = get_site();
1139 $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1141 // Filter available courses to those within this category or it's children.
1142 $ids = [$categoryid];
1143 $category = \core_course_category::get($categoryid);
1144 $ids = array_merge($ids, array_keys($category->get_children()));
1145 $courses = array_filter($courses, function($course) use ($ids) {
1146 return array_search($course->category, $ids) !== false;
1148 $category = $category->get_db_record();
1150 $calendar->context = context_coursecat::instance($categoryid);
1151 } else {
1152 $course = get_site();
1153 $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1154 $category = null;
1156 $calendar->context = context_system::instance();
1159 $calendar->set_sources($course, $courses, $category);
1161 return $calendar;
1165 * Set the time period of this instance.
1167 * @param int $time the unixtimestamp representing the date we want to view.
1168 * @return $this
1170 public function set_time($time = null) {
1171 if (empty($time)) {
1172 $this->time = time();
1173 } else {
1174 $this->time = $time;
1177 return $this;
1181 * Initialize calendar information
1183 * @deprecated 3.4
1184 * @param stdClass $course object
1185 * @param array $coursestoload An array of courses [$course->id => $course]
1186 * @param bool $ignorefilters options to use filter
1188 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
1189 debugging('The prepare_for_view() function has been deprecated. Please update your code to use set_sources()',
1190 DEBUG_DEVELOPER);
1191 $this->set_sources($course, $coursestoload);
1195 * Set the sources for events within the calendar.
1197 * If no category is provided, then the category path for the current
1198 * course will be used.
1200 * @param stdClass $course The current course being viewed.
1201 * @param stdClass[] $courses The list of all courses currently accessible.
1202 * @param stdClass $category The current category to show.
1204 public function set_sources(stdClass $course, array $courses, stdClass $category = null) {
1205 global $USER;
1207 // A cousre must always be specified.
1208 $this->course = $course;
1209 $this->courseid = $course->id;
1211 list($courseids, $group, $user) = calendar_set_filters($courses);
1212 $this->courses = $courseids;
1213 $this->groups = $group;
1214 $this->users = $user;
1216 // Do not show category events by default.
1217 $this->categoryid = null;
1218 $this->categories = null;
1220 // Determine the correct category information to show.
1221 // When called with a course, the category of that course is usually included too.
1222 // When a category was specifically requested, it should be requested with the site id.
1223 if (SITEID !== $this->courseid) {
1224 // A specific course was requested.
1225 // Fetch the category that this course is in, along with all parents.
1226 // Do not include child categories of this category, as the user many not have enrolments in those siblings or children.
1227 $category = \core_course_category::get($course->category, MUST_EXIST, true);
1228 $this->categoryid = $category->id;
1230 $this->categories = $category->get_parents();
1231 $this->categories[] = $category->id;
1232 } else if (null !== $category && $category->id > 0) {
1233 // A specific category was requested.
1234 // Fetch all parents of this category, along with all children too.
1235 $category = \core_course_category::get($category->id);
1236 $this->categoryid = $category->id;
1238 // Build the category list.
1239 // This includes the current category.
1240 $this->categories = $category->get_parents();
1241 $this->categories[] = $category->id;
1242 $this->categories = array_merge($this->categories, $category->get_all_children_ids());
1243 } else if (SITEID === $this->courseid) {
1244 // The site was requested.
1245 // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
1247 // Grab the list of categories that this user has courses in.
1248 $coursecategories = array_flip(array_map(function($course) {
1249 return $course->category;
1250 }, $courses));
1252 $calcatcache = cache::make('core', 'calendar_categories');
1253 $this->categories = $calcatcache->get('site');
1254 if ($this->categories === false) {
1255 // Use the category id as the key in the following array. That way we do not have to remove duplicates.
1256 $categories = [];
1257 foreach (\core_course_category::get_all() as $category) {
1258 if (isset($coursecategories[$category->id]) ||
1259 has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
1260 // If the user has access to a course in this category or can manage the category,
1261 // then they can see all parent categories too.
1262 $categories[$category->id] = true;
1263 foreach ($category->get_parents() as $catid) {
1264 $categories[$catid] = true;
1268 $this->categories = array_keys($categories);
1269 $calcatcache->set('site', $this->categories);
1275 * Ensures the date for the calendar is correct and either sets it to now
1276 * or throws a moodle_exception if not
1278 * @param bool $defaultonow use current time
1279 * @throws moodle_exception
1280 * @return bool validation of checkdate
1282 public function checkdate($defaultonow = true) {
1283 if (!checkdate($this->month, $this->day, $this->year)) {
1284 if ($defaultonow) {
1285 $now = usergetdate(time());
1286 $this->day = intval($now['mday']);
1287 $this->month = intval($now['mon']);
1288 $this->year = intval($now['year']);
1289 return true;
1290 } else {
1291 throw new moodle_exception('invaliddate');
1294 return true;
1298 * Gets todays timestamp for the calendar
1300 * @return int today timestamp
1302 public function timestamp_today() {
1303 return $this->time;
1306 * Gets tomorrows timestamp for the calendar
1308 * @return int tomorrow timestamp
1310 public function timestamp_tomorrow() {
1311 return strtotime('+1 day', $this->time);
1314 * Adds the pretend blocks for the calendar
1316 * @param core_calendar_renderer $renderer
1317 * @param bool $showfilters display filters, false is set as default
1318 * @param string|null $view preference view options (eg: day, month, upcoming)
1320 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
1321 global $PAGE;
1323 if (!has_capability('moodle/block:view', $PAGE->context) ) {
1324 return;
1327 if ($showfilters) {
1328 $filters = new block_contents();
1329 $filters->content = $renderer->event_filter();
1330 $filters->footer = '';
1331 $filters->title = get_string('eventskey', 'calendar');
1332 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
1337 * Getter method for the calendar's view mode.
1339 * @return string
1341 public function get_viewmode(): string {
1342 return $this->viewmode;
1346 * Setter method for the calendar's view mode.
1348 * @param string $viewmode
1350 public function set_viewmode(string $viewmode): void {
1351 $this->viewmode = $viewmode;
1356 * Get calendar events.
1358 * @param int $tstart Start time of time range for events
1359 * @param int $tend End time of time range for events
1360 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
1361 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
1362 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
1363 * @param boolean $withduration whether only events starting within time range selected
1364 * or events in progress/already started selected as well
1365 * @param boolean $ignorehidden whether to select only visible events or all events
1366 * @param array|int|boolean $categories array of categories, category id or boolean for all/no course events
1367 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
1369 function calendar_get_events($tstart, $tend, $users, $groups, $courses,
1370 $withduration = true, $ignorehidden = true, $categories = []) {
1371 global $DB;
1373 $whereclause = '';
1374 $params = array();
1375 // Quick test.
1376 if (empty($users) && empty($groups) && empty($courses) && empty($categories)) {
1377 return array();
1380 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
1381 // Events from a number of users
1382 if(!empty($whereclause)) $whereclause .= ' OR';
1383 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED);
1384 $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)";
1385 $params = array_merge($params, $inparamsusers);
1386 } else if($users === true) {
1387 // Events from ALL users
1388 if(!empty($whereclause)) $whereclause .= ' OR';
1389 $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)';
1390 } else if($users === false) {
1391 // No user at all, do nothing
1394 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
1395 // Events from a number of groups
1396 if(!empty($whereclause)) $whereclause .= ' OR';
1397 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED);
1398 $whereclause .= " e.groupid $insqlgroups ";
1399 $params = array_merge($params, $inparamsgroups);
1400 } else if($groups === true) {
1401 // Events from ALL groups
1402 if(!empty($whereclause)) $whereclause .= ' OR ';
1403 $whereclause .= ' e.groupid != 0';
1405 // boolean false (no groups at all): we don't need to do anything
1407 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
1408 if(!empty($whereclause)) $whereclause .= ' OR';
1409 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED);
1410 $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
1411 $params = array_merge($params, $inparamscourses);
1412 } else if ($courses === true) {
1413 // Events from ALL courses
1414 if(!empty($whereclause)) $whereclause .= ' OR';
1415 $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
1418 if ((is_array($categories) && !empty($categories)) || is_numeric($categories)) {
1419 if (!empty($whereclause)) {
1420 $whereclause .= ' OR';
1422 list($insqlcategories, $inparamscategories) = $DB->get_in_or_equal($categories, SQL_PARAMS_NAMED);
1423 $whereclause .= " (e.groupid = 0 AND e.courseid = 0 AND e.categoryid $insqlcategories)";
1424 $params = array_merge($params, $inparamscategories);
1425 } else if ($categories === true) {
1426 // Events from ALL categories.
1427 if (!empty($whereclause)) {
1428 $whereclause .= ' OR';
1430 $whereclause .= ' (e.groupid = 0 AND e.courseid = 0 AND e.categoryid != 0)';
1433 // Security check: if, by now, we have NOTHING in $whereclause, then it means
1434 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
1435 // events no matter what. Allowing the code to proceed might return a completely
1436 // valid query with only time constraints, thus selecting ALL events in that time frame!
1437 if(empty($whereclause)) {
1438 return array();
1441 if($withduration) {
1442 $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1444 else {
1445 $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1447 if(!empty($whereclause)) {
1448 // We have additional constraints
1449 $whereclause = $timeclause.' AND ('.$whereclause.')';
1451 else {
1452 // Just basic time filtering
1453 $whereclause = $timeclause;
1456 if ($ignorehidden) {
1457 $whereclause .= ' AND e.visible = 1';
1460 $sql = "SELECT e.*
1461 FROM {event} e
1462 LEFT JOIN {modules} m ON e.modulename = m.name
1463 -- Non visible modules will have a value of 0.
1464 WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
1465 ORDER BY e.timestart";
1466 $events = $DB->get_records_sql($sql, $params);
1468 if ($events === false) {
1469 $events = array();
1471 return $events;
1475 * Return the days of the week.
1477 * @return array array of days
1479 function calendar_get_days() {
1480 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1481 return $calendartype->get_weekdays();
1485 * Get the subscription from a given id.
1487 * @since Moodle 2.5
1488 * @param int $id id of the subscription
1489 * @return stdClass Subscription record from DB
1490 * @throws moodle_exception for an invalid id
1492 function calendar_get_subscription($id) {
1493 global $DB;
1495 $cache = \cache::make('core', 'calendar_subscriptions');
1496 $subscription = $cache->get($id);
1497 if (empty($subscription)) {
1498 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
1499 $cache->set($id, $subscription);
1502 return $subscription;
1506 * Gets the first day of the week.
1508 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
1510 * @return int
1512 function calendar_get_starting_weekday() {
1513 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1514 return $calendartype->get_starting_weekday();
1518 * Get a HTML link to a course.
1520 * @param int|stdClass $course the course id or course object
1521 * @return string a link to the course (as HTML); empty if the course id is invalid
1523 function calendar_get_courselink($course) {
1524 if (!$course) {
1525 return '';
1528 if (!is_object($course)) {
1529 $course = calendar_get_course_cached($coursecache, $course);
1531 $context = \context_course::instance($course->id);
1532 $fullname = format_string($course->fullname, true, array('context' => $context));
1533 $url = new \moodle_url('/course/view.php', array('id' => $course->id));
1534 $link = \html_writer::link($url, $fullname);
1536 return $link;
1540 * Get current module cache.
1542 * Only use this method if you do not know courseid. Otherwise use:
1543 * get_fast_modinfo($courseid)->instances[$modulename][$instance]
1545 * @param array $modulecache in memory module cache
1546 * @param string $modulename name of the module
1547 * @param int $instance module instance number
1548 * @return stdClass|bool $module information
1550 function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
1551 if (!isset($modulecache[$modulename . '_' . $instance])) {
1552 $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
1555 return $modulecache[$modulename . '_' . $instance];
1559 * Get current course cache.
1561 * @param array $coursecache list of course cache
1562 * @param int $courseid id of the course
1563 * @return stdClass $coursecache[$courseid] return the specific course cache
1565 function calendar_get_course_cached(&$coursecache, $courseid) {
1566 if (!isset($coursecache[$courseid])) {
1567 $coursecache[$courseid] = get_course($courseid);
1569 return $coursecache[$courseid];
1573 * Get group from groupid for calendar display
1575 * @param int $groupid
1576 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1578 function calendar_get_group_cached($groupid) {
1579 static $groupscache = array();
1580 if (!isset($groupscache[$groupid])) {
1581 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1583 return $groupscache[$groupid];
1587 * Add calendar event metadata
1589 * @deprecated since 3.9
1591 * @param stdClass $event event info
1592 * @return stdClass $event metadata
1594 function calendar_add_event_metadata($event) {
1595 debugging('This function is no longer used', DEBUG_DEVELOPER);
1596 global $CFG, $OUTPUT;
1598 // Support multilang in event->name.
1599 $event->name = format_string($event->name, true);
1601 if (!empty($event->modulename)) { // Activity event.
1602 // The module name is set. I will assume that it has to be displayed, and
1603 // also that it is an automatically-generated event. And of course that the
1604 // instace id and modulename are set correctly.
1605 $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
1606 if (!array_key_exists($event->instance, $instances)) {
1607 return;
1609 $module = $instances[$event->instance];
1611 $modulename = $module->get_module_type_name(false);
1612 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
1613 // Will be used as alt text if the event icon.
1614 $eventtype = get_string($event->eventtype, $event->modulename);
1615 } else {
1616 $eventtype = '';
1619 $event->icon = '<img src="' . s($module->get_icon_url()) . '" alt="' . s($eventtype) .
1620 '" title="' . s($modulename) . '" class="icon" />';
1621 $event->referer = html_writer::link($module->url, $event->name);
1622 $event->courselink = calendar_get_courselink($module->get_course());
1623 $event->cmid = $module->id;
1624 } else if ($event->courseid == SITEID) { // Site event.
1625 $event->icon = '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
1626 get_string('siteevent', 'calendar') . '" class="icon" />';
1627 $event->cssclass = 'calendar_event_site';
1628 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event.
1629 $event->icon = '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
1630 get_string('courseevent', 'calendar') . '" class="icon" />';
1631 $event->courselink = calendar_get_courselink($event->courseid);
1632 $event->cssclass = 'calendar_event_course';
1633 } else if ($event->groupid) { // Group event.
1634 if ($group = calendar_get_group_cached($event->groupid)) {
1635 $groupname = format_string($group->name, true, \context_course::instance($group->courseid));
1636 } else {
1637 $groupname = '';
1639 $event->icon = \html_writer::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
1640 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
1641 $event->courselink = calendar_get_courselink($event->courseid) . ', ' . $groupname;
1642 $event->cssclass = 'calendar_event_group';
1643 } else if ($event->userid) { // User event.
1644 $event->icon = '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
1645 get_string('userevent', 'calendar') . '" class="icon" />';
1646 $event->cssclass = 'calendar_event_user';
1649 return $event;
1653 * Get calendar events by id.
1655 * @since Moodle 2.5
1656 * @param array $eventids list of event ids
1657 * @return array Array of event entries, empty array if nothing found
1659 function calendar_get_events_by_id($eventids) {
1660 global $DB;
1662 if (!is_array($eventids) || empty($eventids)) {
1663 return array();
1666 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
1667 $wheresql = "id $wheresql";
1669 return $DB->get_records_select('event', $wheresql, $params);
1673 * Get control options for calendar.
1675 * @deprecated since Moodle 4.3
1676 * @param string $type of calendar
1677 * @param array $data calendar information
1678 * @return string $content return available control for the calendar in html
1680 function calendar_top_controls($type, $data) {
1681 debugging(__FUNCTION__ . ' has been deprecated and should not be used anymore.', DEBUG_DEVELOPER);
1683 global $PAGE, $OUTPUT;
1685 // Get the calendar type we are using.
1686 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1688 $content = '';
1690 // Ensure course id passed if relevant.
1691 $courseid = '';
1692 if (!empty($data['id'])) {
1693 $courseid = '&amp;course=' . $data['id'];
1696 // If we are passing a month and year then we need to convert this to a timestamp to
1697 // support multiple calendars. No where in core should these be passed, this logic
1698 // here is for third party plugins that may use this function.
1699 if (!empty($data['m']) && !empty($date['y'])) {
1700 if (!isset($data['d'])) {
1701 $data['d'] = 1;
1703 if (!checkdate($data['m'], $data['d'], $data['y'])) {
1704 $time = time();
1705 } else {
1706 $time = make_timestamp($data['y'], $data['m'], $data['d']);
1708 } else if (!empty($data['time'])) {
1709 $time = $data['time'];
1710 } else {
1711 $time = time();
1714 // Get the date for the calendar type.
1715 $date = $calendartype->timestamp_to_date_array($time);
1717 $urlbase = $PAGE->url;
1719 // We need to get the previous and next months in certain cases.
1720 if ($type == 'frontpage' || $type == 'course' || $type == 'month') {
1721 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1722 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
1723 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
1724 $prevmonthtime['hour'], $prevmonthtime['minute']);
1726 $nextmonth = calendar_add_month($date['mon'], $date['year']);
1727 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
1728 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
1729 $nextmonthtime['hour'], $nextmonthtime['minute']);
1732 switch ($type) {
1733 case 'frontpage':
1734 $prevlink = calendar_get_link_previous(get_string('monthprev', 'calendar'), $urlbase, false, false, false,
1735 true, $prevmonthtime);
1736 $nextlink = calendar_get_link_next(get_string('monthnext', 'calendar'), $urlbase, false, false, false, true,
1737 $nextmonthtime);
1738 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1739 false, false, false, $time);
1741 if (!empty($data['id'])) {
1742 $calendarlink->param('course', $data['id']);
1745 $right = $nextlink;
1747 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1748 $content .= $prevlink . '<span class="hide"> | </span>';
1749 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1750 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1751 ), array('class' => 'current'));
1752 $content .= '<span class="hide"> | </span>' . $right;
1753 $content .= "<span class=\"clearer\"><!-- --></span>\n";
1754 $content .= \html_writer::end_tag('div');
1756 break;
1757 case 'course':
1758 $prevlink = calendar_get_link_previous(get_string('monthprev', 'calendar'), $urlbase, false, false, false,
1759 true, $prevmonthtime);
1760 $nextlink = calendar_get_link_next(get_string('monthnext', 'calendar'), $urlbase, false, false, false,
1761 true, $nextmonthtime);
1762 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1763 false, false, false, $time);
1765 if (!empty($data['id'])) {
1766 $calendarlink->param('course', $data['id']);
1769 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1770 $content .= $prevlink . '<span class="hide"> | </span>';
1771 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1772 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1773 ), array('class' => 'current'));
1774 $content .= '<span class="hide"> | </span>' . $nextlink;
1775 $content .= "<span class=\"clearer\"><!-- --></span>";
1776 $content .= \html_writer::end_tag('div');
1777 break;
1778 case 'upcoming':
1779 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'upcoming')),
1780 false, false, false, $time);
1781 if (!empty($data['id'])) {
1782 $calendarlink->param('course', $data['id']);
1784 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1785 $content .= \html_writer::tag('div', $calendarlink, array('class' => 'centered'));
1786 break;
1787 case 'display':
1788 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1789 false, false, false, $time);
1790 if (!empty($data['id'])) {
1791 $calendarlink->param('course', $data['id']);
1793 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1794 $content .= \html_writer::tag('h3', $calendarlink);
1795 break;
1796 case 'month':
1797 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1798 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $prevmonthtime);
1799 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1800 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $nextmonthtime);
1802 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1803 $content .= $prevlink . '<span class="hide"> | </span>';
1804 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1805 $content .= '<span class="hide"> | </span>' . $nextlink;
1806 $content .= '<span class="clearer"><!-- --></span>';
1807 $content .= \html_writer::end_tag('div')."\n";
1808 break;
1809 case 'day':
1810 $days = calendar_get_days();
1812 $prevtimestamp = strtotime('-1 day', $time);
1813 $nexttimestamp = strtotime('+1 day', $time);
1815 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1816 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1818 $prevname = $days[$prevdate['wday']]['fullname'];
1819 $nextname = $days[$nextdate['wday']]['fullname'];
1820 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&amp;', false, false,
1821 false, false, $prevtimestamp);
1822 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&amp;', false, false, false,
1823 false, $nexttimestamp);
1825 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1826 $content .= $prevlink;
1827 $content .= '<span class="hide"> | </span><span class="current">' .userdate($time,
1828 get_string('strftimedaydate')) . '</span>';
1829 $content .= '<span class="hide"> | </span>' . $nextlink;
1830 $content .= "<span class=\"clearer\"><!-- --></span>";
1831 $content .= \html_writer::end_tag('div') . "\n";
1833 break;
1836 return $content;
1840 * Return the representation day.
1842 * @param int $tstamp Timestamp in GMT
1843 * @param int|bool $now current Unix timestamp
1844 * @param bool $usecommonwords
1845 * @return string the formatted date/time
1847 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1848 static $shortformat;
1850 if (empty($shortformat)) {
1851 $shortformat = get_string('strftimedayshort');
1854 if ($now === false) {
1855 $now = time();
1858 // To have it in one place, if a change is needed.
1859 $formal = userdate($tstamp, $shortformat);
1861 $datestamp = usergetdate($tstamp);
1862 $datenow = usergetdate($now);
1864 if ($usecommonwords == false) {
1865 // We don't want words, just a date.
1866 return $formal;
1867 } else if ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1868 return get_string('today', 'calendar');
1869 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1870 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12
1871 && $datenow['yday'] == 1)) {
1872 return get_string('yesterday', 'calendar');
1873 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1874 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12
1875 && $datestamp['yday'] == 1)) {
1876 return get_string('tomorrow', 'calendar');
1877 } else {
1878 return $formal;
1883 * return the formatted representation time.
1886 * @param int $time the timestamp in UTC, as obtained from the database
1887 * @return string the formatted date/time
1889 function calendar_time_representation($time) {
1890 static $langtimeformat = null;
1892 if ($langtimeformat === null) {
1893 $langtimeformat = get_string('strftimetime');
1896 $timeformat = get_user_preferences('calendar_timeformat');
1897 if (empty($timeformat)) {
1898 $timeformat = get_config(null, 'calendar_site_timeformat');
1901 // Allow language customization of selected time format.
1902 if ($timeformat === CALENDAR_TF_12) {
1903 $timeformat = get_string('strftimetime12', 'langconfig');
1904 } else if ($timeformat === CALENDAR_TF_24) {
1905 $timeformat = get_string('strftimetime24', 'langconfig');
1908 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
1912 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1914 * @param string|moodle_url $linkbase
1915 * @param int $d The number of the day.
1916 * @param int $m The number of the month.
1917 * @param int $y The number of the year.
1918 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1919 * $m and $y are kept for backwards compatibility.
1920 * @return moodle_url|null $linkbase
1922 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1923 if (empty($linkbase)) {
1924 return null;
1927 if (!($linkbase instanceof \moodle_url)) {
1928 $linkbase = new \moodle_url($linkbase);
1931 $linkbase->param('time', calendar_get_timestamp($d, $m, $y, $time));
1933 return $linkbase;
1937 * Build and return a previous month HTML link, with an arrow.
1939 * @deprecated since Moodle 4.3
1940 * @param string $text The text label.
1941 * @param string|moodle_url $linkbase The URL stub.
1942 * @param int $d The number of the date.
1943 * @param int $m The number of the month.
1944 * @param int $y year The number of the year.
1945 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1946 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1947 * $m and $y are kept for backwards compatibility.
1948 * @return string HTML string.
1950 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1951 debugging(__FUNCTION__ . ' has been deprecated and should not be used anymore.', DEBUG_DEVELOPER);
1953 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1955 if (empty($href)) {
1956 return $text;
1959 $attrs = [
1960 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1961 'data-drop-zone' => 'nav-link',
1964 return link_arrow_left($text, $href->out(false), $accesshide, 'previous', $attrs);
1968 * Build and return a next month HTML link, with an arrow.
1970 * @deprecated since Moodle 4.3
1971 * @param string $text The text label.
1972 * @param string|moodle_url $linkbase The URL stub.
1973 * @param int $d the number of the Day
1974 * @param int $m The number of the month.
1975 * @param int $y The number of the year.
1976 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1977 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1978 * $m and $y are kept for backwards compatibility.
1979 * @return string HTML string.
1981 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1982 debugging(__FUNCTION__ . ' has been deprecated and should not be used anymore.', DEBUG_DEVELOPER);
1984 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1986 if (empty($href)) {
1987 return $text;
1990 $attrs = [
1991 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1992 'data-drop-zone' => 'nav-link',
1995 return link_arrow_right($text, $href->out(false), $accesshide, 'next', $attrs);
1999 * Return the number of days in month.
2001 * @param int $month the number of the month.
2002 * @param int $year the number of the year
2003 * @return int
2005 function calendar_days_in_month($month, $year) {
2006 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2007 return $calendartype->get_num_days_in_month($year, $month);
2011 * Get the next following month.
2013 * @param int $month the number of the month.
2014 * @param int $year the number of the year.
2015 * @return array the following month
2017 function calendar_add_month($month, $year) {
2018 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2019 return $calendartype->get_next_month($year, $month);
2023 * Get the previous month.
2025 * @param int $month the number of the month.
2026 * @param int $year the number of the year.
2027 * @return array previous month
2029 function calendar_sub_month($month, $year) {
2030 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2031 return $calendartype->get_prev_month($year, $month);
2035 * Get per-day basis events
2037 * @param array $events list of events
2038 * @param int $month the number of the month
2039 * @param int $year the number of the year
2040 * @param array $eventsbyday event on specific day
2041 * @param array $durationbyday duration of the event in days
2042 * @param array $typesbyday event type (eg: site, course, user, or group)
2043 * @param array $courses list of courses
2044 * @return void
2046 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
2047 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2049 $eventsbyday = array();
2050 $typesbyday = array();
2051 $durationbyday = array();
2053 if ($events === false) {
2054 return;
2057 foreach ($events as $event) {
2058 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
2059 if ($event->timeduration) {
2060 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
2061 } else {
2062 $enddate = $startdate;
2065 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair.
2066 if (!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) &&
2067 ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
2068 continue;
2071 $eventdaystart = intval($startdate['mday']);
2073 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2074 // Give the event to its day.
2075 $eventsbyday[$eventdaystart][] = $event->id;
2077 // Mark the day as having such an event.
2078 if ($event->courseid == SITEID && $event->groupid == 0) {
2079 $typesbyday[$eventdaystart]['startsite'] = true;
2080 // Set event class for site event.
2081 $events[$event->id]->class = 'calendar_event_site';
2082 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
2083 $typesbyday[$eventdaystart]['startcourse'] = true;
2084 // Set event class for course event.
2085 $events[$event->id]->class = 'calendar_event_course';
2086 } else if ($event->groupid) {
2087 $typesbyday[$eventdaystart]['startgroup'] = true;
2088 // Set event class for group event.
2089 $events[$event->id]->class = 'calendar_event_group';
2090 } else if ($event->userid) {
2091 $typesbyday[$eventdaystart]['startuser'] = true;
2092 // Set event class for user event.
2093 $events[$event->id]->class = 'calendar_event_user';
2097 if ($event->timeduration == 0) {
2098 // Proceed with the next.
2099 continue;
2102 // The event starts on $month $year or before.
2103 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2104 $lowerbound = intval($startdate['mday']);
2105 } else {
2106 $lowerbound = 0;
2109 // Also, it ends on $month $year or later.
2110 if ($enddate['mon'] == $month && $enddate['year'] == $year) {
2111 $upperbound = intval($enddate['mday']);
2112 } else {
2113 $upperbound = calendar_days_in_month($month, $year);
2116 // Mark all days between $lowerbound and $upperbound (inclusive) as duration.
2117 for ($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
2118 $durationbyday[$i][] = $event->id;
2119 if ($event->courseid == SITEID && $event->groupid == 0) {
2120 $typesbyday[$i]['durationsite'] = true;
2121 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
2122 $typesbyday[$i]['durationcourse'] = true;
2123 } else if ($event->groupid) {
2124 $typesbyday[$i]['durationgroup'] = true;
2125 } else if ($event->userid) {
2126 $typesbyday[$i]['durationuser'] = true;
2131 return;
2135 * Returns the courses to load events for.
2137 * @param array $courseeventsfrom An array of courses to load calendar events for
2138 * @param bool $ignorefilters specify the use of filters, false is set as default
2139 * @param stdClass $user The user object. This defaults to the global $USER object.
2140 * @return array An array of courses, groups, and user to load calendar events for based upon filters
2142 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false, stdClass $user = null) {
2143 global $CFG, $USER;
2145 if (is_null($user)) {
2146 $user = $USER;
2149 $courses = array();
2150 $userid = false;
2151 $group = false;
2153 // Get the capabilities that allow seeing group events from all groups.
2154 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
2156 $isvaliduser = !empty($user->id);
2158 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE, $user)) {
2159 $courses = array_keys($courseeventsfrom);
2161 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_SITE, $user)) {
2162 $courses[] = SITEID;
2164 $courses = array_unique($courses);
2165 sort($courses);
2167 if (!empty($courses) && in_array(SITEID, $courses)) {
2168 // Sort courses for consistent colour highlighting.
2169 // Effectively ignoring SITEID as setting as last course id.
2170 $key = array_search(SITEID, $courses);
2171 unset($courses[$key]);
2172 $courses[] = SITEID;
2175 if ($ignorefilters || ($isvaliduser && calendar_show_event_type(CALENDAR_EVENT_USER, $user))) {
2176 $userid = $user->id;
2179 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP, $user) || $ignorefilters)) {
2181 if (count($courseeventsfrom) == 1) {
2182 $course = reset($courseeventsfrom);
2183 if (has_any_capability($allgroupscaps, \context_course::instance($course->id))) {
2184 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
2185 $group = array_keys($coursegroups);
2188 if ($group === false) {
2189 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, \context_system::instance())) {
2190 $group = true;
2191 } else if ($isvaliduser) {
2192 $groupids = array();
2193 foreach ($courseeventsfrom as $courseid => $course) {
2194 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2195 // If this course has groups, show events from all of those related to the current user.
2196 $coursegroups = groups_get_user_groups($course->id, $user->id);
2197 $groupids = array_merge($groupids, $coursegroups['0']);
2200 if (!empty($groupids)) {
2201 $group = $groupids;
2206 if (empty($courses)) {
2207 $courses = false;
2210 return array($courses, $group, $userid);
2214 * Can current user manage a non user event in system context.
2216 * @param calendar_event|stdClass $event event object
2217 * @return boolean
2219 function calendar_can_manage_non_user_event_in_system($event) {
2220 $sitecontext = \context_system::instance();
2221 $isuserevent = $event->eventtype == 'user';
2222 $canmanageentries = has_capability('moodle/calendar:manageentries', $sitecontext);
2223 // If user has manageentries at site level and it's not user event, return true.
2224 if ($canmanageentries && !$isuserevent) {
2225 return true;
2228 return false;
2232 * Return the capability for viewing a calendar event.
2234 * @param calendar_event $event event object
2235 * @return boolean
2237 function calendar_view_event_allowed(calendar_event $event) {
2238 global $USER;
2240 // Anyone can see site events.
2241 if ($event->courseid && $event->courseid == SITEID) {
2242 return true;
2245 if (calendar_can_manage_non_user_event_in_system($event)) {
2246 return true;
2249 if (!empty($event->groupid)) {
2250 // If it is a group event we need to be able to manage events in the course, or be in the group.
2251 if (has_capability('moodle/calendar:manageentries', $event->context) ||
2252 has_capability('moodle/calendar:managegroupentries', $event->context)) {
2253 return true;
2256 $mycourses = enrol_get_my_courses('id');
2257 return isset($mycourses[$event->courseid]) && groups_is_member($event->groupid);
2258 } else if ($event->modulename) {
2259 // If this is a module event we need to be able to see the module.
2260 $coursemodules = [];
2261 $courseid = 0;
2262 // Override events do not have the courseid set.
2263 if ($event->courseid) {
2264 $courseid = $event->courseid;
2265 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2266 } else {
2267 $cmraw = get_coursemodule_from_instance($event->modulename, $event->instance, 0, false, MUST_EXIST);
2268 $courseid = $cmraw->course;
2269 $coursemodules = get_fast_modinfo($cmraw->course)->instances;
2271 $hasmodule = isset($coursemodules[$event->modulename]);
2272 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2274 // If modinfo doesn't know about the module, return false to be safe.
2275 if (!$hasmodule || !$hasinstance) {
2276 return false;
2279 // Must be able to see the course and the module - MDL-59304.
2280 $cm = $coursemodules[$event->modulename][$event->instance];
2281 if (!$cm->uservisible) {
2282 return false;
2284 $mycourses = enrol_get_my_courses('id');
2285 return isset($mycourses[$courseid]);
2286 } else if ($event->categoryid) {
2287 // If this is a category we need to be able to see the category.
2288 $cat = \core_course_category::get($event->categoryid, IGNORE_MISSING);
2289 if (!$cat) {
2290 return false;
2292 return true;
2293 } else if (!empty($event->courseid)) {
2294 // If it is a course event we need to be able to manage events in the course, or be in the course.
2295 if (has_capability('moodle/calendar:manageentries', $event->context)) {
2296 return true;
2299 return can_access_course(get_course($event->courseid));
2300 } else if ($event->userid) {
2301 return calendar_can_manage_user_event($event);
2302 } else {
2303 throw new moodle_exception('unknown event type');
2306 return false;
2310 * Return the capability for editing calendar event.
2312 * @param calendar_event $event event object
2313 * @param bool $manualedit is the event being edited manually by the user
2314 * @return bool capability to edit event
2316 function calendar_edit_event_allowed($event, $manualedit = false) {
2317 global $USER, $DB;
2319 // Must be logged in.
2320 if (!isloggedin()) {
2321 return false;
2324 // Can not be using guest account.
2325 if (isguestuser()) {
2326 return false;
2329 if ($manualedit && !empty($event->modulename)) {
2330 $hascallback = component_callback_exists(
2331 'mod_' . $event->modulename,
2332 'core_calendar_event_timestart_updated'
2335 if (!$hascallback) {
2336 // If the activity hasn't implemented the correct callback
2337 // to handle changes to it's events then don't allow any
2338 // manual changes to them.
2339 return false;
2342 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2343 $hasmodule = isset($coursemodules[$event->modulename]);
2344 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2346 // If modinfo doesn't know about the module, return false to be safe.
2347 if (!$hasmodule || !$hasinstance) {
2348 return false;
2351 $coursemodule = $coursemodules[$event->modulename][$event->instance];
2352 $context = context_module::instance($coursemodule->id);
2353 // This is the capability that allows a user to modify the activity
2354 // settings. Since the activity generated this event we need to check
2355 // that the current user has the same capability before allowing them
2356 // to update the event because the changes to the event will be
2357 // reflected within the activity.
2358 return has_capability('moodle/course:manageactivities', $context);
2361 if ($manualedit && !empty($event->component)) {
2362 // TODO possibly we can later add a callback similar to core_calendar_event_timestart_updated in the modules.
2363 return false;
2366 // You cannot edit URL based calendar subscription events presently.
2367 if (!empty($event->subscriptionid)) {
2368 if (!empty($event->subscription->url)) {
2369 // This event can be updated externally, so it cannot be edited.
2370 return false;
2374 if (calendar_can_manage_non_user_event_in_system($event)) {
2375 return true;
2378 // If groupid is set, it's definitely a group event.
2379 if (!empty($event->groupid)) {
2380 // Allow users to add/edit group events if -
2381 // 1) They have manageentries for the course OR
2382 // 2) They have managegroupentries AND are in the group.
2383 $group = $DB->get_record('groups', array('id' => $event->groupid));
2384 return $group && (
2385 has_capability('moodle/calendar:manageentries', $event->context) ||
2386 (has_capability('moodle/calendar:managegroupentries', $event->context)
2387 && groups_is_member($event->groupid)));
2388 } else if (!empty($event->courseid)) {
2389 // If groupid is not set, but course is set, it's definitely a course event.
2390 return has_capability('moodle/calendar:manageentries', $event->context);
2391 } else if (!empty($event->categoryid)) {
2392 // If groupid is not set, but category is set, it's definitely a category event.
2393 return has_capability('moodle/calendar:manageentries', $event->context);
2394 } else if (!empty($event->userid) && $event->userid == $USER->id) {
2395 // If course is not set, but userid id set, it's a user event.
2396 return (has_capability('moodle/calendar:manageownentries',
2397 context_user::instance($event->userid)));
2398 } else if (!empty($event->userid)) {
2399 return calendar_can_manage_user_event($event);
2402 return false;
2406 * Can current user edit/delete/add an user event?
2408 * @param calendar_event|stdClass $event event object
2409 * @return bool
2411 function calendar_can_manage_user_event($event): bool {
2412 global $USER;
2414 if (!($event instanceof \calendar_event)) {
2415 $event = new \calendar_event(clone($event));
2418 $canmanage = has_capability('moodle/calendar:manageentries', $event->context);
2419 $canmanageown = has_capability('moodle/calendar:manageownentries', $event->context);
2420 $ismyevent = $event->userid == $USER->id;
2421 $isadminevent = is_siteadmin($event->userid);
2423 if ($canmanageown && $ismyevent) {
2424 return true;
2427 // In site context, user must have login and calendar:manageentries permissions
2428 // ... to manage other user's events except admin users.
2429 if ($canmanage && !$isadminevent) {
2430 return true;
2433 return false;
2437 * Return the capability for deleting a calendar event.
2439 * @param calendar_event $event The event object
2440 * @return bool Whether the user has permission to delete the event or not.
2442 function calendar_delete_event_allowed($event) {
2443 // Only allow delete if you have capabilities and it is not an module or component event.
2444 return (calendar_edit_event_allowed($event) && empty($event->modulename) && empty($event->component));
2448 * Returns the default courses to display on the calendar when there isn't a specific
2449 * course to display.
2451 * @param int $courseid (optional) If passed, an additional course can be returned for admins (the current course).
2452 * @param string $fields Comma separated list of course fields to return.
2453 * @param bool $canmanage If true, this will return the list of courses the user can create events in, rather
2454 * than the list of courses they see events from (an admin can always add events in a course
2455 * calendar, even if they are not enrolled in the course).
2456 * @param int $userid (optional) The user which this function returns the default courses for.
2457 * By default the current user.
2458 * @return array $courses Array of courses to display
2460 function calendar_get_default_courses($courseid = null, $fields = '*', $canmanage = false, int $userid = null) {
2461 global $CFG, $USER;
2463 if (!$userid) {
2464 if (!isloggedin()) {
2465 return array();
2467 $userid = $USER->id;
2470 if ((!empty($CFG->calendar_adminseesall) || $canmanage) &&
2471 has_capability('moodle/calendar:manageentries', context_system::instance(), $userid)) {
2473 // Add a c. prefix to every field as expected by get_courses function.
2474 $fieldlist = explode(',', $fields);
2476 $prefixedfields = array_map(function($value) {
2477 return 'c.' . trim(strtolower($value));
2478 }, $fieldlist);
2480 $courses = get_courses('all', 'c.shortname', implode(',', $prefixedfields));
2481 } else {
2482 $courses = enrol_get_users_courses($userid, true, $fields, 'c.shortname');
2485 if ($courseid && $courseid != SITEID) {
2486 if (empty($courses[$courseid]) && has_capability('moodle/calendar:manageentries', context_system::instance(), $userid)) {
2487 // Allow a site admin to see calendars from courses he is not enrolled in.
2488 // This will come from $COURSE.
2489 $courses[$courseid] = get_course($courseid);
2493 return $courses;
2497 * Get event format time.
2499 * @param calendar_event $event event object
2500 * @param int $now current time in gmt
2501 * @param array $linkparams list of params for event link
2502 * @param bool $usecommonwords the words as formatted date/time.
2503 * @param int $showtime determine the show time GMT timestamp
2504 * @return string $eventtime link/string for event time
2506 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
2507 $starttime = $event->timestart;
2508 $endtime = $event->timestart + $event->timeduration;
2510 if (empty($linkparams) || !is_array($linkparams)) {
2511 $linkparams = array();
2514 $linkparams['view'] = 'day';
2516 // OK, now to get a meaningful display.
2517 // Check if there is a duration for this event.
2518 if ($event->timeduration) {
2519 // Get the midnight of the day the event will start.
2520 $usermidnightstart = usergetmidnight($starttime);
2521 // Get the midnight of the day the event will end.
2522 $usermidnightend = usergetmidnight($endtime);
2523 // Check if we will still be on the same day.
2524 if ($usermidnightstart == $usermidnightend) {
2525 // Check if we are running all day.
2526 if ($event->timeduration == DAYSECS) {
2527 $time = get_string('allday', 'calendar');
2528 } else { // Specify the time we will be running this from.
2529 $datestart = calendar_time_representation($starttime);
2530 $dateend = calendar_time_representation($endtime);
2531 $time = $datestart . ' <strong>&raquo;</strong> ' . $dateend;
2534 // Set printable representation.
2535 if (!$showtime) {
2536 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2537 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2538 $eventtime = \html_writer::link($url, $day) . ', ' . $time;
2539 } else {
2540 $eventtime = $time;
2542 } else { // It must spans two or more days.
2543 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
2544 if ($showtime == $usermidnightstart) {
2545 $daystart = '';
2547 $timestart = calendar_time_representation($event->timestart);
2548 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
2549 if ($showtime == $usermidnightend) {
2550 $dayend = '';
2552 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
2554 // Set printable representation.
2555 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2556 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2557 $eventtime = $timestart . ' <strong>&raquo;</strong> ' . \html_writer::link($url, $dayend) . $timeend;
2558 } else {
2559 // The event is in the future, print start and end links.
2560 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2561 $eventtime = \html_writer::link($url, $daystart) . $timestart . ' <strong>&raquo;</strong> ';
2563 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2564 $eventtime .= \html_writer::link($url, $dayend) . $timeend;
2567 } else { // There is no time duration.
2568 $time = calendar_time_representation($event->timestart);
2569 // Set printable representation.
2570 if (!$showtime) {
2571 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2572 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2573 $eventtime = \html_writer::link($url, $day) . ', ' . trim($time);
2574 } else {
2575 $eventtime = $time;
2579 // Check if It has expired.
2580 if ($event->timestart + $event->timeduration < $now) {
2581 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2584 return $eventtime;
2588 * Format event location property
2590 * @param calendar_event $event
2591 * @return string
2593 function calendar_format_event_location(calendar_event $event): string {
2594 $location = format_text($event->location, FORMAT_PLAIN, ['context' => $event->context]);
2596 // If it looks like a link, convert it to one.
2597 if (preg_match('/^https?:\/\//i', $location) && clean_param($location, PARAM_URL)) {
2598 $location = \html_writer::link($location, $location, [
2599 'title' => get_string('eventnamelocation', 'core_calendar', ['name' => $event->name, 'location' => $location]),
2603 return $location;
2607 * Checks to see if the requested type of event should be shown for the given user.
2609 * @param int $type The type to check the display for (default is to display all)
2610 * @param stdClass|int|null $user The user to check for - by default the current user
2611 * @return bool True if the tyep should be displayed false otherwise
2613 function calendar_show_event_type($type, $user = null) {
2614 $default = CALENDAR_EVENT_SITE + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
2616 if ((int)get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2617 global $SESSION;
2618 if (!isset($SESSION->calendarshoweventtype)) {
2619 $SESSION->calendarshoweventtype = $default;
2621 return $SESSION->calendarshoweventtype & $type;
2622 } else {
2623 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2628 * Sets the display of the event type given $display.
2630 * If $display = true the event type will be shown.
2631 * If $display = false the event type will NOT be shown.
2632 * If $display = null the current value will be toggled and saved.
2634 * @param int $type object of CALENDAR_EVENT_XXX
2635 * @param bool $display option to display event type
2636 * @param stdClass|int $user moodle user object or id, null means current user
2638 function calendar_set_event_type_display($type, $display = null, $user = null) {
2639 $persist = (int)get_user_preferences('calendar_persistflt', 0, $user);
2640 $default = CALENDAR_EVENT_SITE + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP
2641 + CALENDAR_EVENT_USER + CALENDAR_EVENT_COURSECAT;
2642 if ($persist === 0) {
2643 global $SESSION;
2644 if (!isset($SESSION->calendarshoweventtype)) {
2645 $SESSION->calendarshoweventtype = $default;
2647 $preference = $SESSION->calendarshoweventtype;
2648 } else {
2649 $preference = get_user_preferences('calendar_savedflt', $default, $user);
2651 $current = $preference & $type;
2652 if ($display === null) {
2653 $display = !$current;
2655 if ($display && !$current) {
2656 $preference += $type;
2657 } else if (!$display && $current) {
2658 $preference -= $type;
2660 if ($persist === 0) {
2661 $SESSION->calendarshoweventtype = $preference;
2662 } else {
2663 if ($preference == $default) {
2664 unset_user_preference('calendar_savedflt', $user);
2665 } else {
2666 set_user_preference('calendar_savedflt', $preference, $user);
2672 * Get calendar's allowed types.
2674 * @param stdClass $allowed list of allowed edit for event type
2675 * @param stdClass|int $course object of a course or course id
2676 * @param array $groups array of groups for the given course
2677 * @param stdClass|int $category object of a category
2679 function calendar_get_allowed_types(&$allowed, $course = null, $groups = null, $category = null) {
2680 global $USER, $DB;
2682 $allowed = new \stdClass();
2683 $allowed->user = has_capability('moodle/calendar:manageownentries', \context_system::instance());
2684 $allowed->groups = false;
2685 $allowed->courses = false;
2686 $allowed->categories = false;
2687 $allowed->site = has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID));
2688 $getgroupsfunc = function($course, $context, $user) use ($groups) {
2689 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2690 if (has_capability('moodle/site:accessallgroups', $context)) {
2691 return is_null($groups) ? groups_get_all_groups($course->id) : $groups;
2692 } else {
2693 if (is_null($groups)) {
2694 return groups_get_all_groups($course->id, $user->id);
2695 } else {
2696 return array_filter($groups, function($group) use ($user) {
2697 return isset($group->members[$user->id]);
2703 return false;
2706 if (!empty($course)) {
2707 if (!is_object($course)) {
2708 $course = $DB->get_record('course', array('id' => $course), 'id, groupmode, groupmodeforce', MUST_EXIST);
2710 if ($course->id != SITEID) {
2711 $coursecontext = \context_course::instance($course->id);
2712 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
2714 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2715 $allowed->courses = array($course->id => 1);
2716 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2717 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
2718 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2723 if (!empty($category)) {
2724 $catcontext = \context_coursecat::instance($category->id);
2725 if (has_capability('moodle/category:manage', $catcontext)) {
2726 $allowed->categories = [$category->id => 1];
2732 * See if user can add calendar entries at all used to print the "New Event" button.
2734 * @param stdClass $course object of a course or course id
2735 * @return bool has the capability to add at least one event type
2737 function calendar_user_can_add_event($course) {
2738 if (!isloggedin() || isguestuser()) {
2739 return false;
2742 calendar_get_allowed_types($allowed, $course);
2744 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->categories || $allowed->site);
2748 * Check wether the current user is permitted to add events.
2750 * @param stdClass $event object of event
2751 * @return bool has the capability to add event
2753 function calendar_add_event_allowed($event) {
2754 global $USER, $DB;
2756 // Can not be using guest account.
2757 if (!isloggedin() or isguestuser()) {
2758 return false;
2761 if (calendar_can_manage_non_user_event_in_system($event)) {
2762 return true;
2765 switch ($event->eventtype) {
2766 case 'category':
2767 return has_capability('moodle/category:manage', $event->context);
2768 case 'course':
2769 return has_capability('moodle/calendar:manageentries', $event->context);
2770 case 'group':
2771 // Allow users to add/edit group events if -
2772 // 1) They have manageentries (= entries for whole course).
2773 // 2) They have managegroupentries AND are in the group.
2774 $group = $DB->get_record('groups', array('id' => $event->groupid));
2775 return $group && (
2776 has_capability('moodle/calendar:manageentries', $event->context) ||
2777 (has_capability('moodle/calendar:managegroupentries', $event->context)
2778 && groups_is_member($event->groupid)));
2779 case 'user':
2780 return calendar_can_manage_user_event($event);
2781 case 'site':
2782 return has_capability('moodle/calendar:manageentries', $event->context);
2783 default:
2784 return has_capability('moodle/calendar:manageentries', $event->context);
2789 * Returns option list for the poll interval setting.
2791 * @return array An array of poll interval options. Interval => description.
2793 function calendar_get_pollinterval_choices() {
2794 return array(
2795 '0' => get_string('never', 'calendar'),
2796 HOURSECS => get_string('hourly', 'calendar'),
2797 DAYSECS => get_string('daily', 'calendar'),
2798 WEEKSECS => get_string('weekly', 'calendar'),
2799 '2628000' => get_string('monthly', 'calendar'),
2800 YEARSECS => get_string('annually', 'calendar')
2805 * Returns option list of available options for the calendar event type, given the current user and course.
2807 * @param int $courseid The id of the course
2808 * @return array An array containing the event types the user can create.
2810 function calendar_get_eventtype_choices($courseid) {
2811 $choices = array();
2812 $allowed = new \stdClass;
2813 calendar_get_allowed_types($allowed, $courseid);
2815 if ($allowed->user) {
2816 $choices['user'] = get_string('userevents', 'calendar');
2818 if ($allowed->site) {
2819 $choices['site'] = get_string('siteevents', 'calendar');
2821 if (!empty($allowed->courses)) {
2822 $choices['course'] = get_string('courseevents', 'calendar');
2824 if (!empty($allowed->categories)) {
2825 $choices['category'] = get_string('categoryevents', 'calendar');
2827 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2828 $choices['group'] = get_string('group');
2831 return array($choices, $allowed->groups);
2835 * Add an iCalendar subscription to the database.
2837 * @param stdClass $sub The subscription object (e.g. from the form)
2838 * @return int The insert ID, if any.
2840 function calendar_add_subscription($sub) {
2841 global $DB, $USER, $SITE;
2843 // Undo the form definition work around to allow us to have two different
2844 // course selectors present depending on which event type the user selects.
2845 if (!empty($sub->groupcourseid)) {
2846 $sub->courseid = $sub->groupcourseid;
2847 unset($sub->groupcourseid);
2850 // Default course id if none is set.
2851 if (empty($sub->courseid)) {
2852 if ($sub->eventtype === 'site') {
2853 $sub->courseid = SITEID;
2854 } else {
2855 $sub->courseid = 0;
2859 if ($sub->eventtype === 'site') {
2860 $sub->courseid = $SITE->id;
2861 } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
2862 $sub->courseid = $sub->courseid;
2863 } else if ($sub->eventtype === 'category') {
2864 $sub->categoryid = $sub->categoryid;
2865 } else {
2866 // User events.
2867 $sub->courseid = 0;
2869 $sub->userid = $USER->id;
2871 // File subscriptions never update.
2872 if (empty($sub->url)) {
2873 $sub->pollinterval = 0;
2876 if (!empty($sub->name)) {
2877 if (empty($sub->id)) {
2878 $id = $DB->insert_record('event_subscriptions', $sub);
2879 // We cannot cache the data here because $sub is not complete.
2880 $sub->id = $id;
2881 // Trigger event, calendar subscription added.
2882 $eventparams = array('objectid' => $sub->id,
2883 'context' => calendar_get_calendar_context($sub),
2884 'other' => array(
2885 'eventtype' => $sub->eventtype,
2888 switch ($sub->eventtype) {
2889 case 'category':
2890 $eventparams['other']['categoryid'] = $sub->categoryid;
2891 break;
2892 case 'course':
2893 $eventparams['other']['courseid'] = $sub->courseid;
2894 break;
2895 case 'group':
2896 $eventparams['other']['courseid'] = $sub->courseid;
2897 $eventparams['other']['groupid'] = $sub->groupid;
2898 break;
2899 default:
2900 $eventparams['other']['courseid'] = $sub->courseid;
2903 $event = \core\event\calendar_subscription_created::create($eventparams);
2904 $event->trigger();
2905 return $id;
2906 } else {
2907 // Why are we doing an update here?
2908 calendar_update_subscription($sub);
2909 return $sub->id;
2911 } else {
2912 throw new \moodle_exception('errorbadsubscription', 'importcalendar');
2917 * Add an iCalendar event to the Moodle calendar.
2919 * @param stdClass $event The RFC-2445 iCalendar event
2920 * @param int $unused Deprecated
2921 * @param int $subscriptionid The iCalendar subscription ID
2922 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2923 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2924 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2926 function calendar_add_icalendar_event($event, $unused, $subscriptionid, $timezone='UTC') {
2927 global $DB;
2929 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2930 if (empty($event->properties['SUMMARY'])) {
2931 return 0;
2934 $name = $event->properties['SUMMARY'][0]->value;
2935 $name = str_replace('\n', '<br />', $name);
2936 $name = str_replace('\\', '', $name);
2937 $name = preg_replace('/\s+/u', ' ', $name);
2939 $eventrecord = new \stdClass;
2940 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
2942 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2943 $description = '';
2944 } else {
2945 $description = $event->properties['DESCRIPTION'][0]->value;
2946 $description = clean_param($description, PARAM_NOTAGS);
2947 $description = str_replace('\n', '<br />', $description);
2948 $description = str_replace('\\', '', $description);
2949 $description = preg_replace('/\s+/u', ' ', $description);
2951 $eventrecord->description = $description;
2953 // Probably a repeating event with RRULE etc. TODO: skip for now.
2954 if (empty($event->properties['DTSTART'][0]->value)) {
2955 return 0;
2958 if (isset($event->properties['DTSTART'][0]->parameters['TZID'])) {
2959 $tz = $event->properties['DTSTART'][0]->parameters['TZID'];
2960 } else {
2961 $tz = $timezone;
2963 $tz = \core_date::normalise_timezone($tz);
2964 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value . ' ' . $tz);
2965 if (empty($event->properties['DTEND'])) {
2966 $eventrecord->timeduration = 0; // No duration if no end time specified.
2967 } else {
2968 if (isset($event->properties['DTEND'][0]->parameters['TZID'])) {
2969 $endtz = $event->properties['DTEND'][0]->parameters['TZID'];
2970 } else {
2971 $endtz = $timezone;
2973 $endtz = \core_date::normalise_timezone($endtz);
2974 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value . ' ' . $endtz) - $eventrecord->timestart;
2977 // Check to see if it should be treated as an all day event.
2978 if ($eventrecord->timeduration == DAYSECS) {
2979 // Check to see if the event started at Midnight on the imported calendar.
2980 date_default_timezone_set($timezone);
2981 if (date('H:i:s', $eventrecord->timestart) === "00:00:00") {
2982 // This event should be an all day event. This is not correct, we don't do anything differently for all day events.
2983 // See MDL-56227.
2984 $eventrecord->timeduration = 0;
2986 \core_date::set_default_server_timezone();
2989 $eventrecord->location = empty($event->properties['LOCATION'][0]->value) ? '' :
2990 trim(str_replace('\\', '', $event->properties['LOCATION'][0]->value));
2991 $eventrecord->uuid = $event->properties['UID'][0]->value;
2992 $eventrecord->timemodified = time();
2994 // Add the iCal subscription details if required.
2995 // We should never do anything with an event without a subscription reference.
2996 $sub = calendar_get_subscription($subscriptionid);
2997 $eventrecord->subscriptionid = $subscriptionid;
2998 $eventrecord->userid = $sub->userid;
2999 $eventrecord->groupid = $sub->groupid;
3000 $eventrecord->courseid = $sub->courseid;
3001 $eventrecord->categoryid = $sub->categoryid;
3002 $eventrecord->eventtype = $sub->eventtype;
3004 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid,
3005 'subscriptionid' => $eventrecord->subscriptionid))) {
3007 // Compare iCal event data against the moodle event to see if something has changed.
3008 $result = array_diff((array) $eventrecord, (array) $updaterecord);
3010 // Unset timemodified field because it's always going to be different.
3011 unset($result['timemodified']);
3013 if (count($result)) {
3014 $eventrecord->id = $updaterecord->id;
3015 $return = CALENDAR_IMPORT_EVENT_UPDATED; // Update.
3016 } else {
3017 return CALENDAR_IMPORT_EVENT_SKIPPED;
3019 } else {
3020 $return = CALENDAR_IMPORT_EVENT_INSERTED; // Insert.
3023 if ($createdevent = \calendar_event::create($eventrecord, false)) {
3024 if (!empty($event->properties['RRULE'])) {
3025 // Repeating events.
3026 date_default_timezone_set($tz); // Change time zone to parse all events.
3027 $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
3028 $rrule->parse_rrule();
3029 $rrule->create_events($createdevent);
3030 \core_date::set_default_server_timezone(); // Change time zone back to what it was.
3032 return $return;
3033 } else {
3034 return 0;
3039 * Delete subscription and all related events.
3041 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
3043 function calendar_delete_subscription($subscription) {
3044 global $DB;
3046 if (!is_object($subscription)) {
3047 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST);
3050 // Delete subscription and related events.
3051 $DB->delete_records('event', array('subscriptionid' => $subscription->id));
3052 $DB->delete_records('event_subscriptions', array('id' => $subscription->id));
3053 \cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id));
3055 // Trigger event, calendar subscription deleted.
3056 $eventparams = array('objectid' => $subscription->id,
3057 'context' => calendar_get_calendar_context($subscription),
3058 'other' => array(
3059 'eventtype' => $subscription->eventtype,
3062 switch ($subscription->eventtype) {
3063 case 'category':
3064 $eventparams['other']['categoryid'] = $subscription->categoryid;
3065 break;
3066 case 'course':
3067 $eventparams['other']['courseid'] = $subscription->courseid;
3068 break;
3069 case 'group':
3070 $eventparams['other']['courseid'] = $subscription->courseid;
3071 $eventparams['other']['groupid'] = $subscription->groupid;
3072 break;
3073 default:
3074 $eventparams['other']['courseid'] = $subscription->courseid;
3076 $event = \core\event\calendar_subscription_deleted::create($eventparams);
3077 $event->trigger();
3081 * From a URL, fetch the calendar and return an iCalendar object.
3083 * @param string $url The iCalendar URL
3084 * @return iCalendar The iCalendar object
3086 function calendar_get_icalendar($url) {
3087 global $CFG;
3089 require_once($CFG->libdir . '/filelib.php');
3090 require_once($CFG->libdir . '/bennu/bennu.inc.php');
3092 $curl = new \curl();
3093 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
3094 $calendar = $curl->get($url);
3096 // Http code validation should actually be the job of curl class.
3097 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
3098 throw new \moodle_exception('errorinvalidicalurl', 'calendar');
3101 $ical = new \iCalendar();
3102 $ical->unserialize($calendar);
3104 return $ical;
3108 * Import events from an iCalendar object into a course calendar.
3110 * @param iCalendar $ical The iCalendar object.
3111 * @param int|null $subscriptionid The subscription ID.
3112 * @return array A log of the import progress, including errors.
3114 function calendar_import_events_from_ical(iCalendar $ical, int $subscriptionid = null): array {
3115 global $DB;
3117 $errors = [];
3118 $eventcount = 0;
3119 $updatecount = 0;
3120 $skippedcount = 0;
3121 $deletedcount = 0;
3123 // Large calendars take a while...
3124 if (!CLI_SCRIPT) {
3125 \core_php_time_limit::raise(300);
3128 // Start with a safe default timezone.
3129 $timezone = 'UTC';
3131 // Grab the timezone from the iCalendar file to be used later.
3132 if (isset($ical->properties['X-WR-TIMEZONE'][0]->value)) {
3133 $timezone = $ical->properties['X-WR-TIMEZONE'][0]->value;
3135 } else if (isset($ical->properties['PRODID'][0]->value)) {
3136 // If the timezone was not found, check to se if this is MS exchange / Office 365 which uses Windows timezones.
3137 if (strncmp($ical->properties['PRODID'][0]->value, 'Microsoft', 9) == 0) {
3138 if (isset($ical->components['VTIMEZONE'][0]->properties['TZID'][0]->value)) {
3139 $tzname = $ical->components['VTIMEZONE'][0]->properties['TZID'][0]->value;
3140 $timezone = IntlTimeZone::getIDForWindowsID($tzname);
3145 $icaluuids = [];
3146 foreach ($ical->components['VEVENT'] as $event) {
3147 $icaluuids[] = $event->properties['UID'][0]->value;
3148 $res = calendar_add_icalendar_event($event, null, $subscriptionid, $timezone);
3149 switch ($res) {
3150 case CALENDAR_IMPORT_EVENT_UPDATED:
3151 $updatecount++;
3152 break;
3153 case CALENDAR_IMPORT_EVENT_INSERTED:
3154 $eventcount++;
3155 break;
3156 case CALENDAR_IMPORT_EVENT_SKIPPED:
3157 $skippedcount++;
3158 break;
3159 case 0:
3160 if (empty($event->properties['SUMMARY'])) {
3161 $errors[] = '(' . get_string('notitle', 'calendar') . ')';
3162 } else {
3163 $errors[] = $event->properties['SUMMARY'][0]->value;
3165 break;
3169 $existing = $DB->get_field('event_subscriptions', 'lastupdated', ['id' => $subscriptionid]);
3170 if (!empty($existing)) {
3171 $eventsuuids = $DB->get_records_menu('event', ['subscriptionid' => $subscriptionid], '', 'id, uuid');
3173 $icaleventscount = count($icaluuids);
3174 $tobedeleted = [];
3175 if (count($eventsuuids) > $icaleventscount) {
3176 foreach ($eventsuuids as $eventid => $eventuuid) {
3177 if (!in_array($eventuuid, $icaluuids)) {
3178 $tobedeleted[] = $eventid;
3181 if (!empty($tobedeleted)) {
3182 $DB->delete_records_list('event', 'id', $tobedeleted);
3183 $deletedcount = count($tobedeleted);
3188 $result = [
3189 'eventsimported' => $eventcount,
3190 'eventsskipped' => $skippedcount,
3191 'eventsupdated' => $updatecount,
3192 'eventsdeleted' => $deletedcount,
3193 'haserror' => !empty($errors),
3194 'errors' => $errors,
3197 return $result;
3201 * Fetch a calendar subscription and update the events in the calendar.
3203 * @param int $subscriptionid The course ID for the calendar.
3204 * @return array A log of the import progress, including errors.
3206 function calendar_update_subscription_events($subscriptionid) {
3207 $sub = calendar_get_subscription($subscriptionid);
3209 // Don't update a file subscription.
3210 if (empty($sub->url)) {
3211 return 'File subscription not updated.';
3214 $ical = calendar_get_icalendar($sub->url);
3215 $return = calendar_import_events_from_ical($ical, $subscriptionid);
3216 $sub->lastupdated = time();
3218 calendar_update_subscription($sub);
3220 return $return;
3224 * Update a calendar subscription. Also updates the associated cache.
3226 * @param stdClass|array $subscription Subscription record.
3227 * @throws coding_exception If something goes wrong
3228 * @since Moodle 2.5
3230 function calendar_update_subscription($subscription) {
3231 global $DB;
3233 if (is_array($subscription)) {
3234 $subscription = (object)$subscription;
3236 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
3237 throw new \coding_exception('Cannot update a subscription without a valid id');
3240 $DB->update_record('event_subscriptions', $subscription);
3242 // Update cache.
3243 $cache = \cache::make('core', 'calendar_subscriptions');
3244 $cache->set($subscription->id, $subscription);
3246 // Trigger event, calendar subscription updated.
3247 $eventparams = array('userid' => $subscription->userid,
3248 'objectid' => $subscription->id,
3249 'context' => calendar_get_calendar_context($subscription),
3250 'other' => array(
3251 'eventtype' => $subscription->eventtype,
3254 switch ($subscription->eventtype) {
3255 case 'category':
3256 $eventparams['other']['categoryid'] = $subscription->categoryid;
3257 break;
3258 case 'course':
3259 $eventparams['other']['courseid'] = $subscription->courseid;
3260 break;
3261 case 'group':
3262 $eventparams['other']['courseid'] = $subscription->courseid;
3263 $eventparams['other']['groupid'] = $subscription->groupid;
3264 break;
3265 default:
3266 $eventparams['other']['courseid'] = $subscription->courseid;
3268 $event = \core\event\calendar_subscription_updated::create($eventparams);
3269 $event->trigger();
3273 * Checks to see if the user can edit a given subscription feed.
3275 * @param mixed $subscriptionorid Subscription object or id
3276 * @return bool true if current user can edit the subscription else false
3278 function calendar_can_edit_subscription($subscriptionorid) {
3279 global $USER;
3280 if (is_array($subscriptionorid)) {
3281 $subscription = (object)$subscriptionorid;
3282 } else if (is_object($subscriptionorid)) {
3283 $subscription = $subscriptionorid;
3284 } else {
3285 $subscription = calendar_get_subscription($subscriptionorid);
3288 $allowed = new \stdClass;
3289 $courseid = $subscription->courseid;
3290 $categoryid = $subscription->categoryid;
3291 $groupid = $subscription->groupid;
3292 $category = null;
3294 if (!empty($categoryid)) {
3295 $category = \core_course_category::get($categoryid);
3297 calendar_get_allowed_types($allowed, $courseid, null, $category);
3298 switch ($subscription->eventtype) {
3299 case 'user':
3300 return ($USER->id == $subscription->userid && $allowed->user);
3301 case 'course':
3302 if (isset($allowed->courses[$courseid])) {
3303 return $allowed->courses[$courseid];
3304 } else {
3305 return false;
3307 case 'category':
3308 if (isset($allowed->categories[$categoryid])) {
3309 return $allowed->categories[$categoryid];
3310 } else {
3311 return false;
3313 case 'site':
3314 return $allowed->site;
3315 case 'group':
3316 if (isset($allowed->groups[$groupid])) {
3317 return $allowed->groups[$groupid];
3318 } else {
3319 return false;
3321 default:
3322 return false;
3327 * Helper function to determine the context of a calendar subscription.
3328 * Subscriptions can be created in two contexts COURSE, or USER.
3330 * @param stdClass $subscription
3331 * @return context instance
3333 function calendar_get_calendar_context($subscription) {
3334 // Determine context based on calendar type.
3335 if ($subscription->eventtype === 'site') {
3336 $context = \context_course::instance(SITEID);
3337 } else if ($subscription->eventtype === 'group' || $subscription->eventtype === 'course') {
3338 $context = \context_course::instance($subscription->courseid);
3339 } else {
3340 $context = \context_user::instance($subscription->userid);
3342 return $context;
3346 * Implements callback user_preferences, lists preferences that users are allowed to update directly
3348 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3350 * @return array
3352 function core_calendar_user_preferences() {
3353 $preferences = [];
3354 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED, 'default' => '0',
3355 'choices' => array('0', CALENDAR_TF_12, CALENDAR_TF_24)
3357 $preferences['calendar_startwday'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3358 'choices' => array(0, 1, 2, 3, 4, 5, 6));
3359 $preferences['calendar_maxevents'] = array('type' => PARAM_INT, 'choices' => range(1, 20));
3360 $preferences['calendar_lookahead'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 365,
3361 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3362 $preferences['calendar_persistflt'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3363 'choices' => array(0, 1));
3364 return $preferences;
3368 * Get legacy calendar events
3370 * @param int $tstart Start time of time range for events
3371 * @param int $tend End time of time range for events
3372 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3373 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3374 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3375 * @param boolean $withduration whether only events starting within time range selected
3376 * or events in progress/already started selected as well
3377 * @param boolean $ignorehidden whether to select only visible events or all events
3378 * @param array $categories array of category ids and/or objects.
3379 * @param int $limitnum Number of events to fetch or zero to fetch all.
3381 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3383 function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses,
3384 $withduration = true, $ignorehidden = true, $categories = [], $limitnum = 0) {
3385 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3386 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3387 // parameters, but with the new API method, only null and arrays are accepted.
3388 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3389 // If parameter is true, return null.
3390 if ($param === true) {
3391 return null;
3394 // If parameter is false, return an empty array.
3395 if ($param === false) {
3396 return [];
3399 // If the parameter is a scalar value, enclose it in an array.
3400 if (!is_array($param)) {
3401 return [$param];
3404 // No normalisation required.
3405 return $param;
3406 }, [$users, $groups, $courses, $categories]);
3408 // If a single user is provided, we can use that for capability checks.
3409 // Otherwise current logged in user is used - See MDL-58768.
3410 if (is_array($userparam) && count($userparam) == 1) {
3411 \core_calendar\local\event\container::set_requesting_user($userparam[0]);
3413 $mapper = \core_calendar\local\event\container::get_event_mapper();
3414 $events = \core_calendar\local\api::get_events(
3415 $tstart,
3416 $tend,
3417 null,
3418 null,
3419 null,
3420 null,
3421 $limitnum,
3422 null,
3423 $userparam,
3424 $groupparam,
3425 $courseparam,
3426 $categoryparam,
3427 $withduration,
3428 $ignorehidden
3431 return array_reduce($events, function($carry, $event) use ($mapper) {
3432 return $carry + [$event->get_id() => $mapper->from_event_to_stdclass($event)];
3433 }, []);
3438 * Get the calendar view output.
3440 * @param \calendar_information $calendar The calendar being represented
3441 * @param string $view The type of calendar to have displayed
3442 * @param bool $includenavigation Whether to include navigation
3443 * @param bool $skipevents Whether to load the events or not
3444 * @param int $lookahead Overwrites site and users's lookahead setting.
3445 * @return array[array, string]
3447 function calendar_get_view(\calendar_information $calendar, $view, $includenavigation = true, bool $skipevents = false,
3448 ?int $lookahead = null) {
3449 global $PAGE, $CFG;
3451 $renderer = $PAGE->get_renderer('core_calendar');
3452 $type = \core_calendar\type_factory::get_calendar_instance();
3454 // Calculate the bounds of the month.
3455 $calendardate = $type->timestamp_to_date_array($calendar->time);
3457 $date = new \DateTime('now', core_date::get_user_timezone_object(99));
3458 $eventlimit = 0;
3460 if ($view === 'day') {
3461 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday']);
3462 $date->setTimestamp($tstart);
3463 $date->modify('+1 day');
3464 } else if ($view === 'upcoming' || $view === 'upcoming_mini') {
3465 // Number of days in the future that will be used to fetch events.
3466 if (!$lookahead) {
3467 if (isset($CFG->calendar_lookahead)) {
3468 $defaultlookahead = intval($CFG->calendar_lookahead);
3469 } else {
3470 $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD;
3472 $lookahead = get_user_preferences('calendar_lookahead', $defaultlookahead);
3475 // Maximum number of events to be displayed on upcoming view.
3476 $defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS;
3477 if (isset($CFG->calendar_maxevents)) {
3478 $defaultmaxevents = intval($CFG->calendar_maxevents);
3480 $eventlimit = get_user_preferences('calendar_maxevents', $defaultmaxevents);
3482 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday'],
3483 $calendardate['hours']);
3484 $date->setTimestamp($tstart);
3485 $date->modify('+' . $lookahead . ' days');
3486 } else {
3487 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], 1);
3488 $monthdays = $type->get_num_days_in_month($calendardate['year'], $calendardate['mon']);
3489 $date->setTimestamp($tstart);
3490 $date->modify('+' . $monthdays . ' days');
3492 if ($view === 'mini' || $view === 'minithree') {
3493 $template = 'core_calendar/calendar_mini';
3494 } else {
3495 $template = 'core_calendar/calendar_month';
3499 // We need to extract 1 second to ensure that we don't get into the next day.
3500 $date->modify('-1 second');
3501 $tend = $date->getTimestamp();
3503 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3504 // If parameter is true, return null.
3505 if ($param === true) {
3506 return null;
3509 // If parameter is false, return an empty array.
3510 if ($param === false) {
3511 return [];
3514 // If the parameter is a scalar value, enclose it in an array.
3515 if (!is_array($param)) {
3516 return [$param];
3519 // No normalisation required.
3520 return $param;
3521 }, [$calendar->users, $calendar->groups, $calendar->courses, $calendar->categories]);
3523 if ($skipevents) {
3524 $events = [];
3525 } else {
3526 $events = \core_calendar\local\api::get_events(
3527 $tstart,
3528 $tend,
3529 null,
3530 null,
3531 null,
3532 null,
3533 $eventlimit,
3534 null,
3535 $userparam,
3536 $groupparam,
3537 $courseparam,
3538 $categoryparam,
3539 true,
3540 true,
3541 function ($event) {
3542 if ($proxy = $event->get_course_module()) {
3543 $cminfo = $proxy->get_proxied_instance();
3544 return $cminfo->uservisible;
3547 if ($proxy = $event->get_category()) {
3548 $category = $proxy->get_proxied_instance();
3550 return $category->is_uservisible();
3553 return true;
3558 $related = [
3559 'events' => $events,
3560 'cache' => new \core_calendar\external\events_related_objects_cache($events),
3561 'type' => $type,
3564 $data = [];
3565 $calendar->set_viewmode($view);
3566 if ($view == "month" || $view == "monthblock" || $view == "mini" || $view == "minithree" ) {
3567 $month = new \core_calendar\external\month_exporter($calendar, $type, $related);
3568 $month->set_includenavigation($includenavigation);
3569 $month->set_initialeventsloaded(!$skipevents);
3570 $month->set_showcoursefilter(($view == "month" || $view == "monthblock"));
3571 $data = $month->export($renderer);
3572 } else if ($view == "day") {
3573 $day = new \core_calendar\external\calendar_day_exporter($calendar, $related);
3574 $data = $day->export($renderer);
3575 $data->viewingday = true;
3576 $data->showviewselector = true;
3577 $template = 'core_calendar/calendar_day';
3578 } else if ($view == "upcoming" || $view == "upcoming_mini") {
3579 $upcoming = new \core_calendar\external\calendar_upcoming_exporter($calendar, $related);
3580 $data = $upcoming->export($renderer);
3582 if ($view == "upcoming") {
3583 $template = 'core_calendar/calendar_upcoming';
3584 $data->viewingupcoming = true;
3585 $data->showviewselector = true;
3586 } else if ($view == "upcoming_mini") {
3587 $template = 'core_calendar/calendar_upcoming_mini';
3591 // Check if $data has events.
3592 if (isset($data->events)) {
3593 // Let's check and sanitize all "name" in $data->events before it's sent to front end.
3594 foreach ($data->events as $d) {
3595 $name = $d->name ?? null;
3596 // Encode special characters if our decoded name does not match the original name.
3597 if ($name && (html_entity_decode($name) !== $name)) {
3598 $d->name = htmlspecialchars(html_entity_decode($name), ENT_QUOTES, 'utf-8');
3603 return [$data, $template];
3607 * Request and render event form fragment.
3609 * @param array $args The fragment arguments.
3610 * @return string The rendered mform fragment.
3612 function calendar_output_fragment_event_form($args) {
3613 global $CFG, $OUTPUT, $USER;
3614 require_once($CFG->libdir . '/grouplib.php');
3615 $html = '';
3616 $data = [];
3617 $eventid = isset($args['eventid']) ? clean_param($args['eventid'], PARAM_INT) : null;
3618 $starttime = isset($args['starttime']) ? clean_param($args['starttime'], PARAM_INT) : null;
3619 $courseid = (isset($args['courseid']) && $args['courseid'] != SITEID) ? clean_param($args['courseid'], PARAM_INT) : null;
3620 $categoryid = isset($args['categoryid']) ? clean_param($args['categoryid'], PARAM_INT) : null;
3621 $event = null;
3622 $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
3623 $context = \context_user::instance($USER->id);
3624 $editoroptions = \core_calendar\local\event\forms\create::build_editor_options($context);
3625 $formoptions = ['editoroptions' => $editoroptions, 'courseid' => $courseid];
3626 $draftitemid = 0;
3628 if ($hasformdata) {
3629 parse_str(clean_param($args['formdata'], PARAM_TEXT), $data);
3630 if (isset($data['description']['itemid'])) {
3631 $draftitemid = $data['description']['itemid'];
3635 if ($starttime) {
3636 $formoptions['starttime'] = $starttime;
3638 // Let's check first which event types user can add.
3639 $eventtypes = calendar_get_allowed_event_types($courseid);
3640 $formoptions['eventtypes'] = $eventtypes;
3642 if (is_null($eventid)) {
3643 if (!empty($courseid)) {
3644 $groupcoursedata = groups_get_course_data($courseid);
3645 $formoptions['groups'] = [];
3646 foreach ($groupcoursedata->groups as $groupid => $groupdata) {
3647 $formoptions['groups'][$groupid] = $groupdata->name;
3651 $mform = new \core_calendar\local\event\forms\create(
3652 null,
3653 $formoptions,
3654 'post',
3656 null,
3657 true,
3658 $data
3661 // If the user is on course context and is allowed to add course events set the event type default to course.
3662 if (!empty($courseid) && !empty($eventtypes['course'])) {
3663 $data['eventtype'] = 'course';
3664 $data['courseid'] = $courseid;
3665 $data['groupcourseid'] = $courseid;
3666 } else if (!empty($categoryid) && !empty($eventtypes['category'])) {
3667 $data['eventtype'] = 'category';
3668 $data['categoryid'] = $categoryid;
3669 } else if (!empty($groupcoursedata) && !empty($eventtypes['group'])) {
3670 $data['groupcourseid'] = $courseid;
3671 $data['groups'] = $groupcoursedata->groups;
3673 $mform->set_data($data);
3674 } else {
3675 $event = calendar_event::load($eventid);
3677 if (!calendar_edit_event_allowed($event)) {
3678 throw new \moodle_exception('nopermissiontoupdatecalendar');
3681 $mapper = new \core_calendar\local\event\mappers\create_update_form_mapper();
3682 $eventdata = $mapper->from_legacy_event_to_data($event);
3683 $data = array_merge((array) $eventdata, $data);
3684 $event->count_repeats();
3685 $formoptions['event'] = $event;
3687 if (!empty($event->courseid)) {
3688 $groupcoursedata = groups_get_course_data($event->courseid);
3689 $formoptions['groups'] = [];
3690 foreach ($groupcoursedata->groups as $groupid => $groupdata) {
3691 $formoptions['groups'][$groupid] = $groupdata->name;
3695 $data['description']['text'] = file_prepare_draft_area(
3696 $draftitemid,
3697 $event->context->id,
3698 'calendar',
3699 'event_description',
3700 $event->id,
3701 null,
3702 $data['description']['text']
3704 $data['description']['itemid'] = $draftitemid;
3706 $mform = new \core_calendar\local\event\forms\update(
3707 null,
3708 $formoptions,
3709 'post',
3711 null,
3712 true,
3713 $data
3715 $mform->set_data($data);
3717 // Check to see if this event is part of a subscription or import.
3718 // If so display a warning on edit.
3719 if (isset($event->subscriptionid) && ($event->subscriptionid != null)) {
3720 $renderable = new \core\output\notification(
3721 get_string('eventsubscriptioneditwarning', 'calendar'),
3722 \core\output\notification::NOTIFY_INFO
3725 $html .= $OUTPUT->render($renderable);
3729 if ($hasformdata) {
3730 $mform->is_validated();
3733 $html .= $mform->render();
3734 return $html;
3738 * Calculate the timestamp from the supplied Gregorian Year, Month, and Day.
3740 * @param int $d The day
3741 * @param int $m The month
3742 * @param int $y The year
3743 * @param int $time The timestamp to use instead of a separate y/m/d.
3744 * @return int The timestamp
3746 function calendar_get_timestamp($d, $m, $y, $time = 0) {
3747 // If a day, month and year were passed then convert it to a timestamp. If these were passed
3748 // then we can assume the day, month and year are passed as Gregorian, as no where in core
3749 // should we be passing these values rather than the time.
3750 if (!empty($d) && !empty($m) && !empty($y)) {
3751 if (checkdate($m, $d, $y)) {
3752 $time = make_timestamp($y, $m, $d);
3753 } else {
3754 $time = time();
3756 } else if (empty($time)) {
3757 $time = time();
3760 return $time;
3764 * Get the calendar footer options.
3766 * @param calendar_information $calendar The calendar information object.
3767 * @param array $options Display options for the footer. If an option is not set, a default value will be provided.
3768 * It consists of:
3769 * - showfullcalendarlink - bool - Whether to show the full calendar link or not. Defaults to false.
3771 * @return array The data for template and template name.
3773 function calendar_get_footer_options($calendar, array $options = []) {
3774 global $CFG, $USER, $PAGE;
3776 // Generate hash for iCal link.
3777 $authtoken = calendar_get_export_token($USER);
3779 $renderer = $PAGE->get_renderer('core_calendar');
3780 $footer = new \core_calendar\external\footer_options_exporter($calendar, $USER->id, $authtoken, $options);
3781 $data = $footer->export($renderer);
3782 $template = 'core_calendar/footer_options';
3784 return [$data, $template];
3788 * Get the list of potential calendar filter types as a type => name
3789 * combination.
3791 * @return array
3793 function calendar_get_filter_types() {
3794 $types = [
3795 'site',
3796 'category',
3797 'course',
3798 'group',
3799 'user',
3800 'other'
3803 return array_map(function($type) {
3804 return [
3805 'eventtype' => $type,
3806 'name' => get_string("eventtype{$type}", "calendar"),
3807 'icon' => true,
3808 'key' => 'i/' . $type . 'event',
3809 'component' => 'core'
3811 }, $types);
3815 * Check whether the specified event type is valid.
3817 * @param string $type
3818 * @return bool
3820 function calendar_is_valid_eventtype($type) {
3821 $validtypes = [
3822 'user',
3823 'group',
3824 'course',
3825 'category',
3826 'site',
3828 return in_array($type, $validtypes);
3832 * Get event types the user can create event based on categories, courses and groups
3833 * the logged in user belongs to.
3835 * @param int|null $courseid The course id.
3836 * @return array The array of allowed types.
3838 function calendar_get_allowed_event_types(int $courseid = null) {
3839 global $DB, $CFG, $USER;
3841 $types = [
3842 'user' => false,
3843 'site' => false,
3844 'course' => false,
3845 'group' => false,
3846 'category' => false
3849 if (!empty($courseid) && $courseid != SITEID) {
3850 $context = \context_course::instance($courseid);
3851 $types['user'] = has_capability('moodle/calendar:manageownentries', $context);
3852 calendar_internal_update_course_and_group_permission($courseid, $context, $types);
3855 if (has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID))) {
3856 $types['site'] = true;
3859 if (has_capability('moodle/calendar:manageownentries', \context_system::instance())) {
3860 $types['user'] = true;
3862 if (core_course_category::has_manage_capability_on_any()) {
3863 $types['category'] = true;
3866 // We still don't know if the user can create group and course events, so iterate over the courses to find out
3867 // if the user has capabilities in one of the courses.
3868 if ($types['course'] == false || $types['group'] == false) {
3869 if ($CFG->calendar_adminseesall && has_capability('moodle/calendar:manageentries', context_system::instance())) {
3870 $sql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3871 FROM {course} c
3872 JOIN {context} ctx ON ctx.contextlevel = ? AND ctx.instanceid = c.id
3873 WHERE c.id IN (
3874 SELECT DISTINCT courseid FROM {groups}
3876 $courseswithgroups = $DB->get_recordset_sql($sql, [CONTEXT_COURSE]);
3877 foreach ($courseswithgroups as $course) {
3878 context_helper::preload_from_record($course);
3879 $context = context_course::instance($course->id);
3881 if (has_capability('moodle/calendar:manageentries', $context)) {
3882 if (has_any_capability(['moodle/site:accessallgroups', 'moodle/calendar:managegroupentries'], $context)) {
3883 // The user can manage group entries or access any group.
3884 $types['group'] = true;
3885 $types['course'] = true;
3886 break;
3890 $courseswithgroups->close();
3892 if (false === $types['course']) {
3893 // Course is still not confirmed. There may have been no courses with a group in them.
3894 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
3895 $sql = "SELECT
3896 c.id, c.visible, {$ctxfields}
3897 FROM {course} c
3898 JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
3899 $params = [
3900 'contextlevel' => CONTEXT_COURSE,
3902 $courses = $DB->get_recordset_sql($sql, $params);
3903 foreach ($courses as $course) {
3904 context_helper::preload_from_record($course);
3905 $context = context_course::instance($course->id);
3906 if (has_capability('moodle/calendar:manageentries', $context)) {
3907 $types['course'] = true;
3908 break;
3911 $courses->close();
3914 } else {
3915 $courses = calendar_get_default_courses(null, 'id');
3916 if (empty($courses)) {
3917 return $types;
3920 $courseids = array_map(function($c) {
3921 return $c->id;
3922 }, $courses);
3924 // Check whether the user has access to create events within courses which have groups.
3925 list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
3926 $sql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3927 FROM {course} c
3928 JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3929 WHERE c.id $insql
3930 AND c.id IN (SELECT DISTINCT courseid FROM {groups})";
3931 $params['contextlevel'] = CONTEXT_COURSE;
3932 $courseswithgroups = $DB->get_recordset_sql($sql, $params);
3933 foreach ($courseswithgroups as $coursewithgroup) {
3934 context_helper::preload_from_record($coursewithgroup);
3935 $context = context_course::instance($coursewithgroup->id);
3937 calendar_internal_update_course_and_group_permission($coursewithgroup->id, $context, $types);
3939 // Okay, course and group event types are allowed, no need to keep the loop iteration.
3940 if ($types['course'] == true && $types['group'] == true) {
3941 break;
3944 $courseswithgroups->close();
3946 if (false === $types['course']) {
3947 list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
3948 $contextsql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3949 FROM {course} c
3950 JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3951 WHERE c.id $insql";
3952 $params['contextlevel'] = CONTEXT_COURSE;
3953 $contextrecords = $DB->get_recordset_sql($contextsql, $params);
3954 foreach ($contextrecords as $course) {
3955 context_helper::preload_from_record($course);
3956 $coursecontext = context_course::instance($course->id);
3957 if (has_capability('moodle/calendar:manageentries', $coursecontext)
3958 && ($courseid == $course->id || empty($courseid))) {
3959 $types['course'] = true;
3960 break;
3963 $contextrecords->close();
3969 return $types;
3973 * Given a course id, and context, updates the permission types array to add the 'course' or 'group'
3974 * permission if it is relevant for that course.
3976 * For efficiency, if they already have 'course' or 'group' then it skips checks.
3978 * Do not call this function directly, it is only for use by calendar_get_allowed_event_types().
3980 * @param int $courseid Course id
3981 * @param context $context Context for that course
3982 * @param array $types Current permissions
3984 function calendar_internal_update_course_and_group_permission(int $courseid, context $context, array &$types) {
3985 if (!$types['course']) {
3986 // If they have manageentries permission on the course, then they can update this course.
3987 if (has_capability('moodle/calendar:manageentries', $context)) {
3988 $types['course'] = true;
3991 // To update group events they must have EITHER manageentries OR managegroupentries.
3992 if (!$types['group'] && (has_capability('moodle/calendar:manageentries', $context) ||
3993 has_capability('moodle/calendar:managegroupentries', $context))) {
3994 // And they also need for a group to exist on the course.
3995 $groups = groups_get_all_groups($courseid);
3996 if (!empty($groups)) {
3997 // And either accessallgroups, or belong to one of the groups.
3998 if (has_capability('moodle/site:accessallgroups', $context)) {
3999 $types['group'] = true;
4000 } else {
4001 foreach ($groups as $group) {
4002 if (groups_is_member($group->id)) {
4003 $types['group'] = true;
4004 break;
4013 * Get the auth token for exporting the given user calendar.
4014 * @param stdClass $user The user to export the calendar for
4016 * @return string The export token.
4018 function calendar_get_export_token(stdClass $user): string {
4019 global $CFG, $DB;
4021 return sha1($user->id . $DB->get_field('user', 'password', ['id' => $user->id]) . $CFG->calendar_exportsalt);
4025 * Get the list of URL parameters for calendar expport and import links.
4027 * @return array
4029 function calendar_get_export_import_link_params(): array {
4030 global $PAGE;
4032 $params = [];
4033 if ($courseid = $PAGE->url->get_param('course')) {
4034 $params['course'] = $courseid;
4036 if ($categoryid = $PAGE->url->get_param('category')) {
4037 $params['category'] = $categoryid;
4040 return $params;
4044 * Implements the inplace editable feature.
4046 * @param string $itemtype Type of the inplace editable element
4047 * @param int $itemid Id of the item to edit
4048 * @param int $newvalue New value of the item
4049 * @return \core\output\inplace_editable
4051 function calendar_inplace_editable(string $itemtype, int $itemid, int $newvalue): \core\output\inplace_editable {
4052 global $OUTPUT;
4054 if ($itemtype === 'refreshinterval') {
4056 $subscription = calendar_get_subscription($itemid);
4057 $context = calendar_get_calendar_context($subscription);
4058 external_api::validate_context($context);
4060 $updateresult = \core_calendar\output\refreshintervalcollection::update($itemid, $newvalue);
4062 $refreshresults = calendar_update_subscription_events($itemid);
4063 \core\notification::add($OUTPUT->render_from_template(
4064 'core_calendar/subscription_update_result',
4065 array_merge($refreshresults, [
4066 'subscriptionname' => s($subscription->name),
4068 ), \core\notification::INFO);
4070 return $updateresult;
4073 external_api::validate_context(context_system::instance());