MDL-74905 environment: 4.2 base information
[moodle.git] / calendar / lib.php
blobbf5f15c279f69a7baa1d1ddfd8c8bd7abdcdc232
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 array 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;
1070 * Creates a new instance
1072 * @param int $day the number of the day
1073 * @param int $month the number of the month
1074 * @param int $year the number of the year
1075 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
1076 * and $calyear to support multiple calendars
1078 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
1079 // If a day, month and year were passed then convert it to a timestamp. If these were passed
1080 // then we can assume the day, month and year are passed as Gregorian, as no where in core
1081 // should we be passing these values rather than the time. This is done for BC.
1082 if (!empty($day) || !empty($month) || !empty($year)) {
1083 $date = usergetdate(time());
1084 if (empty($day)) {
1085 $day = $date['mday'];
1087 if (empty($month)) {
1088 $month = $date['mon'];
1090 if (empty($year)) {
1091 $year = $date['year'];
1093 if (checkdate($month, $day, $year)) {
1094 $time = make_timestamp($year, $month, $day);
1095 } else {
1096 $time = time();
1100 $this->set_time($time);
1104 * Creates and set up a instance.
1106 * @param int $time the unixtimestamp representing the date we want to view.
1107 * @param int $courseid The ID of the course the user wishes to view.
1108 * @param int $categoryid The ID of the category the user wishes to view
1109 * If a courseid is specified, this value is ignored.
1110 * @return calendar_information
1112 public static function create($time, int $courseid, int $categoryid = null) : calendar_information {
1113 $calendar = new static(0, 0, 0, $time);
1114 if ($courseid != SITEID && !empty($courseid)) {
1115 // Course ID must be valid and existing.
1116 $course = get_course($courseid);
1117 $calendar->context = context_course::instance($course->id);
1119 if (!$course->visible && !is_role_switched($course->id)) {
1120 require_capability('moodle/course:viewhiddencourses', $calendar->context);
1123 $courses = [$course->id => $course];
1124 $category = (\core_course_category::get($course->category, MUST_EXIST, true))->get_db_record();
1125 } else if (!empty($categoryid)) {
1126 $course = get_site();
1127 $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1129 // Filter available courses to those within this category or it's children.
1130 $ids = [$categoryid];
1131 $category = \core_course_category::get($categoryid);
1132 $ids = array_merge($ids, array_keys($category->get_children()));
1133 $courses = array_filter($courses, function($course) use ($ids) {
1134 return array_search($course->category, $ids) !== false;
1136 $category = $category->get_db_record();
1138 $calendar->context = context_coursecat::instance($categoryid);
1139 } else {
1140 $course = get_site();
1141 $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1142 $category = null;
1144 $calendar->context = context_system::instance();
1147 $calendar->set_sources($course, $courses, $category);
1149 return $calendar;
1153 * Set the time period of this instance.
1155 * @param int $time the unixtimestamp representing the date we want to view.
1156 * @return $this
1158 public function set_time($time = null) {
1159 if (empty($time)) {
1160 $this->time = time();
1161 } else {
1162 $this->time = $time;
1165 return $this;
1169 * Initialize calendar information
1171 * @deprecated 3.4
1172 * @param stdClass $course object
1173 * @param array $coursestoload An array of courses [$course->id => $course]
1174 * @param bool $ignorefilters options to use filter
1176 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
1177 debugging('The prepare_for_view() function has been deprecated. Please update your code to use set_sources()',
1178 DEBUG_DEVELOPER);
1179 $this->set_sources($course, $coursestoload);
1183 * Set the sources for events within the calendar.
1185 * If no category is provided, then the category path for the current
1186 * course will be used.
1188 * @param stdClass $course The current course being viewed.
1189 * @param stdClass[] $courses The list of all courses currently accessible.
1190 * @param stdClass $category The current category to show.
1192 public function set_sources(stdClass $course, array $courses, stdClass $category = null) {
1193 global $USER;
1195 // A cousre must always be specified.
1196 $this->course = $course;
1197 $this->courseid = $course->id;
1199 list($courseids, $group, $user) = calendar_set_filters($courses);
1200 $this->courses = $courseids;
1201 $this->groups = $group;
1202 $this->users = $user;
1204 // Do not show category events by default.
1205 $this->categoryid = null;
1206 $this->categories = null;
1208 // Determine the correct category information to show.
1209 // When called with a course, the category of that course is usually included too.
1210 // When a category was specifically requested, it should be requested with the site id.
1211 if (SITEID !== $this->courseid) {
1212 // A specific course was requested.
1213 // Fetch the category that this course is in, along with all parents.
1214 // Do not include child categories of this category, as the user many not have enrolments in those siblings or children.
1215 $category = \core_course_category::get($course->category, MUST_EXIST, true);
1216 $this->categoryid = $category->id;
1218 $this->categories = $category->get_parents();
1219 $this->categories[] = $category->id;
1220 } else if (null !== $category && $category->id > 0) {
1221 // A specific category was requested.
1222 // Fetch all parents of this category, along with all children too.
1223 $category = \core_course_category::get($category->id);
1224 $this->categoryid = $category->id;
1226 // Build the category list.
1227 // This includes the current category.
1228 $this->categories = $category->get_parents();
1229 $this->categories[] = $category->id;
1230 $this->categories = array_merge($this->categories, $category->get_all_children_ids());
1231 } else if (SITEID === $this->courseid) {
1232 // The site was requested.
1233 // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
1235 // Grab the list of categories that this user has courses in.
1236 $coursecategories = array_flip(array_map(function($course) {
1237 return $course->category;
1238 }, $courses));
1240 $calcatcache = cache::make('core', 'calendar_categories');
1241 $this->categories = $calcatcache->get('site');
1242 if ($this->categories === false) {
1243 // Use the category id as the key in the following array. That way we do not have to remove duplicates.
1244 $categories = [];
1245 foreach (\core_course_category::get_all() as $category) {
1246 if (isset($coursecategories[$category->id]) ||
1247 has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
1248 // If the user has access to a course in this category or can manage the category,
1249 // then they can see all parent categories too.
1250 $categories[$category->id] = true;
1251 foreach ($category->get_parents() as $catid) {
1252 $categories[$catid] = true;
1256 $this->categories = array_keys($categories);
1257 $calcatcache->set('site', $this->categories);
1263 * Ensures the date for the calendar is correct and either sets it to now
1264 * or throws a moodle_exception if not
1266 * @param bool $defaultonow use current time
1267 * @throws moodle_exception
1268 * @return bool validation of checkdate
1270 public function checkdate($defaultonow = true) {
1271 if (!checkdate($this->month, $this->day, $this->year)) {
1272 if ($defaultonow) {
1273 $now = usergetdate(time());
1274 $this->day = intval($now['mday']);
1275 $this->month = intval($now['mon']);
1276 $this->year = intval($now['year']);
1277 return true;
1278 } else {
1279 throw new moodle_exception('invaliddate');
1282 return true;
1286 * Gets todays timestamp for the calendar
1288 * @return int today timestamp
1290 public function timestamp_today() {
1291 return $this->time;
1294 * Gets tomorrows timestamp for the calendar
1296 * @return int tomorrow timestamp
1298 public function timestamp_tomorrow() {
1299 return strtotime('+1 day', $this->time);
1302 * Adds the pretend blocks for the calendar
1304 * @param core_calendar_renderer $renderer
1305 * @param bool $showfilters display filters, false is set as default
1306 * @param string|null $view preference view options (eg: day, month, upcoming)
1308 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
1309 global $PAGE;
1311 if (!has_capability('moodle/block:view', $PAGE->context) ) {
1312 return;
1315 if ($showfilters) {
1316 $filters = new block_contents();
1317 $filters->content = $renderer->event_filter();
1318 $filters->footer = '';
1319 $filters->title = get_string('eventskey', 'calendar');
1320 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
1325 * Getter method for the calendar's view mode.
1327 * @return string
1329 public function get_viewmode(): string {
1330 return $this->viewmode;
1334 * Setter method for the calendar's view mode.
1336 * @param string $viewmode
1338 public function set_viewmode(string $viewmode): void {
1339 $this->viewmode = $viewmode;
1344 * Get calendar events.
1346 * @param int $tstart Start time of time range for events
1347 * @param int $tend End time of time range for events
1348 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
1349 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
1350 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
1351 * @param boolean $withduration whether only events starting within time range selected
1352 * or events in progress/already started selected as well
1353 * @param boolean $ignorehidden whether to select only visible events or all events
1354 * @param array|int|boolean $categories array of categories, category id or boolean for all/no course events
1355 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
1357 function calendar_get_events($tstart, $tend, $users, $groups, $courses,
1358 $withduration = true, $ignorehidden = true, $categories = []) {
1359 global $DB;
1361 $whereclause = '';
1362 $params = array();
1363 // Quick test.
1364 if (empty($users) && empty($groups) && empty($courses) && empty($categories)) {
1365 return array();
1368 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
1369 // Events from a number of users
1370 if(!empty($whereclause)) $whereclause .= ' OR';
1371 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED);
1372 $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)";
1373 $params = array_merge($params, $inparamsusers);
1374 } else if($users === true) {
1375 // Events from ALL users
1376 if(!empty($whereclause)) $whereclause .= ' OR';
1377 $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)';
1378 } else if($users === false) {
1379 // No user at all, do nothing
1382 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
1383 // Events from a number of groups
1384 if(!empty($whereclause)) $whereclause .= ' OR';
1385 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED);
1386 $whereclause .= " e.groupid $insqlgroups ";
1387 $params = array_merge($params, $inparamsgroups);
1388 } else if($groups === true) {
1389 // Events from ALL groups
1390 if(!empty($whereclause)) $whereclause .= ' OR ';
1391 $whereclause .= ' e.groupid != 0';
1393 // boolean false (no groups at all): we don't need to do anything
1395 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
1396 if(!empty($whereclause)) $whereclause .= ' OR';
1397 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED);
1398 $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
1399 $params = array_merge($params, $inparamscourses);
1400 } else if ($courses === true) {
1401 // Events from ALL courses
1402 if(!empty($whereclause)) $whereclause .= ' OR';
1403 $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
1406 if ((is_array($categories) && !empty($categories)) || is_numeric($categories)) {
1407 if (!empty($whereclause)) {
1408 $whereclause .= ' OR';
1410 list($insqlcategories, $inparamscategories) = $DB->get_in_or_equal($categories, SQL_PARAMS_NAMED);
1411 $whereclause .= " (e.groupid = 0 AND e.courseid = 0 AND e.categoryid $insqlcategories)";
1412 $params = array_merge($params, $inparamscategories);
1413 } else if ($categories === true) {
1414 // Events from ALL categories.
1415 if (!empty($whereclause)) {
1416 $whereclause .= ' OR';
1418 $whereclause .= ' (e.groupid = 0 AND e.courseid = 0 AND e.categoryid != 0)';
1421 // Security check: if, by now, we have NOTHING in $whereclause, then it means
1422 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
1423 // events no matter what. Allowing the code to proceed might return a completely
1424 // valid query with only time constraints, thus selecting ALL events in that time frame!
1425 if(empty($whereclause)) {
1426 return array();
1429 if($withduration) {
1430 $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1432 else {
1433 $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1435 if(!empty($whereclause)) {
1436 // We have additional constraints
1437 $whereclause = $timeclause.' AND ('.$whereclause.')';
1439 else {
1440 // Just basic time filtering
1441 $whereclause = $timeclause;
1444 if ($ignorehidden) {
1445 $whereclause .= ' AND e.visible = 1';
1448 $sql = "SELECT e.*
1449 FROM {event} e
1450 LEFT JOIN {modules} m ON e.modulename = m.name
1451 -- Non visible modules will have a value of 0.
1452 WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
1453 ORDER BY e.timestart";
1454 $events = $DB->get_records_sql($sql, $params);
1456 if ($events === false) {
1457 $events = array();
1459 return $events;
1463 * Return the days of the week.
1465 * @return array array of days
1467 function calendar_get_days() {
1468 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1469 return $calendartype->get_weekdays();
1473 * Get the subscription from a given id.
1475 * @since Moodle 2.5
1476 * @param int $id id of the subscription
1477 * @return stdClass Subscription record from DB
1478 * @throws moodle_exception for an invalid id
1480 function calendar_get_subscription($id) {
1481 global $DB;
1483 $cache = \cache::make('core', 'calendar_subscriptions');
1484 $subscription = $cache->get($id);
1485 if (empty($subscription)) {
1486 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
1487 $cache->set($id, $subscription);
1490 return $subscription;
1494 * Gets the first day of the week.
1496 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
1498 * @return int
1500 function calendar_get_starting_weekday() {
1501 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1502 return $calendartype->get_starting_weekday();
1506 * Get a HTML link to a course.
1508 * @param int|stdClass $course the course id or course object
1509 * @return string a link to the course (as HTML); empty if the course id is invalid
1511 function calendar_get_courselink($course) {
1512 if (!$course) {
1513 return '';
1516 if (!is_object($course)) {
1517 $course = calendar_get_course_cached($coursecache, $course);
1519 $context = \context_course::instance($course->id);
1520 $fullname = format_string($course->fullname, true, array('context' => $context));
1521 $url = new \moodle_url('/course/view.php', array('id' => $course->id));
1522 $link = \html_writer::link($url, $fullname);
1524 return $link;
1528 * Get current module cache.
1530 * Only use this method if you do not know courseid. Otherwise use:
1531 * get_fast_modinfo($courseid)->instances[$modulename][$instance]
1533 * @param array $modulecache in memory module cache
1534 * @param string $modulename name of the module
1535 * @param int $instance module instance number
1536 * @return stdClass|bool $module information
1538 function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
1539 if (!isset($modulecache[$modulename . '_' . $instance])) {
1540 $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
1543 return $modulecache[$modulename . '_' . $instance];
1547 * Get current course cache.
1549 * @param array $coursecache list of course cache
1550 * @param int $courseid id of the course
1551 * @return stdClass $coursecache[$courseid] return the specific course cache
1553 function calendar_get_course_cached(&$coursecache, $courseid) {
1554 if (!isset($coursecache[$courseid])) {
1555 $coursecache[$courseid] = get_course($courseid);
1557 return $coursecache[$courseid];
1561 * Get group from groupid for calendar display
1563 * @param int $groupid
1564 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1566 function calendar_get_group_cached($groupid) {
1567 static $groupscache = array();
1568 if (!isset($groupscache[$groupid])) {
1569 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1571 return $groupscache[$groupid];
1575 * Add calendar event metadata
1577 * @deprecated since 3.9
1579 * @param stdClass $event event info
1580 * @return stdClass $event metadata
1582 function calendar_add_event_metadata($event) {
1583 debugging('This function is no longer used', DEBUG_DEVELOPER);
1584 global $CFG, $OUTPUT;
1586 // Support multilang in event->name.
1587 $event->name = format_string($event->name, true);
1589 if (!empty($event->modulename)) { // Activity event.
1590 // The module name is set. I will assume that it has to be displayed, and
1591 // also that it is an automatically-generated event. And of course that the
1592 // instace id and modulename are set correctly.
1593 $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
1594 if (!array_key_exists($event->instance, $instances)) {
1595 return;
1597 $module = $instances[$event->instance];
1599 $modulename = $module->get_module_type_name(false);
1600 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
1601 // Will be used as alt text if the event icon.
1602 $eventtype = get_string($event->eventtype, $event->modulename);
1603 } else {
1604 $eventtype = '';
1607 $event->icon = '<img src="' . s($module->get_icon_url()) . '" alt="' . s($eventtype) .
1608 '" title="' . s($modulename) . '" class="icon" />';
1609 $event->referer = html_writer::link($module->url, $event->name);
1610 $event->courselink = calendar_get_courselink($module->get_course());
1611 $event->cmid = $module->id;
1612 } else if ($event->courseid == SITEID) { // Site event.
1613 $event->icon = '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
1614 get_string('siteevent', 'calendar') . '" class="icon" />';
1615 $event->cssclass = 'calendar_event_site';
1616 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event.
1617 $event->icon = '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
1618 get_string('courseevent', 'calendar') . '" class="icon" />';
1619 $event->courselink = calendar_get_courselink($event->courseid);
1620 $event->cssclass = 'calendar_event_course';
1621 } else if ($event->groupid) { // Group event.
1622 if ($group = calendar_get_group_cached($event->groupid)) {
1623 $groupname = format_string($group->name, true, \context_course::instance($group->courseid));
1624 } else {
1625 $groupname = '';
1627 $event->icon = \html_writer::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
1628 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
1629 $event->courselink = calendar_get_courselink($event->courseid) . ', ' . $groupname;
1630 $event->cssclass = 'calendar_event_group';
1631 } else if ($event->userid) { // User event.
1632 $event->icon = '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
1633 get_string('userevent', 'calendar') . '" class="icon" />';
1634 $event->cssclass = 'calendar_event_user';
1637 return $event;
1641 * Get calendar events by id.
1643 * @since Moodle 2.5
1644 * @param array $eventids list of event ids
1645 * @return array Array of event entries, empty array if nothing found
1647 function calendar_get_events_by_id($eventids) {
1648 global $DB;
1650 if (!is_array($eventids) || empty($eventids)) {
1651 return array();
1654 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
1655 $wheresql = "id $wheresql";
1657 return $DB->get_records_select('event', $wheresql, $params);
1661 * Get control options for calendar.
1663 * @param string $type of calendar
1664 * @param array $data calendar information
1665 * @return string $content return available control for the calender in html
1667 function calendar_top_controls($type, $data) {
1668 global $PAGE, $OUTPUT;
1670 // Get the calendar type we are using.
1671 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1673 $content = '';
1675 // Ensure course id passed if relevant.
1676 $courseid = '';
1677 if (!empty($data['id'])) {
1678 $courseid = '&amp;course=' . $data['id'];
1681 // If we are passing a month and year then we need to convert this to a timestamp to
1682 // support multiple calendars. No where in core should these be passed, this logic
1683 // here is for third party plugins that may use this function.
1684 if (!empty($data['m']) && !empty($date['y'])) {
1685 if (!isset($data['d'])) {
1686 $data['d'] = 1;
1688 if (!checkdate($data['m'], $data['d'], $data['y'])) {
1689 $time = time();
1690 } else {
1691 $time = make_timestamp($data['y'], $data['m'], $data['d']);
1693 } else if (!empty($data['time'])) {
1694 $time = $data['time'];
1695 } else {
1696 $time = time();
1699 // Get the date for the calendar type.
1700 $date = $calendartype->timestamp_to_date_array($time);
1702 $urlbase = $PAGE->url;
1704 // We need to get the previous and next months in certain cases.
1705 if ($type == 'frontpage' || $type == 'course' || $type == 'month') {
1706 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1707 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
1708 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
1709 $prevmonthtime['hour'], $prevmonthtime['minute']);
1711 $nextmonth = calendar_add_month($date['mon'], $date['year']);
1712 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
1713 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
1714 $nextmonthtime['hour'], $nextmonthtime['minute']);
1717 switch ($type) {
1718 case 'frontpage':
1719 $prevlink = calendar_get_link_previous(get_string('monthprev', 'calendar'), $urlbase, false, false, false,
1720 true, $prevmonthtime);
1721 $nextlink = calendar_get_link_next(get_string('monthnext', 'calendar'), $urlbase, false, false, false, true,
1722 $nextmonthtime);
1723 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1724 false, false, false, $time);
1726 if (!empty($data['id'])) {
1727 $calendarlink->param('course', $data['id']);
1730 $right = $nextlink;
1732 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1733 $content .= $prevlink . '<span class="hide"> | </span>';
1734 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1735 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1736 ), array('class' => 'current'));
1737 $content .= '<span class="hide"> | </span>' . $right;
1738 $content .= "<span class=\"clearer\"><!-- --></span>\n";
1739 $content .= \html_writer::end_tag('div');
1741 break;
1742 case 'course':
1743 $prevlink = calendar_get_link_previous(get_string('monthprev', 'calendar'), $urlbase, false, false, false,
1744 true, $prevmonthtime);
1745 $nextlink = calendar_get_link_next(get_string('monthnext', 'calendar'), $urlbase, false, false, false,
1746 true, $nextmonthtime);
1747 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1748 false, false, false, $time);
1750 if (!empty($data['id'])) {
1751 $calendarlink->param('course', $data['id']);
1754 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1755 $content .= $prevlink . '<span class="hide"> | </span>';
1756 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1757 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1758 ), array('class' => 'current'));
1759 $content .= '<span class="hide"> | </span>' . $nextlink;
1760 $content .= "<span class=\"clearer\"><!-- --></span>";
1761 $content .= \html_writer::end_tag('div');
1762 break;
1763 case 'upcoming':
1764 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'upcoming')),
1765 false, false, false, $time);
1766 if (!empty($data['id'])) {
1767 $calendarlink->param('course', $data['id']);
1769 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1770 $content .= \html_writer::tag('div', $calendarlink, array('class' => 'centered'));
1771 break;
1772 case 'display':
1773 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1774 false, false, false, $time);
1775 if (!empty($data['id'])) {
1776 $calendarlink->param('course', $data['id']);
1778 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1779 $content .= \html_writer::tag('h3', $calendarlink);
1780 break;
1781 case 'month':
1782 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1783 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $prevmonthtime);
1784 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1785 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $nextmonthtime);
1787 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1788 $content .= $prevlink . '<span class="hide"> | </span>';
1789 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1790 $content .= '<span class="hide"> | </span>' . $nextlink;
1791 $content .= '<span class="clearer"><!-- --></span>';
1792 $content .= \html_writer::end_tag('div')."\n";
1793 break;
1794 case 'day':
1795 $days = calendar_get_days();
1797 $prevtimestamp = strtotime('-1 day', $time);
1798 $nexttimestamp = strtotime('+1 day', $time);
1800 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1801 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1803 $prevname = $days[$prevdate['wday']]['fullname'];
1804 $nextname = $days[$nextdate['wday']]['fullname'];
1805 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&amp;', false, false,
1806 false, false, $prevtimestamp);
1807 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&amp;', false, false, false,
1808 false, $nexttimestamp);
1810 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1811 $content .= $prevlink;
1812 $content .= '<span class="hide"> | </span><span class="current">' .userdate($time,
1813 get_string('strftimedaydate')) . '</span>';
1814 $content .= '<span class="hide"> | </span>' . $nextlink;
1815 $content .= "<span class=\"clearer\"><!-- --></span>";
1816 $content .= \html_writer::end_tag('div') . "\n";
1818 break;
1821 return $content;
1825 * Return the representation day.
1827 * @param int $tstamp Timestamp in GMT
1828 * @param int|bool $now current Unix timestamp
1829 * @param bool $usecommonwords
1830 * @return string the formatted date/time
1832 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1833 static $shortformat;
1835 if (empty($shortformat)) {
1836 $shortformat = get_string('strftimedayshort');
1839 if ($now === false) {
1840 $now = time();
1843 // To have it in one place, if a change is needed.
1844 $formal = userdate($tstamp, $shortformat);
1846 $datestamp = usergetdate($tstamp);
1847 $datenow = usergetdate($now);
1849 if ($usecommonwords == false) {
1850 // We don't want words, just a date.
1851 return $formal;
1852 } else if ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1853 return get_string('today', 'calendar');
1854 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1855 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12
1856 && $datenow['yday'] == 1)) {
1857 return get_string('yesterday', 'calendar');
1858 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1859 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12
1860 && $datestamp['yday'] == 1)) {
1861 return get_string('tomorrow', 'calendar');
1862 } else {
1863 return $formal;
1868 * return the formatted representation time.
1871 * @param int $time the timestamp in UTC, as obtained from the database
1872 * @return string the formatted date/time
1874 function calendar_time_representation($time) {
1875 static $langtimeformat = null;
1877 if ($langtimeformat === null) {
1878 $langtimeformat = get_string('strftimetime');
1881 $timeformat = get_user_preferences('calendar_timeformat');
1882 if (empty($timeformat)) {
1883 $timeformat = get_config(null, 'calendar_site_timeformat');
1886 // Allow language customization of selected time format.
1887 if ($timeformat === CALENDAR_TF_12) {
1888 $timeformat = get_string('strftimetime12', 'langconfig');
1889 } else if ($timeformat === CALENDAR_TF_24) {
1890 $timeformat = get_string('strftimetime24', 'langconfig');
1893 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
1897 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1899 * @param string|moodle_url $linkbase
1900 * @param int $d The number of the day.
1901 * @param int $m The number of the month.
1902 * @param int $y The number of the year.
1903 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1904 * $m and $y are kept for backwards compatibility.
1905 * @return moodle_url|null $linkbase
1907 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1908 if (empty($linkbase)) {
1909 return null;
1912 if (!($linkbase instanceof \moodle_url)) {
1913 $linkbase = new \moodle_url($linkbase);
1916 $linkbase->param('time', calendar_get_timestamp($d, $m, $y, $time));
1918 return $linkbase;
1922 * Build and return a previous month HTML link, with an arrow.
1924 * @param string $text The text label.
1925 * @param string|moodle_url $linkbase The URL stub.
1926 * @param int $d The number of the date.
1927 * @param int $m The number of the month.
1928 * @param int $y year The number of the year.
1929 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1930 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1931 * $m and $y are kept for backwards compatibility.
1932 * @return string HTML string.
1934 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1935 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1937 if (empty($href)) {
1938 return $text;
1941 $attrs = [
1942 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1943 'data-drop-zone' => 'nav-link',
1946 return link_arrow_left($text, $href->out(false), $accesshide, 'previous', $attrs);
1950 * Build and return a next month HTML link, with an arrow.
1952 * @param string $text The text label.
1953 * @param string|moodle_url $linkbase The URL stub.
1954 * @param int $d the number of the Day
1955 * @param int $m The number of the month.
1956 * @param int $y The number of the year.
1957 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1958 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1959 * $m and $y are kept for backwards compatibility.
1960 * @return string HTML string.
1962 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1963 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1965 if (empty($href)) {
1966 return $text;
1969 $attrs = [
1970 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1971 'data-drop-zone' => 'nav-link',
1974 return link_arrow_right($text, $href->out(false), $accesshide, 'next', $attrs);
1978 * Return the number of days in month.
1980 * @param int $month the number of the month.
1981 * @param int $year the number of the year
1982 * @return int
1984 function calendar_days_in_month($month, $year) {
1985 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1986 return $calendartype->get_num_days_in_month($year, $month);
1990 * Get the next following month.
1992 * @param int $month the number of the month.
1993 * @param int $year the number of the year.
1994 * @return array the following month
1996 function calendar_add_month($month, $year) {
1997 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1998 return $calendartype->get_next_month($year, $month);
2002 * Get the previous month.
2004 * @param int $month the number of the month.
2005 * @param int $year the number of the year.
2006 * @return array previous month
2008 function calendar_sub_month($month, $year) {
2009 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2010 return $calendartype->get_prev_month($year, $month);
2014 * Get per-day basis events
2016 * @param array $events list of events
2017 * @param int $month the number of the month
2018 * @param int $year the number of the year
2019 * @param array $eventsbyday event on specific day
2020 * @param array $durationbyday duration of the event in days
2021 * @param array $typesbyday event type (eg: site, course, user, or group)
2022 * @param array $courses list of courses
2023 * @return void
2025 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
2026 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2028 $eventsbyday = array();
2029 $typesbyday = array();
2030 $durationbyday = array();
2032 if ($events === false) {
2033 return;
2036 foreach ($events as $event) {
2037 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
2038 if ($event->timeduration) {
2039 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
2040 } else {
2041 $enddate = $startdate;
2044 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair.
2045 if (!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) &&
2046 ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
2047 continue;
2050 $eventdaystart = intval($startdate['mday']);
2052 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2053 // Give the event to its day.
2054 $eventsbyday[$eventdaystart][] = $event->id;
2056 // Mark the day as having such an event.
2057 if ($event->courseid == SITEID && $event->groupid == 0) {
2058 $typesbyday[$eventdaystart]['startsite'] = true;
2059 // Set event class for site event.
2060 $events[$event->id]->class = 'calendar_event_site';
2061 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
2062 $typesbyday[$eventdaystart]['startcourse'] = true;
2063 // Set event class for course event.
2064 $events[$event->id]->class = 'calendar_event_course';
2065 } else if ($event->groupid) {
2066 $typesbyday[$eventdaystart]['startgroup'] = true;
2067 // Set event class for group event.
2068 $events[$event->id]->class = 'calendar_event_group';
2069 } else if ($event->userid) {
2070 $typesbyday[$eventdaystart]['startuser'] = true;
2071 // Set event class for user event.
2072 $events[$event->id]->class = 'calendar_event_user';
2076 if ($event->timeduration == 0) {
2077 // Proceed with the next.
2078 continue;
2081 // The event starts on $month $year or before.
2082 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2083 $lowerbound = intval($startdate['mday']);
2084 } else {
2085 $lowerbound = 0;
2088 // Also, it ends on $month $year or later.
2089 if ($enddate['mon'] == $month && $enddate['year'] == $year) {
2090 $upperbound = intval($enddate['mday']);
2091 } else {
2092 $upperbound = calendar_days_in_month($month, $year);
2095 // Mark all days between $lowerbound and $upperbound (inclusive) as duration.
2096 for ($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
2097 $durationbyday[$i][] = $event->id;
2098 if ($event->courseid == SITEID && $event->groupid == 0) {
2099 $typesbyday[$i]['durationsite'] = true;
2100 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
2101 $typesbyday[$i]['durationcourse'] = true;
2102 } else if ($event->groupid) {
2103 $typesbyday[$i]['durationgroup'] = true;
2104 } else if ($event->userid) {
2105 $typesbyday[$i]['durationuser'] = true;
2110 return;
2114 * Returns the courses to load events for.
2116 * @param array $courseeventsfrom An array of courses to load calendar events for
2117 * @param bool $ignorefilters specify the use of filters, false is set as default
2118 * @param stdClass $user The user object. This defaults to the global $USER object.
2119 * @return array An array of courses, groups, and user to load calendar events for based upon filters
2121 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false, stdClass $user = null) {
2122 global $CFG, $USER;
2124 if (is_null($user)) {
2125 $user = $USER;
2128 $courses = array();
2129 $userid = false;
2130 $group = false;
2132 // Get the capabilities that allow seeing group events from all groups.
2133 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
2135 $isvaliduser = !empty($user->id);
2137 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE, $user)) {
2138 $courses = array_keys($courseeventsfrom);
2140 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_SITE, $user)) {
2141 $courses[] = SITEID;
2143 $courses = array_unique($courses);
2144 sort($courses);
2146 if (!empty($courses) && in_array(SITEID, $courses)) {
2147 // Sort courses for consistent colour highlighting.
2148 // Effectively ignoring SITEID as setting as last course id.
2149 $key = array_search(SITEID, $courses);
2150 unset($courses[$key]);
2151 $courses[] = SITEID;
2154 if ($ignorefilters || ($isvaliduser && calendar_show_event_type(CALENDAR_EVENT_USER, $user))) {
2155 $userid = $user->id;
2158 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP, $user) || $ignorefilters)) {
2160 if (count($courseeventsfrom) == 1) {
2161 $course = reset($courseeventsfrom);
2162 if (has_any_capability($allgroupscaps, \context_course::instance($course->id))) {
2163 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
2164 $group = array_keys($coursegroups);
2167 if ($group === false) {
2168 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, \context_system::instance())) {
2169 $group = true;
2170 } else if ($isvaliduser) {
2171 $groupids = array();
2172 foreach ($courseeventsfrom as $courseid => $course) {
2173 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2174 // If this course has groups, show events from all of those related to the current user.
2175 $coursegroups = groups_get_user_groups($course->id, $user->id);
2176 $groupids = array_merge($groupids, $coursegroups['0']);
2179 if (!empty($groupids)) {
2180 $group = $groupids;
2185 if (empty($courses)) {
2186 $courses = false;
2189 return array($courses, $group, $userid);
2193 * Can current user manage a non user event in system context.
2195 * @param calendar_event|stdClass $event event object
2196 * @return boolean
2198 function calendar_can_manage_non_user_event_in_system($event) {
2199 $sitecontext = \context_system::instance();
2200 $isuserevent = $event->eventtype == 'user';
2201 $canmanageentries = has_capability('moodle/calendar:manageentries', $sitecontext);
2202 // If user has manageentries at site level and it's not user event, return true.
2203 if ($canmanageentries && !$isuserevent) {
2204 return true;
2207 return false;
2211 * Return the capability for viewing a calendar event.
2213 * @param calendar_event $event event object
2214 * @return boolean
2216 function calendar_view_event_allowed(calendar_event $event) {
2217 global $USER;
2219 // Anyone can see site events.
2220 if ($event->courseid && $event->courseid == SITEID) {
2221 return true;
2224 if (calendar_can_manage_non_user_event_in_system($event)) {
2225 return true;
2228 if (!empty($event->groupid)) {
2229 // If it is a group event we need to be able to manage events in the course, or be in the group.
2230 if (has_capability('moodle/calendar:manageentries', $event->context) ||
2231 has_capability('moodle/calendar:managegroupentries', $event->context)) {
2232 return true;
2235 $mycourses = enrol_get_my_courses('id');
2236 return isset($mycourses[$event->courseid]) && groups_is_member($event->groupid);
2237 } else if ($event->modulename) {
2238 // If this is a module event we need to be able to see the module.
2239 $coursemodules = [];
2240 $courseid = 0;
2241 // Override events do not have the courseid set.
2242 if ($event->courseid) {
2243 $courseid = $event->courseid;
2244 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2245 } else {
2246 $cmraw = get_coursemodule_from_instance($event->modulename, $event->instance, 0, false, MUST_EXIST);
2247 $courseid = $cmraw->course;
2248 $coursemodules = get_fast_modinfo($cmraw->course)->instances;
2250 $hasmodule = isset($coursemodules[$event->modulename]);
2251 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2253 // If modinfo doesn't know about the module, return false to be safe.
2254 if (!$hasmodule || !$hasinstance) {
2255 return false;
2258 // Must be able to see the course and the module - MDL-59304.
2259 $cm = $coursemodules[$event->modulename][$event->instance];
2260 if (!$cm->uservisible) {
2261 return false;
2263 $mycourses = enrol_get_my_courses('id');
2264 return isset($mycourses[$courseid]);
2265 } else if ($event->categoryid) {
2266 // If this is a category we need to be able to see the category.
2267 $cat = \core_course_category::get($event->categoryid, IGNORE_MISSING);
2268 if (!$cat) {
2269 return false;
2271 return true;
2272 } else if (!empty($event->courseid)) {
2273 // If it is a course event we need to be able to manage events in the course, or be in the course.
2274 if (has_capability('moodle/calendar:manageentries', $event->context)) {
2275 return true;
2278 return can_access_course(get_course($event->courseid));
2279 } else if ($event->userid) {
2280 return calendar_can_manage_user_event($event);
2281 } else {
2282 throw new moodle_exception('unknown event type');
2285 return false;
2289 * Return the capability for editing calendar event.
2291 * @param calendar_event $event event object
2292 * @param bool $manualedit is the event being edited manually by the user
2293 * @return bool capability to edit event
2295 function calendar_edit_event_allowed($event, $manualedit = false) {
2296 global $USER, $DB;
2298 // Must be logged in.
2299 if (!isloggedin()) {
2300 return false;
2303 // Can not be using guest account.
2304 if (isguestuser()) {
2305 return false;
2308 if ($manualedit && !empty($event->modulename)) {
2309 $hascallback = component_callback_exists(
2310 'mod_' . $event->modulename,
2311 'core_calendar_event_timestart_updated'
2314 if (!$hascallback) {
2315 // If the activity hasn't implemented the correct callback
2316 // to handle changes to it's events then don't allow any
2317 // manual changes to them.
2318 return false;
2321 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2322 $hasmodule = isset($coursemodules[$event->modulename]);
2323 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2325 // If modinfo doesn't know about the module, return false to be safe.
2326 if (!$hasmodule || !$hasinstance) {
2327 return false;
2330 $coursemodule = $coursemodules[$event->modulename][$event->instance];
2331 $context = context_module::instance($coursemodule->id);
2332 // This is the capability that allows a user to modify the activity
2333 // settings. Since the activity generated this event we need to check
2334 // that the current user has the same capability before allowing them
2335 // to update the event because the changes to the event will be
2336 // reflected within the activity.
2337 return has_capability('moodle/course:manageactivities', $context);
2340 if ($manualedit && !empty($event->component)) {
2341 // TODO possibly we can later add a callback similar to core_calendar_event_timestart_updated in the modules.
2342 return false;
2345 // You cannot edit URL based calendar subscription events presently.
2346 if (!empty($event->subscriptionid)) {
2347 if (!empty($event->subscription->url)) {
2348 // This event can be updated externally, so it cannot be edited.
2349 return false;
2353 if (calendar_can_manage_non_user_event_in_system($event)) {
2354 return true;
2357 // If groupid is set, it's definitely a group event.
2358 if (!empty($event->groupid)) {
2359 // Allow users to add/edit group events if -
2360 // 1) They have manageentries for the course OR
2361 // 2) They have managegroupentries AND are in the group.
2362 $group = $DB->get_record('groups', array('id' => $event->groupid));
2363 return $group && (
2364 has_capability('moodle/calendar:manageentries', $event->context) ||
2365 (has_capability('moodle/calendar:managegroupentries', $event->context)
2366 && groups_is_member($event->groupid)));
2367 } else if (!empty($event->courseid)) {
2368 // If groupid is not set, but course is set, it's definitely a course event.
2369 return has_capability('moodle/calendar:manageentries', $event->context);
2370 } else if (!empty($event->categoryid)) {
2371 // If groupid is not set, but category is set, it's definitely a category event.
2372 return has_capability('moodle/calendar:manageentries', $event->context);
2373 } else if (!empty($event->userid) && $event->userid == $USER->id) {
2374 // If course is not set, but userid id set, it's a user event.
2375 return (has_capability('moodle/calendar:manageownentries',
2376 context_user::instance($event->userid)));
2377 } else if (!empty($event->userid)) {
2378 return calendar_can_manage_user_event($event);
2381 return false;
2385 * Can current user edit/delete/add an user event?
2387 * @param calendar_event|stdClass $event event object
2388 * @return bool
2390 function calendar_can_manage_user_event($event): bool {
2391 global $USER;
2393 if (!($event instanceof \calendar_event)) {
2394 $event = new \calendar_event(clone($event));
2397 $canmanage = has_capability('moodle/calendar:manageentries', $event->context);
2398 $canmanageown = has_capability('moodle/calendar:manageownentries', $event->context);
2399 $ismyevent = $event->userid == $USER->id;
2400 $isadminevent = is_siteadmin($event->userid);
2402 if ($canmanageown && $ismyevent) {
2403 return true;
2406 // In site context, user must have login and calendar:manageentries permissions
2407 // ... to manage other user's events except admin users.
2408 if ($canmanage && !$isadminevent) {
2409 return true;
2412 return false;
2416 * Return the capability for deleting a calendar event.
2418 * @param calendar_event $event The event object
2419 * @return bool Whether the user has permission to delete the event or not.
2421 function calendar_delete_event_allowed($event) {
2422 // Only allow delete if you have capabilities and it is not an module or component event.
2423 return (calendar_edit_event_allowed($event) && empty($event->modulename) && empty($event->component));
2427 * Returns the default courses to display on the calendar when there isn't a specific
2428 * course to display.
2430 * @param int $courseid (optional) If passed, an additional course can be returned for admins (the current course).
2431 * @param string $fields Comma separated list of course fields to return.
2432 * @param bool $canmanage If true, this will return the list of courses the user can create events in, rather
2433 * than the list of courses they see events from (an admin can always add events in a course
2434 * calendar, even if they are not enrolled in the course).
2435 * @param int $userid (optional) The user which this function returns the default courses for.
2436 * By default the current user.
2437 * @return array $courses Array of courses to display
2439 function calendar_get_default_courses($courseid = null, $fields = '*', $canmanage = false, int $userid = null) {
2440 global $CFG, $USER;
2442 if (!$userid) {
2443 if (!isloggedin()) {
2444 return array();
2446 $userid = $USER->id;
2449 if ((!empty($CFG->calendar_adminseesall) || $canmanage) &&
2450 has_capability('moodle/calendar:manageentries', context_system::instance(), $userid)) {
2452 // Add a c. prefix to every field as expected by get_courses function.
2453 $fieldlist = explode(',', $fields);
2455 $prefixedfields = array_map(function($value) {
2456 return 'c.' . trim(strtolower($value));
2457 }, $fieldlist);
2459 $courses = get_courses('all', 'c.shortname', implode(',', $prefixedfields));
2460 } else {
2461 $courses = enrol_get_users_courses($userid, true, $fields, 'c.shortname');
2464 if ($courseid && $courseid != SITEID) {
2465 if (empty($courses[$courseid]) && has_capability('moodle/calendar:manageentries', context_system::instance(), $userid)) {
2466 // Allow a site admin to see calendars from courses he is not enrolled in.
2467 // This will come from $COURSE.
2468 $courses[$courseid] = get_course($courseid);
2472 return $courses;
2476 * Get event format time.
2478 * @param calendar_event $event event object
2479 * @param int $now current time in gmt
2480 * @param array $linkparams list of params for event link
2481 * @param bool $usecommonwords the words as formatted date/time.
2482 * @param int $showtime determine the show time GMT timestamp
2483 * @return string $eventtime link/string for event time
2485 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
2486 $starttime = $event->timestart;
2487 $endtime = $event->timestart + $event->timeduration;
2489 if (empty($linkparams) || !is_array($linkparams)) {
2490 $linkparams = array();
2493 $linkparams['view'] = 'day';
2495 // OK, now to get a meaningful display.
2496 // Check if there is a duration for this event.
2497 if ($event->timeduration) {
2498 // Get the midnight of the day the event will start.
2499 $usermidnightstart = usergetmidnight($starttime);
2500 // Get the midnight of the day the event will end.
2501 $usermidnightend = usergetmidnight($endtime);
2502 // Check if we will still be on the same day.
2503 if ($usermidnightstart == $usermidnightend) {
2504 // Check if we are running all day.
2505 if ($event->timeduration == DAYSECS) {
2506 $time = get_string('allday', 'calendar');
2507 } else { // Specify the time we will be running this from.
2508 $datestart = calendar_time_representation($starttime);
2509 $dateend = calendar_time_representation($endtime);
2510 $time = $datestart . ' <strong>&raquo;</strong> ' . $dateend;
2513 // Set printable representation.
2514 if (!$showtime) {
2515 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2516 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2517 $eventtime = \html_writer::link($url, $day) . ', ' . $time;
2518 } else {
2519 $eventtime = $time;
2521 } else { // It must spans two or more days.
2522 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
2523 if ($showtime == $usermidnightstart) {
2524 $daystart = '';
2526 $timestart = calendar_time_representation($event->timestart);
2527 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
2528 if ($showtime == $usermidnightend) {
2529 $dayend = '';
2531 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
2533 // Set printable representation.
2534 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2535 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2536 $eventtime = $timestart . ' <strong>&raquo;</strong> ' . \html_writer::link($url, $dayend) . $timeend;
2537 } else {
2538 // The event is in the future, print start and end links.
2539 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2540 $eventtime = \html_writer::link($url, $daystart) . $timestart . ' <strong>&raquo;</strong> ';
2542 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2543 $eventtime .= \html_writer::link($url, $dayend) . $timeend;
2546 } else { // There is no time duration.
2547 $time = calendar_time_representation($event->timestart);
2548 // Set printable representation.
2549 if (!$showtime) {
2550 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2551 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2552 $eventtime = \html_writer::link($url, $day) . ', ' . trim($time);
2553 } else {
2554 $eventtime = $time;
2558 // Check if It has expired.
2559 if ($event->timestart + $event->timeduration < $now) {
2560 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2563 return $eventtime;
2567 * Format event location property
2569 * @param calendar_event $event
2570 * @return string
2572 function calendar_format_event_location(calendar_event $event): string {
2573 $location = format_text($event->location, FORMAT_PLAIN, ['context' => $event->context]);
2575 // If it looks like a link, convert it to one.
2576 if (preg_match('/^https?:\/\//i', $location) && clean_param($location, PARAM_URL)) {
2577 $location = \html_writer::link($location, $location, [
2578 'title' => get_string('eventnamelocation', 'core_calendar', ['name' => $event->name, 'location' => $location]),
2582 return $location;
2586 * Checks to see if the requested type of event should be shown for the given user.
2588 * @param int $type The type to check the display for (default is to display all)
2589 * @param stdClass|int|null $user The user to check for - by default the current user
2590 * @return bool True if the tyep should be displayed false otherwise
2592 function calendar_show_event_type($type, $user = null) {
2593 $default = CALENDAR_EVENT_SITE + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
2595 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2596 global $SESSION;
2597 if (!isset($SESSION->calendarshoweventtype)) {
2598 $SESSION->calendarshoweventtype = $default;
2600 return $SESSION->calendarshoweventtype & $type;
2601 } else {
2602 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2607 * Sets the display of the event type given $display.
2609 * If $display = true the event type will be shown.
2610 * If $display = false the event type will NOT be shown.
2611 * If $display = null the current value will be toggled and saved.
2613 * @param int $type object of CALENDAR_EVENT_XXX
2614 * @param bool $display option to display event type
2615 * @param stdClass|int $user moodle user object or id, null means current user
2617 function calendar_set_event_type_display($type, $display = null, $user = null) {
2618 $persist = get_user_preferences('calendar_persistflt', 0, $user);
2619 $default = CALENDAR_EVENT_SITE + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP
2620 + CALENDAR_EVENT_USER + CALENDAR_EVENT_COURSECAT;
2621 if ($persist === 0) {
2622 global $SESSION;
2623 if (!isset($SESSION->calendarshoweventtype)) {
2624 $SESSION->calendarshoweventtype = $default;
2626 $preference = $SESSION->calendarshoweventtype;
2627 } else {
2628 $preference = get_user_preferences('calendar_savedflt', $default, $user);
2630 $current = $preference & $type;
2631 if ($display === null) {
2632 $display = !$current;
2634 if ($display && !$current) {
2635 $preference += $type;
2636 } else if (!$display && $current) {
2637 $preference -= $type;
2639 if ($persist === 0) {
2640 $SESSION->calendarshoweventtype = $preference;
2641 } else {
2642 if ($preference == $default) {
2643 unset_user_preference('calendar_savedflt', $user);
2644 } else {
2645 set_user_preference('calendar_savedflt', $preference, $user);
2651 * Get calendar's allowed types.
2653 * @param stdClass $allowed list of allowed edit for event type
2654 * @param stdClass|int $course object of a course or course id
2655 * @param array $groups array of groups for the given course
2656 * @param stdClass|int $category object of a category
2658 function calendar_get_allowed_types(&$allowed, $course = null, $groups = null, $category = null) {
2659 global $USER, $DB;
2661 $allowed = new \stdClass();
2662 $allowed->user = has_capability('moodle/calendar:manageownentries', \context_system::instance());
2663 $allowed->groups = false;
2664 $allowed->courses = false;
2665 $allowed->categories = false;
2666 $allowed->site = has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID));
2667 $getgroupsfunc = function($course, $context, $user) use ($groups) {
2668 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2669 if (has_capability('moodle/site:accessallgroups', $context)) {
2670 return is_null($groups) ? groups_get_all_groups($course->id) : $groups;
2671 } else {
2672 if (is_null($groups)) {
2673 return groups_get_all_groups($course->id, $user->id);
2674 } else {
2675 return array_filter($groups, function($group) use ($user) {
2676 return isset($group->members[$user->id]);
2682 return false;
2685 if (!empty($course)) {
2686 if (!is_object($course)) {
2687 $course = $DB->get_record('course', array('id' => $course), 'id, groupmode, groupmodeforce', MUST_EXIST);
2689 if ($course->id != SITEID) {
2690 $coursecontext = \context_course::instance($course->id);
2691 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
2693 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2694 $allowed->courses = array($course->id => 1);
2695 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2696 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
2697 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2702 if (!empty($category)) {
2703 $catcontext = \context_coursecat::instance($category->id);
2704 if (has_capability('moodle/category:manage', $catcontext)) {
2705 $allowed->categories = [$category->id => 1];
2711 * See if user can add calendar entries at all used to print the "New Event" button.
2713 * @param stdClass $course object of a course or course id
2714 * @return bool has the capability to add at least one event type
2716 function calendar_user_can_add_event($course) {
2717 if (!isloggedin() || isguestuser()) {
2718 return false;
2721 calendar_get_allowed_types($allowed, $course);
2723 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->categories || $allowed->site);
2727 * Check wether the current user is permitted to add events.
2729 * @param stdClass $event object of event
2730 * @return bool has the capability to add event
2732 function calendar_add_event_allowed($event) {
2733 global $USER, $DB;
2735 // Can not be using guest account.
2736 if (!isloggedin() or isguestuser()) {
2737 return false;
2740 if (calendar_can_manage_non_user_event_in_system($event)) {
2741 return true;
2744 switch ($event->eventtype) {
2745 case 'category':
2746 return has_capability('moodle/category:manage', $event->context);
2747 case 'course':
2748 return has_capability('moodle/calendar:manageentries', $event->context);
2749 case 'group':
2750 // Allow users to add/edit group events if -
2751 // 1) They have manageentries (= entries for whole course).
2752 // 2) They have managegroupentries AND are in the group.
2753 $group = $DB->get_record('groups', array('id' => $event->groupid));
2754 return $group && (
2755 has_capability('moodle/calendar:manageentries', $event->context) ||
2756 (has_capability('moodle/calendar:managegroupentries', $event->context)
2757 && groups_is_member($event->groupid)));
2758 case 'user':
2759 return calendar_can_manage_user_event($event);
2760 case 'site':
2761 return has_capability('moodle/calendar:manageentries', $event->context);
2762 default:
2763 return has_capability('moodle/calendar:manageentries', $event->context);
2768 * Returns option list for the poll interval setting.
2770 * @return array An array of poll interval options. Interval => description.
2772 function calendar_get_pollinterval_choices() {
2773 return array(
2774 '0' => get_string('never', 'calendar'),
2775 HOURSECS => get_string('hourly', 'calendar'),
2776 DAYSECS => get_string('daily', 'calendar'),
2777 WEEKSECS => get_string('weekly', 'calendar'),
2778 '2628000' => get_string('monthly', 'calendar'),
2779 YEARSECS => get_string('annually', 'calendar')
2784 * Returns option list of available options for the calendar event type, given the current user and course.
2786 * @param int $courseid The id of the course
2787 * @return array An array containing the event types the user can create.
2789 function calendar_get_eventtype_choices($courseid) {
2790 $choices = array();
2791 $allowed = new \stdClass;
2792 calendar_get_allowed_types($allowed, $courseid);
2794 if ($allowed->user) {
2795 $choices['user'] = get_string('userevents', 'calendar');
2797 if ($allowed->site) {
2798 $choices['site'] = get_string('siteevents', 'calendar');
2800 if (!empty($allowed->courses)) {
2801 $choices['course'] = get_string('courseevents', 'calendar');
2803 if (!empty($allowed->categories)) {
2804 $choices['category'] = get_string('categoryevents', 'calendar');
2806 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2807 $choices['group'] = get_string('group');
2810 return array($choices, $allowed->groups);
2814 * Add an iCalendar subscription to the database.
2816 * @param stdClass $sub The subscription object (e.g. from the form)
2817 * @return int The insert ID, if any.
2819 function calendar_add_subscription($sub) {
2820 global $DB, $USER, $SITE;
2822 // Undo the form definition work around to allow us to have two different
2823 // course selectors present depending on which event type the user selects.
2824 if (!empty($sub->groupcourseid)) {
2825 $sub->courseid = $sub->groupcourseid;
2826 unset($sub->groupcourseid);
2829 // Default course id if none is set.
2830 if (empty($sub->courseid)) {
2831 if ($sub->eventtype === 'site') {
2832 $sub->courseid = SITEID;
2833 } else {
2834 $sub->courseid = 0;
2838 if ($sub->eventtype === 'site') {
2839 $sub->courseid = $SITE->id;
2840 } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
2841 $sub->courseid = $sub->courseid;
2842 } else if ($sub->eventtype === 'category') {
2843 $sub->categoryid = $sub->categoryid;
2844 } else {
2845 // User events.
2846 $sub->courseid = 0;
2848 $sub->userid = $USER->id;
2850 // File subscriptions never update.
2851 if (empty($sub->url)) {
2852 $sub->pollinterval = 0;
2855 if (!empty($sub->name)) {
2856 if (empty($sub->id)) {
2857 $id = $DB->insert_record('event_subscriptions', $sub);
2858 // We cannot cache the data here because $sub is not complete.
2859 $sub->id = $id;
2860 // Trigger event, calendar subscription added.
2861 $eventparams = array('objectid' => $sub->id,
2862 'context' => calendar_get_calendar_context($sub),
2863 'other' => array(
2864 'eventtype' => $sub->eventtype,
2867 switch ($sub->eventtype) {
2868 case 'category':
2869 $eventparams['other']['categoryid'] = $sub->categoryid;
2870 break;
2871 case 'course':
2872 $eventparams['other']['courseid'] = $sub->courseid;
2873 break;
2874 case 'group':
2875 $eventparams['other']['courseid'] = $sub->courseid;
2876 $eventparams['other']['groupid'] = $sub->groupid;
2877 break;
2878 default:
2879 $eventparams['other']['courseid'] = $sub->courseid;
2882 $event = \core\event\calendar_subscription_created::create($eventparams);
2883 $event->trigger();
2884 return $id;
2885 } else {
2886 // Why are we doing an update here?
2887 calendar_update_subscription($sub);
2888 return $sub->id;
2890 } else {
2891 throw new \moodle_exception('errorbadsubscription', 'importcalendar');
2896 * Add an iCalendar event to the Moodle calendar.
2898 * @param stdClass $event The RFC-2445 iCalendar event
2899 * @param int $unused Deprecated
2900 * @param int $subscriptionid The iCalendar subscription ID
2901 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2902 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2903 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2905 function calendar_add_icalendar_event($event, $unused, $subscriptionid, $timezone='UTC') {
2906 global $DB;
2908 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2909 if (empty($event->properties['SUMMARY'])) {
2910 return 0;
2913 $name = $event->properties['SUMMARY'][0]->value;
2914 $name = str_replace('\n', '<br />', $name);
2915 $name = str_replace('\\', '', $name);
2916 $name = preg_replace('/\s+/u', ' ', $name);
2918 $eventrecord = new \stdClass;
2919 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
2921 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2922 $description = '';
2923 } else {
2924 $description = $event->properties['DESCRIPTION'][0]->value;
2925 $description = clean_param($description, PARAM_NOTAGS);
2926 $description = str_replace('\n', '<br />', $description);
2927 $description = str_replace('\\', '', $description);
2928 $description = preg_replace('/\s+/u', ' ', $description);
2930 $eventrecord->description = $description;
2932 // Probably a repeating event with RRULE etc. TODO: skip for now.
2933 if (empty($event->properties['DTSTART'][0]->value)) {
2934 return 0;
2937 if (isset($event->properties['DTSTART'][0]->parameters['TZID'])) {
2938 $tz = $event->properties['DTSTART'][0]->parameters['TZID'];
2939 } else {
2940 $tz = $timezone;
2942 $tz = \core_date::normalise_timezone($tz);
2943 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value . ' ' . $tz);
2944 if (empty($event->properties['DTEND'])) {
2945 $eventrecord->timeduration = 0; // No duration if no end time specified.
2946 } else {
2947 if (isset($event->properties['DTEND'][0]->parameters['TZID'])) {
2948 $endtz = $event->properties['DTEND'][0]->parameters['TZID'];
2949 } else {
2950 $endtz = $timezone;
2952 $endtz = \core_date::normalise_timezone($endtz);
2953 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value . ' ' . $endtz) - $eventrecord->timestart;
2956 // Check to see if it should be treated as an all day event.
2957 if ($eventrecord->timeduration == DAYSECS) {
2958 // Check to see if the event started at Midnight on the imported calendar.
2959 date_default_timezone_set($timezone);
2960 if (date('H:i:s', $eventrecord->timestart) === "00:00:00") {
2961 // This event should be an all day event. This is not correct, we don't do anything differently for all day events.
2962 // See MDL-56227.
2963 $eventrecord->timeduration = 0;
2965 \core_date::set_default_server_timezone();
2968 $eventrecord->location = empty($event->properties['LOCATION'][0]->value) ? '' :
2969 trim(str_replace('\\', '', $event->properties['LOCATION'][0]->value));
2970 $eventrecord->uuid = $event->properties['UID'][0]->value;
2971 $eventrecord->timemodified = time();
2973 // Add the iCal subscription details if required.
2974 // We should never do anything with an event without a subscription reference.
2975 $sub = calendar_get_subscription($subscriptionid);
2976 $eventrecord->subscriptionid = $subscriptionid;
2977 $eventrecord->userid = $sub->userid;
2978 $eventrecord->groupid = $sub->groupid;
2979 $eventrecord->courseid = $sub->courseid;
2980 $eventrecord->categoryid = $sub->categoryid;
2981 $eventrecord->eventtype = $sub->eventtype;
2983 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid,
2984 'subscriptionid' => $eventrecord->subscriptionid))) {
2986 // Compare iCal event data against the moodle event to see if something has changed.
2987 $result = array_diff((array) $eventrecord, (array) $updaterecord);
2989 // Unset timemodified field because it's always going to be different.
2990 unset($result['timemodified']);
2992 if (count($result)) {
2993 $eventrecord->id = $updaterecord->id;
2994 $return = CALENDAR_IMPORT_EVENT_UPDATED; // Update.
2995 } else {
2996 return CALENDAR_IMPORT_EVENT_SKIPPED;
2998 } else {
2999 $return = CALENDAR_IMPORT_EVENT_INSERTED; // Insert.
3002 if ($createdevent = \calendar_event::create($eventrecord, false)) {
3003 if (!empty($event->properties['RRULE'])) {
3004 // Repeating events.
3005 date_default_timezone_set($tz); // Change time zone to parse all events.
3006 $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
3007 $rrule->parse_rrule();
3008 $rrule->create_events($createdevent);
3009 \core_date::set_default_server_timezone(); // Change time zone back to what it was.
3011 return $return;
3012 } else {
3013 return 0;
3018 * Delete subscription and all related events.
3020 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
3022 function calendar_delete_subscription($subscription) {
3023 global $DB;
3025 if (!is_object($subscription)) {
3026 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST);
3029 // Delete subscription and related events.
3030 $DB->delete_records('event', array('subscriptionid' => $subscription->id));
3031 $DB->delete_records('event_subscriptions', array('id' => $subscription->id));
3032 \cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id));
3034 // Trigger event, calendar subscription deleted.
3035 $eventparams = array('objectid' => $subscription->id,
3036 'context' => calendar_get_calendar_context($subscription),
3037 'other' => array(
3038 'eventtype' => $subscription->eventtype,
3041 switch ($subscription->eventtype) {
3042 case 'category':
3043 $eventparams['other']['categoryid'] = $subscription->categoryid;
3044 break;
3045 case 'course':
3046 $eventparams['other']['courseid'] = $subscription->courseid;
3047 break;
3048 case 'group':
3049 $eventparams['other']['courseid'] = $subscription->courseid;
3050 $eventparams['other']['groupid'] = $subscription->groupid;
3051 break;
3052 default:
3053 $eventparams['other']['courseid'] = $subscription->courseid;
3055 $event = \core\event\calendar_subscription_deleted::create($eventparams);
3056 $event->trigger();
3060 * From a URL, fetch the calendar and return an iCalendar object.
3062 * @param string $url The iCalendar URL
3063 * @return iCalendar The iCalendar object
3065 function calendar_get_icalendar($url) {
3066 global $CFG;
3068 require_once($CFG->libdir . '/filelib.php');
3069 require_once($CFG->libdir . '/bennu/bennu.inc.php');
3071 $curl = new \curl();
3072 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
3073 $calendar = $curl->get($url);
3075 // Http code validation should actually be the job of curl class.
3076 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
3077 throw new \moodle_exception('errorinvalidicalurl', 'calendar');
3080 $ical = new \iCalendar();
3081 $ical->unserialize($calendar);
3083 return $ical;
3087 * Import events from an iCalendar object into a course calendar.
3089 * @param iCalendar $ical The iCalendar object.
3090 * @param int|null $subscriptionid The subscription ID.
3091 * @return array A log of the import progress, including errors.
3093 function calendar_import_events_from_ical(iCalendar $ical, int $subscriptionid = null): array {
3094 global $DB;
3096 $errors = [];
3097 $eventcount = 0;
3098 $updatecount = 0;
3099 $skippedcount = 0;
3100 $deletedcount = 0;
3102 // Large calendars take a while...
3103 if (!CLI_SCRIPT) {
3104 \core_php_time_limit::raise(300);
3107 // Start with a safe default timezone.
3108 $timezone = 'UTC';
3110 // Grab the timezone from the iCalendar file to be used later.
3111 if (isset($ical->properties['X-WR-TIMEZONE'][0]->value)) {
3112 $timezone = $ical->properties['X-WR-TIMEZONE'][0]->value;
3114 } else if (isset($ical->properties['PRODID'][0]->value)) {
3115 // If the timezone was not found, check to se if this is MS exchange / Office 365 which uses Windows timezones.
3116 if (strncmp($ical->properties['PRODID'][0]->value, 'Microsoft', 9) == 0) {
3117 if (isset($ical->components['VTIMEZONE'][0]->properties['TZID'][0]->value)) {
3118 $tzname = $ical->components['VTIMEZONE'][0]->properties['TZID'][0]->value;
3119 $timezone = IntlTimeZone::getIDForWindowsID($tzname);
3124 $icaluuids = [];
3125 foreach ($ical->components['VEVENT'] as $event) {
3126 $icaluuids[] = $event->properties['UID'][0]->value;
3127 $res = calendar_add_icalendar_event($event, null, $subscriptionid, $timezone);
3128 switch ($res) {
3129 case CALENDAR_IMPORT_EVENT_UPDATED:
3130 $updatecount++;
3131 break;
3132 case CALENDAR_IMPORT_EVENT_INSERTED:
3133 $eventcount++;
3134 break;
3135 case CALENDAR_IMPORT_EVENT_SKIPPED:
3136 $skippedcount++;
3137 break;
3138 case 0:
3139 if (empty($event->properties['SUMMARY'])) {
3140 $errors[] = '(' . get_string('notitle', 'calendar') . ')';
3141 } else {
3142 $errors[] = $event->properties['SUMMARY'][0]->value;
3144 break;
3148 $existing = $DB->get_field('event_subscriptions', 'lastupdated', ['id' => $subscriptionid]);
3149 if (!empty($existing)) {
3150 $eventsuuids = $DB->get_records_menu('event', ['subscriptionid' => $subscriptionid], '', 'id, uuid');
3152 $icaleventscount = count($icaluuids);
3153 $tobedeleted = [];
3154 if (count($eventsuuids) > $icaleventscount) {
3155 foreach ($eventsuuids as $eventid => $eventuuid) {
3156 if (!in_array($eventuuid, $icaluuids)) {
3157 $tobedeleted[] = $eventid;
3160 if (!empty($tobedeleted)) {
3161 $DB->delete_records_list('event', 'id', $tobedeleted);
3162 $deletedcount = count($tobedeleted);
3167 $result = [
3168 'eventsimported' => $eventcount,
3169 'eventsskipped' => $skippedcount,
3170 'eventsupdated' => $updatecount,
3171 'eventsdeleted' => $deletedcount,
3172 'haserror' => !empty($errors),
3173 'errors' => $errors,
3176 return $result;
3180 * Fetch a calendar subscription and update the events in the calendar.
3182 * @param int $subscriptionid The course ID for the calendar.
3183 * @return string A log of the import progress, including errors.
3185 function calendar_update_subscription_events($subscriptionid) {
3186 $sub = calendar_get_subscription($subscriptionid);
3188 // Don't update a file subscription.
3189 if (empty($sub->url)) {
3190 return 'File subscription not updated.';
3193 $ical = calendar_get_icalendar($sub->url);
3194 $return = calendar_import_events_from_ical($ical, $subscriptionid);
3195 $sub->lastupdated = time();
3197 calendar_update_subscription($sub);
3199 return $return;
3203 * Update a calendar subscription. Also updates the associated cache.
3205 * @param stdClass|array $subscription Subscription record.
3206 * @throws coding_exception If something goes wrong
3207 * @since Moodle 2.5
3209 function calendar_update_subscription($subscription) {
3210 global $DB;
3212 if (is_array($subscription)) {
3213 $subscription = (object)$subscription;
3215 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
3216 throw new \coding_exception('Cannot update a subscription without a valid id');
3219 $DB->update_record('event_subscriptions', $subscription);
3221 // Update cache.
3222 $cache = \cache::make('core', 'calendar_subscriptions');
3223 $cache->set($subscription->id, $subscription);
3225 // Trigger event, calendar subscription updated.
3226 $eventparams = array('userid' => $subscription->userid,
3227 'objectid' => $subscription->id,
3228 'context' => calendar_get_calendar_context($subscription),
3229 'other' => array(
3230 'eventtype' => $subscription->eventtype,
3233 switch ($subscription->eventtype) {
3234 case 'category':
3235 $eventparams['other']['categoryid'] = $subscription->categoryid;
3236 break;
3237 case 'course':
3238 $eventparams['other']['courseid'] = $subscription->courseid;
3239 break;
3240 case 'group':
3241 $eventparams['other']['courseid'] = $subscription->courseid;
3242 $eventparams['other']['groupid'] = $subscription->groupid;
3243 break;
3244 default:
3245 $eventparams['other']['courseid'] = $subscription->courseid;
3247 $event = \core\event\calendar_subscription_updated::create($eventparams);
3248 $event->trigger();
3252 * Checks to see if the user can edit a given subscription feed.
3254 * @param mixed $subscriptionorid Subscription object or id
3255 * @return bool true if current user can edit the subscription else false
3257 function calendar_can_edit_subscription($subscriptionorid) {
3258 global $USER;
3259 if (is_array($subscriptionorid)) {
3260 $subscription = (object)$subscriptionorid;
3261 } else if (is_object($subscriptionorid)) {
3262 $subscription = $subscriptionorid;
3263 } else {
3264 $subscription = calendar_get_subscription($subscriptionorid);
3267 $allowed = new \stdClass;
3268 $courseid = $subscription->courseid;
3269 $categoryid = $subscription->categoryid;
3270 $groupid = $subscription->groupid;
3271 $category = null;
3273 if (!empty($categoryid)) {
3274 $category = \core_course_category::get($categoryid);
3276 calendar_get_allowed_types($allowed, $courseid, null, $category);
3277 switch ($subscription->eventtype) {
3278 case 'user':
3279 return ($USER->id == $subscription->userid && $allowed->user);
3280 case 'course':
3281 if (isset($allowed->courses[$courseid])) {
3282 return $allowed->courses[$courseid];
3283 } else {
3284 return false;
3286 case 'category':
3287 if (isset($allowed->categories[$categoryid])) {
3288 return $allowed->categories[$categoryid];
3289 } else {
3290 return false;
3292 case 'site':
3293 return $allowed->site;
3294 case 'group':
3295 if (isset($allowed->groups[$groupid])) {
3296 return $allowed->groups[$groupid];
3297 } else {
3298 return false;
3300 default:
3301 return false;
3306 * Helper function to determine the context of a calendar subscription.
3307 * Subscriptions can be created in two contexts COURSE, or USER.
3309 * @param stdClass $subscription
3310 * @return context instance
3312 function calendar_get_calendar_context($subscription) {
3313 // Determine context based on calendar type.
3314 if ($subscription->eventtype === 'site') {
3315 $context = \context_course::instance(SITEID);
3316 } else if ($subscription->eventtype === 'group' || $subscription->eventtype === 'course') {
3317 $context = \context_course::instance($subscription->courseid);
3318 } else {
3319 $context = \context_user::instance($subscription->userid);
3321 return $context;
3325 * Implements callback user_preferences, lists preferences that users are allowed to update directly
3327 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3329 * @return array
3331 function core_calendar_user_preferences() {
3332 $preferences = [];
3333 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED, 'default' => '0',
3334 'choices' => array('0', CALENDAR_TF_12, CALENDAR_TF_24)
3336 $preferences['calendar_startwday'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3337 'choices' => array(0, 1, 2, 3, 4, 5, 6));
3338 $preferences['calendar_maxevents'] = array('type' => PARAM_INT, 'choices' => range(1, 20));
3339 $preferences['calendar_lookahead'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 365,
3340 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3341 $preferences['calendar_persistflt'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3342 'choices' => array(0, 1));
3343 return $preferences;
3347 * Get legacy calendar events
3349 * @param int $tstart Start time of time range for events
3350 * @param int $tend End time of time range for events
3351 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3352 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3353 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3354 * @param boolean $withduration whether only events starting within time range selected
3355 * or events in progress/already started selected as well
3356 * @param boolean $ignorehidden whether to select only visible events or all events
3357 * @param array $categories array of category ids and/or objects.
3358 * @param int $limitnum Number of events to fetch or zero to fetch all.
3360 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3362 function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses,
3363 $withduration = true, $ignorehidden = true, $categories = [], $limitnum = 0) {
3364 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3365 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3366 // parameters, but with the new API method, only null and arrays are accepted.
3367 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3368 // If parameter is true, return null.
3369 if ($param === true) {
3370 return null;
3373 // If parameter is false, return an empty array.
3374 if ($param === false) {
3375 return [];
3378 // If the parameter is a scalar value, enclose it in an array.
3379 if (!is_array($param)) {
3380 return [$param];
3383 // No normalisation required.
3384 return $param;
3385 }, [$users, $groups, $courses, $categories]);
3387 // If a single user is provided, we can use that for capability checks.
3388 // Otherwise current logged in user is used - See MDL-58768.
3389 if (is_array($userparam) && count($userparam) == 1) {
3390 \core_calendar\local\event\container::set_requesting_user($userparam[0]);
3392 $mapper = \core_calendar\local\event\container::get_event_mapper();
3393 $events = \core_calendar\local\api::get_events(
3394 $tstart,
3395 $tend,
3396 null,
3397 null,
3398 null,
3399 null,
3400 $limitnum,
3401 null,
3402 $userparam,
3403 $groupparam,
3404 $courseparam,
3405 $categoryparam,
3406 $withduration,
3407 $ignorehidden
3410 return array_reduce($events, function($carry, $event) use ($mapper) {
3411 return $carry + [$event->get_id() => $mapper->from_event_to_stdclass($event)];
3412 }, []);
3417 * Get the calendar view output.
3419 * @param \calendar_information $calendar The calendar being represented
3420 * @param string $view The type of calendar to have displayed
3421 * @param bool $includenavigation Whether to include navigation
3422 * @param bool $skipevents Whether to load the events or not
3423 * @param int $lookahead Overwrites site and users's lookahead setting.
3424 * @return array[array, string]
3426 function calendar_get_view(\calendar_information $calendar, $view, $includenavigation = true, bool $skipevents = false,
3427 ?int $lookahead = null) {
3428 global $PAGE, $CFG;
3430 $renderer = $PAGE->get_renderer('core_calendar');
3431 $type = \core_calendar\type_factory::get_calendar_instance();
3433 // Calculate the bounds of the month.
3434 $calendardate = $type->timestamp_to_date_array($calendar->time);
3436 $date = new \DateTime('now', core_date::get_user_timezone_object(99));
3437 $eventlimit = 0;
3439 if ($view === 'day') {
3440 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday']);
3441 $date->setTimestamp($tstart);
3442 $date->modify('+1 day');
3443 } else if ($view === 'upcoming' || $view === 'upcoming_mini') {
3444 // Number of days in the future that will be used to fetch events.
3445 if (!$lookahead) {
3446 if (isset($CFG->calendar_lookahead)) {
3447 $defaultlookahead = intval($CFG->calendar_lookahead);
3448 } else {
3449 $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD;
3451 $lookahead = get_user_preferences('calendar_lookahead', $defaultlookahead);
3454 // Maximum number of events to be displayed on upcoming view.
3455 $defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS;
3456 if (isset($CFG->calendar_maxevents)) {
3457 $defaultmaxevents = intval($CFG->calendar_maxevents);
3459 $eventlimit = get_user_preferences('calendar_maxevents', $defaultmaxevents);
3461 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday'],
3462 $calendardate['hours']);
3463 $date->setTimestamp($tstart);
3464 $date->modify('+' . $lookahead . ' days');
3465 } else {
3466 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], 1);
3467 $monthdays = $type->get_num_days_in_month($calendardate['year'], $calendardate['mon']);
3468 $date->setTimestamp($tstart);
3469 $date->modify('+' . $monthdays . ' days');
3471 if ($view === 'mini' || $view === 'minithree') {
3472 $template = 'core_calendar/calendar_mini';
3473 } else {
3474 $template = 'core_calendar/calendar_month';
3478 // We need to extract 1 second to ensure that we don't get into the next day.
3479 $date->modify('-1 second');
3480 $tend = $date->getTimestamp();
3482 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3483 // If parameter is true, return null.
3484 if ($param === true) {
3485 return null;
3488 // If parameter is false, return an empty array.
3489 if ($param === false) {
3490 return [];
3493 // If the parameter is a scalar value, enclose it in an array.
3494 if (!is_array($param)) {
3495 return [$param];
3498 // No normalisation required.
3499 return $param;
3500 }, [$calendar->users, $calendar->groups, $calendar->courses, $calendar->categories]);
3502 if ($skipevents) {
3503 $events = [];
3504 } else {
3505 $events = \core_calendar\local\api::get_events(
3506 $tstart,
3507 $tend,
3508 null,
3509 null,
3510 null,
3511 null,
3512 $eventlimit,
3513 null,
3514 $userparam,
3515 $groupparam,
3516 $courseparam,
3517 $categoryparam,
3518 true,
3519 true,
3520 function ($event) {
3521 if ($proxy = $event->get_course_module()) {
3522 $cminfo = $proxy->get_proxied_instance();
3523 return $cminfo->uservisible;
3526 if ($proxy = $event->get_category()) {
3527 $category = $proxy->get_proxied_instance();
3529 return $category->is_uservisible();
3532 return true;
3537 $related = [
3538 'events' => $events,
3539 'cache' => new \core_calendar\external\events_related_objects_cache($events),
3540 'type' => $type,
3543 $data = [];
3544 $calendar->set_viewmode($view);
3545 if ($view == "month" || $view == "monthblock" || $view == "mini" || $view == "minithree" ) {
3546 $month = new \core_calendar\external\month_exporter($calendar, $type, $related);
3547 $month->set_includenavigation($includenavigation);
3548 $month->set_initialeventsloaded(!$skipevents);
3549 $month->set_showcoursefilter(($view == "month" || $view == "monthblock"));
3550 $data = $month->export($renderer);
3551 } else if ($view == "day") {
3552 $day = new \core_calendar\external\calendar_day_exporter($calendar, $related);
3553 $data = $day->export($renderer);
3554 $data->viewingday = true;
3555 $data->showviewselector = true;
3556 $template = 'core_calendar/calendar_day';
3557 } else if ($view == "upcoming" || $view == "upcoming_mini") {
3558 $upcoming = new \core_calendar\external\calendar_upcoming_exporter($calendar, $related);
3559 $data = $upcoming->export($renderer);
3561 if ($view == "upcoming") {
3562 $template = 'core_calendar/calendar_upcoming';
3563 $data->viewingupcoming = true;
3564 $data->showviewselector = true;
3565 } else if ($view == "upcoming_mini") {
3566 $template = 'core_calendar/calendar_upcoming_mini';
3570 return [$data, $template];
3574 * Request and render event form fragment.
3576 * @param array $args The fragment arguments.
3577 * @return string The rendered mform fragment.
3579 function calendar_output_fragment_event_form($args) {
3580 global $CFG, $OUTPUT, $USER;
3581 require_once($CFG->libdir . '/grouplib.php');
3582 $html = '';
3583 $data = [];
3584 $eventid = isset($args['eventid']) ? clean_param($args['eventid'], PARAM_INT) : null;
3585 $starttime = isset($args['starttime']) ? clean_param($args['starttime'], PARAM_INT) : null;
3586 $courseid = (isset($args['courseid']) && $args['courseid'] != SITEID) ? clean_param($args['courseid'], PARAM_INT) : null;
3587 $categoryid = isset($args['categoryid']) ? clean_param($args['categoryid'], PARAM_INT) : null;
3588 $event = null;
3589 $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
3590 $context = \context_user::instance($USER->id);
3591 $editoroptions = \core_calendar\local\event\forms\create::build_editor_options($context);
3592 $formoptions = ['editoroptions' => $editoroptions, 'courseid' => $courseid];
3593 $draftitemid = 0;
3595 if ($hasformdata) {
3596 parse_str(clean_param($args['formdata'], PARAM_TEXT), $data);
3597 if (isset($data['description']['itemid'])) {
3598 $draftitemid = $data['description']['itemid'];
3602 if ($starttime) {
3603 $formoptions['starttime'] = $starttime;
3605 // Let's check first which event types user can add.
3606 $eventtypes = calendar_get_allowed_event_types($courseid);
3607 $formoptions['eventtypes'] = $eventtypes;
3609 if (is_null($eventid)) {
3610 if (!empty($courseid)) {
3611 $groupcoursedata = groups_get_course_data($courseid);
3612 $formoptions['groups'] = [];
3613 foreach ($groupcoursedata->groups as $groupid => $groupdata) {
3614 $formoptions['groups'][$groupid] = $groupdata->name;
3618 $mform = new \core_calendar\local\event\forms\create(
3619 null,
3620 $formoptions,
3621 'post',
3623 null,
3624 true,
3625 $data
3628 // If the user is on course context and is allowed to add course events set the event type default to course.
3629 if (!empty($courseid) && !empty($eventtypes['course'])) {
3630 $data['eventtype'] = 'course';
3631 $data['courseid'] = $courseid;
3632 $data['groupcourseid'] = $courseid;
3633 } else if (!empty($categoryid) && !empty($eventtypes['category'])) {
3634 $data['eventtype'] = 'category';
3635 $data['categoryid'] = $categoryid;
3636 } else if (!empty($groupcoursedata) && !empty($eventtypes['group'])) {
3637 $data['groupcourseid'] = $courseid;
3638 $data['groups'] = $groupcoursedata->groups;
3640 $mform->set_data($data);
3641 } else {
3642 $event = calendar_event::load($eventid);
3644 if (!calendar_edit_event_allowed($event)) {
3645 throw new \moodle_exception('nopermissiontoupdatecalendar');
3648 $mapper = new \core_calendar\local\event\mappers\create_update_form_mapper();
3649 $eventdata = $mapper->from_legacy_event_to_data($event);
3650 $data = array_merge((array) $eventdata, $data);
3651 $event->count_repeats();
3652 $formoptions['event'] = $event;
3654 if (!empty($event->courseid)) {
3655 $groupcoursedata = groups_get_course_data($event->courseid);
3656 $formoptions['groups'] = [];
3657 foreach ($groupcoursedata->groups as $groupid => $groupdata) {
3658 $formoptions['groups'][$groupid] = $groupdata->name;
3662 $data['description']['text'] = file_prepare_draft_area(
3663 $draftitemid,
3664 $event->context->id,
3665 'calendar',
3666 'event_description',
3667 $event->id,
3668 null,
3669 $data['description']['text']
3671 $data['description']['itemid'] = $draftitemid;
3673 $mform = new \core_calendar\local\event\forms\update(
3674 null,
3675 $formoptions,
3676 'post',
3678 null,
3679 true,
3680 $data
3682 $mform->set_data($data);
3684 // Check to see if this event is part of a subscription or import.
3685 // If so display a warning on edit.
3686 if (isset($event->subscriptionid) && ($event->subscriptionid != null)) {
3687 $renderable = new \core\output\notification(
3688 get_string('eventsubscriptioneditwarning', 'calendar'),
3689 \core\output\notification::NOTIFY_INFO
3692 $html .= $OUTPUT->render($renderable);
3696 if ($hasformdata) {
3697 $mform->is_validated();
3700 $html .= $mform->render();
3701 return $html;
3705 * Calculate the timestamp from the supplied Gregorian Year, Month, and Day.
3707 * @param int $d The day
3708 * @param int $m The month
3709 * @param int $y The year
3710 * @param int $time The timestamp to use instead of a separate y/m/d.
3711 * @return int The timestamp
3713 function calendar_get_timestamp($d, $m, $y, $time = 0) {
3714 // If a day, month and year were passed then convert it to a timestamp. If these were passed
3715 // then we can assume the day, month and year are passed as Gregorian, as no where in core
3716 // should we be passing these values rather than the time.
3717 if (!empty($d) && !empty($m) && !empty($y)) {
3718 if (checkdate($m, $d, $y)) {
3719 $time = make_timestamp($y, $m, $d);
3720 } else {
3721 $time = time();
3723 } else if (empty($time)) {
3724 $time = time();
3727 return $time;
3731 * Get the calendar footer options.
3733 * @param calendar_information $calendar The calendar information object.
3734 * @param array $options Display options for the footer. If an option is not set, a default value will be provided.
3735 * It consists of:
3736 * - showfullcalendarlink - bool - Whether to show the full calendar link or not. Defaults to false.
3738 * @return array The data for template and template name.
3740 function calendar_get_footer_options($calendar, array $options = []) {
3741 global $CFG, $USER, $PAGE;
3743 // Generate hash for iCal link.
3744 $authtoken = calendar_get_export_token($USER);
3746 $renderer = $PAGE->get_renderer('core_calendar');
3747 $footer = new \core_calendar\external\footer_options_exporter($calendar, $USER->id, $authtoken, $options);
3748 $data = $footer->export($renderer);
3749 $template = 'core_calendar/footer_options';
3751 return [$data, $template];
3755 * Get the list of potential calendar filter types as a type => name
3756 * combination.
3758 * @return array
3760 function calendar_get_filter_types() {
3761 $types = [
3762 'site',
3763 'category',
3764 'course',
3765 'group',
3766 'user',
3767 'other'
3770 return array_map(function($type) {
3771 return [
3772 'eventtype' => $type,
3773 'name' => get_string("eventtype{$type}", "calendar"),
3774 'icon' => true,
3775 'key' => 'i/' . $type . 'event',
3776 'component' => 'core'
3778 }, $types);
3782 * Check whether the specified event type is valid.
3784 * @param string $type
3785 * @return bool
3787 function calendar_is_valid_eventtype($type) {
3788 $validtypes = [
3789 'user',
3790 'group',
3791 'course',
3792 'category',
3793 'site',
3795 return in_array($type, $validtypes);
3799 * Get event types the user can create event based on categories, courses and groups
3800 * the logged in user belongs to.
3802 * @param int|null $courseid The course id.
3803 * @return array The array of allowed types.
3805 function calendar_get_allowed_event_types(int $courseid = null) {
3806 global $DB, $CFG, $USER;
3808 $types = [
3809 'user' => false,
3810 'site' => false,
3811 'course' => false,
3812 'group' => false,
3813 'category' => false
3816 if (!empty($courseid) && $courseid != SITEID) {
3817 $context = \context_course::instance($courseid);
3818 $types['user'] = has_capability('moodle/calendar:manageownentries', $context);
3819 calendar_internal_update_course_and_group_permission($courseid, $context, $types);
3822 if (has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID))) {
3823 $types['site'] = true;
3826 if (has_capability('moodle/calendar:manageownentries', \context_system::instance())) {
3827 $types['user'] = true;
3829 if (core_course_category::has_manage_capability_on_any()) {
3830 $types['category'] = true;
3833 // We still don't know if the user can create group and course events, so iterate over the courses to find out
3834 // if the user has capabilities in one of the courses.
3835 if ($types['course'] == false || $types['group'] == false) {
3836 if ($CFG->calendar_adminseesall && has_capability('moodle/calendar:manageentries', context_system::instance())) {
3837 $sql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3838 FROM {course} c
3839 JOIN {context} ctx ON ctx.contextlevel = ? AND ctx.instanceid = c.id
3840 WHERE c.id IN (
3841 SELECT DISTINCT courseid FROM {groups}
3843 $courseswithgroups = $DB->get_recordset_sql($sql, [CONTEXT_COURSE]);
3844 foreach ($courseswithgroups as $course) {
3845 context_helper::preload_from_record($course);
3846 $context = context_course::instance($course->id);
3848 if (has_capability('moodle/calendar:manageentries', $context)) {
3849 if (has_any_capability(['moodle/site:accessallgroups', 'moodle/calendar:managegroupentries'], $context)) {
3850 // The user can manage group entries or access any group.
3851 $types['group'] = true;
3852 $types['course'] = true;
3853 break;
3857 $courseswithgroups->close();
3859 if (false === $types['course']) {
3860 // Course is still not confirmed. There may have been no courses with a group in them.
3861 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
3862 $sql = "SELECT
3863 c.id, c.visible, {$ctxfields}
3864 FROM {course} c
3865 JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
3866 $params = [
3867 'contextlevel' => CONTEXT_COURSE,
3869 $courses = $DB->get_recordset_sql($sql, $params);
3870 foreach ($courses as $course) {
3871 context_helper::preload_from_record($course);
3872 $context = context_course::instance($course->id);
3873 if (has_capability('moodle/calendar:manageentries', $context)) {
3874 $types['course'] = true;
3875 break;
3878 $courses->close();
3881 } else {
3882 $courses = calendar_get_default_courses(null, 'id');
3883 if (empty($courses)) {
3884 return $types;
3887 $courseids = array_map(function($c) {
3888 return $c->id;
3889 }, $courses);
3891 // Check whether the user has access to create events within courses which have groups.
3892 list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
3893 $sql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3894 FROM {course} c
3895 JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3896 WHERE c.id $insql
3897 AND c.id IN (SELECT DISTINCT courseid FROM {groups})";
3898 $params['contextlevel'] = CONTEXT_COURSE;
3899 $courseswithgroups = $DB->get_recordset_sql($sql, $params);
3900 foreach ($courseswithgroups as $coursewithgroup) {
3901 context_helper::preload_from_record($coursewithgroup);
3902 $context = context_course::instance($coursewithgroup->id);
3904 calendar_internal_update_course_and_group_permission($coursewithgroup->id, $context, $types);
3906 // Okay, course and group event types are allowed, no need to keep the loop iteration.
3907 if ($types['course'] == true && $types['group'] == true) {
3908 break;
3911 $courseswithgroups->close();
3913 if (false === $types['course']) {
3914 list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
3915 $contextsql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3916 FROM {course} c
3917 JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3918 WHERE c.id $insql";
3919 $params['contextlevel'] = CONTEXT_COURSE;
3920 $contextrecords = $DB->get_recordset_sql($contextsql, $params);
3921 foreach ($contextrecords as $course) {
3922 context_helper::preload_from_record($course);
3923 $coursecontext = context_course::instance($course->id);
3924 if (has_capability('moodle/calendar:manageentries', $coursecontext)
3925 && ($courseid == $course->id || empty($courseid))) {
3926 $types['course'] = true;
3927 break;
3930 $contextrecords->close();
3936 return $types;
3940 * Given a course id, and context, updates the permission types array to add the 'course' or 'group'
3941 * permission if it is relevant for that course.
3943 * For efficiency, if they already have 'course' or 'group' then it skips checks.
3945 * Do not call this function directly, it is only for use by calendar_get_allowed_event_types().
3947 * @param int $courseid Course id
3948 * @param context $context Context for that course
3949 * @param array $types Current permissions
3951 function calendar_internal_update_course_and_group_permission(int $courseid, context $context, array &$types) {
3952 if (!$types['course']) {
3953 // If they have manageentries permission on the course, then they can update this course.
3954 if (has_capability('moodle/calendar:manageentries', $context)) {
3955 $types['course'] = true;
3958 // To update group events they must have EITHER manageentries OR managegroupentries.
3959 if (!$types['group'] && (has_capability('moodle/calendar:manageentries', $context) ||
3960 has_capability('moodle/calendar:managegroupentries', $context))) {
3961 // And they also need for a group to exist on the course.
3962 $groups = groups_get_all_groups($courseid);
3963 if (!empty($groups)) {
3964 // And either accessallgroups, or belong to one of the groups.
3965 if (has_capability('moodle/site:accessallgroups', $context)) {
3966 $types['group'] = true;
3967 } else {
3968 foreach ($groups as $group) {
3969 if (groups_is_member($group->id)) {
3970 $types['group'] = true;
3971 break;
3980 * Get the auth token for exporting the given user calendar.
3981 * @param stdClass $user The user to export the calendar for
3983 * @return string The export token.
3985 function calendar_get_export_token(stdClass $user): string {
3986 global $CFG, $DB;
3988 return sha1($user->id . $DB->get_field('user', 'password', ['id' => $user->id]) . $CFG->calendar_exportsalt);
3992 * Get the list of URL parameters for calendar expport and import links.
3994 * @return array
3996 function calendar_get_export_import_link_params(): array {
3997 global $PAGE;
3999 $params = [];
4000 if ($courseid = $PAGE->url->get_param('course')) {
4001 $params['course'] = $courseid;
4003 if ($categoryid = $PAGE->url->get_param('category')) {
4004 $params['category'] = $categoryid;
4007 return $params;
4011 * Implements the inplace editable feature.
4013 * @param string $itemtype Type of the inplace editable element
4014 * @param int $itemid Id of the item to edit
4015 * @param int $newvalue New value of the item
4016 * @return \core\output\inplace_editable
4018 function calendar_inplace_editable(string $itemtype, int $itemid, int $newvalue): \core\output\inplace_editable {
4019 global $OUTPUT;
4021 if ($itemtype === 'refreshinterval') {
4023 $subscription = calendar_get_subscription($itemid);
4024 $context = calendar_get_calendar_context($subscription);
4025 external_api::validate_context($context);
4027 $updateresult = \core_calendar\output\refreshintervalcollection::update($itemid, $newvalue);
4029 $refreshresults = calendar_update_subscription_events($itemid);
4030 \core\notification::add($OUTPUT->render_from_template(
4031 'core_calendar/subscription_update_result',
4032 array_merge($refreshresults, [
4033 'subscriptionname' => s($subscription->name),
4035 ), \core\notification::INFO);
4037 return $updateresult;
4040 external_api::validate_context(context_system::instance());