2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * @package core_calendar
21 * @copyright 2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 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
33 * These are read by the administration component to provide default values
37 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
39 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
42 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
44 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
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
55 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
57 define('CALENDAR_DEFAULT_WEEKEND', 65);
60 * CALENDAR_URL - path to calendar's folder
62 define('CALENDAR_URL', $CFG->wwwroot
.'/calendar/');
65 * CALENDAR_TF_24 - Calendar time in 24 hours format
67 define('CALENDAR_TF_24', '%H:%M');
70 * CALENDAR_TF_12 - Calendar time in 12 hours format
72 define('CALENDAR_TF_12', '%I:%M %p');
75 * CALENDAR_EVENT_SITE - Site calendar event types
77 define('CALENDAR_EVENT_SITE', 1);
80 * CALENDAR_EVENT_COURSE - Course calendar event types
82 define('CALENDAR_EVENT_COURSE', 2);
85 * CALENDAR_EVENT_GROUP - group calendar event types
87 define('CALENDAR_EVENT_GROUP', 4);
90 * CALENDAR_EVENT_USER - user calendar event types
92 define('CALENDAR_EVENT_USER', 8);
95 * CALENDAR_EVENT_COURSECAT - Course category calendar event types
97 define('CALENDAR_EVENT_COURSECAT', 16);
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
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
171 * @property string $component If created by a plugin/component (other than module), the full frankenstyle name of a component
172 * @property string $modulename If added by a module this will be the module name
173 * @property int $instance If added by a module this will be the module instance
174 * @property string $eventtype The event type
175 * @property int $timestart The start time as a timestamp
176 * @property int $timeduration The duration of the event in seconds
177 * @property int $timeusermidnight User midnight for the event
178 * @property int $visible 1 if the event is visible
179 * @property int $uuid ?
180 * @property int $sequence ?
181 * @property int $timemodified The time last modified as a timestamp
183 class calendar_event
{
185 /** @var stdClass An object containing the event properties can be accessed via the magic __get/set methods */
186 protected $properties = null;
188 /** @var string The converted event discription with file paths resolved.
189 * This gets populated when someone requests description for the first time */
190 protected $_description = null;
192 /** @var array The options to use with this description editor */
193 protected $editoroptions = array(
195 'forcehttps' => false,
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
209 public function __construct($data = null) {
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
)) {
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;
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;
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
320 * Default value is set to CONTEXT_USER
322 * @return \stdClass The context object.
324 protected function calculate_context() {
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,
346 $context = \context_course
::instance($cm->course
);
348 $context = \context_user
::instance($this->properties
->userid
);
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.
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() {
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
;
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() {
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) {
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.
471 'context' => $this->get_context(),
472 'objectid' => $this->properties
->id
,
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');
488 switch ($this->properties
->eventtype
) {
490 $this->properties
->courseid
= 0;
491 $this->properties
->course
= 0;
492 $this->properties
->groupid
= 0;
493 $this->properties
->userid
= $USER->id
;
496 $this->properties
->courseid
= SITEID
;
497 $this->properties
->course
= SITEID
;
498 $this->properties
->groupid
= 0;
499 $this->properties
->userid
= $USER->id
;
502 $this->properties
->groupid
= 0;
503 $this->properties
->userid
= $USER->id
;
506 $this->properties
->groupid
= 0;
507 $this->properties
->category
= 0;
508 $this->properties
->userid
= $USER->id
;
511 $this->properties
->userid
= $USER->id
;
514 // We should NEVER get here, but just incase we do lets fail gracefully.
515 $usingeditor = false;
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.
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
);
535 $this->properties
->description
= file_save_draft_area_files(
537 $this->editorcontext
->id
,
540 $this->properties
->id
,
541 $this->editoroptions
,
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);
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.
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;
587 $eventargs['objectid'] = $eventcopyid;
588 $eventargs['other']['timestart'] = $eventcopy->timestart
;
589 $event = \core\event\calendar_event_created
::create($eventargs);
597 if ($checkcapability) {
598 if (!calendar_edit_event_allowed($this->properties
)) {
599 throw new \
moodle_exception('nopermissiontoupdatecalendar');
604 if ($this->editorcontext
!== null) {
605 $this->properties
->description
= file_save_draft_area_files(
606 $this->properties
->description
['itemid'],
607 $this->editorcontext
->id
,
610 $this->properties
->id
,
611 $this->editoroptions
,
612 $this->properties
->description
['text'],
613 $this->editoroptions
['forcehttps']);
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) {
633 // Note: Group and course id may not be set. If not, keep their current values.
635 $this->properties
->name
,
636 $this->properties
->description
,
637 $this->properties
->timeduration
,
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
;
658 $sql = "UPDATE {event}
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);
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
);
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) {
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
);
708 $calevent = $DB->get_record('event', array('id' => $this->properties
->id
), '*', MUST_EXIST
);
710 $DB->delete_records('event', array('id' => $this->properties
->id
));
712 // Trigger an event for the delete action.
714 'context' => $this->get_context(),
715 'objectid' => $this->properties
->id
,
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);
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);
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) {
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);
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) {
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') {
807 $this->editorcontext
= $this->get_context();
808 } else if ($properties->eventtype
=== 'user') {
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
));
815 throw new \
moodle_exception('invalidcourse');
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);
826 $this->editorcontext
= $this->get_context();
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
)) {
838 // Get the context id that is what we really want.
839 $contextid = $this->editorcontext
->id
;
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.
848 // If the contextid === false we don't support files so no preparing
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
);
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.
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
875 * @return bool if event is successfully updated, toggle will be visible
877 public function toggle_visibility($force = null) {
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;
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.
899 'context' => $this->get_context(),
900 'objectid' => $this->properties
->id
,
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);
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) {
925 if (is_object($param)) {
926 $event = new calendar_event($param);
928 $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST
);
929 $event = new calendar_event($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)) {
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
;
1010 $itemid = $this->properties
->id
;
1013 return \core_external\util
::format_text(
1014 $this->properties
->description
,
1015 $this->properties
->format
,
1016 $this->editorcontext
,
1018 'event_description',
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.
1045 /** @var int A course id */
1046 public $courseid = null;
1048 /** @var array An array of categories */
1049 public $categories = array();
1051 /** @var int The current category */
1052 public $categoryid = null;
1054 /** @var array An array of courses */
1055 public $courses = array();
1057 /** @var array An array of groups */
1058 public $groups = array();
1060 /** @var array An array of users */
1061 public $users = array();
1063 /** @var context The anticipated context that the calendar is viewed in */
1064 public $context = null;
1066 /** @var string The calendar's view mode. */
1067 protected $viewmode;
1069 /** @var \stdClass course data. */
1072 /** @var int day. */
1075 /** @var int month. */
1078 /** @var int year. */
1082 * Creates a new instance
1084 * @param int $day the number of the day
1085 * @param int $month the number of the month
1086 * @param int $year the number of the year
1087 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
1088 * and $calyear to support multiple calendars
1090 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
1091 // If a day, month and year were passed then convert it to a timestamp. If these were passed
1092 // then we can assume the day, month and year are passed as Gregorian, as no where in core
1093 // should we be passing these values rather than the time. This is done for BC.
1094 if (!empty($day) ||
!empty($month) ||
!empty($year)) {
1095 $date = usergetdate(time());
1097 $day = $date['mday'];
1099 if (empty($month)) {
1100 $month = $date['mon'];
1103 $year = $date['year'];
1105 if (checkdate($month, $day, $year)) {
1106 $time = make_timestamp($year, $month, $day);
1112 $this->set_time($time);
1116 * Creates and set up a instance.
1118 * @param int $time the unixtimestamp representing the date we want to view.
1119 * @param int $courseid The ID of the course the user wishes to view.
1120 * @param int $categoryid The ID of the category the user wishes to view
1121 * If a courseid is specified, this value is ignored.
1122 * @return calendar_information
1124 public static function create($time, int $courseid, ?
int $categoryid = null): calendar_information
{
1125 $calendar = new static(0, 0, 0, $time);
1126 if ($courseid != SITEID
&& !empty($courseid)) {
1127 // Course ID must be valid and existing.
1128 $course = get_course($courseid);
1129 $calendar->context
= context_course
::instance($course->id
);
1131 if (!$course->visible
&& !is_role_switched($course->id
)) {
1132 require_capability('moodle/course:viewhiddencourses', $calendar->context
);
1135 $courses = [$course->id
=> $course];
1136 $category = (\core_course_category
::get($course->category
, MUST_EXIST
, true))->get_db_record();
1137 } else if (!empty($categoryid)) {
1138 $course = get_site();
1139 $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1141 // Filter available courses to those within this category or it's children.
1142 $ids = [$categoryid];
1143 $category = \core_course_category
::get($categoryid);
1144 $ids = array_merge($ids, array_keys($category->get_children()));
1145 $courses = array_filter($courses, function($course) use ($ids) {
1146 return array_search($course->category
, $ids) !== false;
1148 $category = $category->get_db_record();
1150 $calendar->context
= context_coursecat
::instance($categoryid);
1152 $course = get_site();
1153 $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1156 $calendar->context
= context_system
::instance();
1159 $calendar->set_sources($course, $courses, $category);
1165 * Set the time period of this instance.
1167 * @param int $time the unixtimestamp representing the date we want to view.
1170 public function set_time($time = null) {
1172 $this->time
= time();
1174 $this->time
= $time;
1181 * Initialize calendar information
1184 * @param stdClass $course object
1185 * @param array $coursestoload An array of courses [$course->id => $course]
1186 * @param bool $ignorefilters options to use filter
1188 public function prepare_for_view(stdClass
$course, array $coursestoload, $ignorefilters = false) {
1189 debugging('The prepare_for_view() function has been deprecated. Please update your code to use set_sources()',
1191 $this->set_sources($course, $coursestoload);
1195 * Set the sources for events within the calendar.
1197 * If no category is provided, then the category path for the current
1198 * course will be used.
1200 * @param stdClass $course The current course being viewed.
1201 * @param stdClass[] $courses The list of all courses currently accessible.
1202 * @param stdClass $category The current category to show.
1204 public function set_sources(stdClass
$course, array $courses, ?stdClass
$category = null) {
1207 // A cousre must always be specified.
1208 $this->course
= $course;
1209 $this->courseid
= $course->id
;
1211 list($courseids, $group, $user) = calendar_set_filters($courses);
1212 $this->courses
= $courseids;
1213 $this->groups
= $group;
1214 $this->users
= $user;
1216 // Do not show category events by default.
1217 $this->categoryid
= null;
1218 $this->categories
= null;
1220 // Determine the correct category information to show.
1221 // When called with a course, the category of that course is usually included too.
1222 // When a category was specifically requested, it should be requested with the site id.
1223 if (SITEID
!== $this->courseid
) {
1224 // A specific course was requested.
1225 // Fetch the category that this course is in, along with all parents.
1226 // Do not include child categories of this category, as the user many not have enrolments in those siblings or children.
1227 $category = \core_course_category
::get($course->category
, MUST_EXIST
, true);
1228 $this->categoryid
= $category->id
;
1230 $this->categories
= $category->get_parents();
1231 $this->categories
[] = $category->id
;
1232 } else if (null !== $category && $category->id
> 0) {
1233 // A specific category was requested.
1234 // Fetch all parents of this category, along with all children too.
1235 $category = \core_course_category
::get($category->id
);
1236 $this->categoryid
= $category->id
;
1238 // Build the category list.
1239 // This includes the current category.
1240 $this->categories
= $category->get_parents();
1241 $this->categories
[] = $category->id
;
1242 $this->categories
= array_merge($this->categories
, $category->get_all_children_ids());
1243 } else if (SITEID
=== $this->courseid
) {
1244 // The site was requested.
1245 // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
1247 // Grab the list of categories that this user has courses in.
1248 $coursecategories = array_flip(array_map(function($course) {
1249 return $course->category
;
1252 $calcatcache = cache
::make('core', 'calendar_categories');
1253 $this->categories
= $calcatcache->get('site');
1254 if ($this->categories
=== false) {
1255 // Use the category id as the key in the following array. That way we do not have to remove duplicates.
1257 foreach (\core_course_category
::get_all() as $category) {
1258 if (isset($coursecategories[$category->id
]) ||
1259 has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
1260 // If the user has access to a course in this category or can manage the category,
1261 // then they can see all parent categories too.
1262 $categories[$category->id
] = true;
1263 foreach ($category->get_parents() as $catid) {
1264 $categories[$catid] = true;
1268 $this->categories
= array_keys($categories);
1269 $calcatcache->set('site', $this->categories
);
1275 * Ensures the date for the calendar is correct and either sets it to now
1276 * or throws a moodle_exception if not
1278 * @param bool $defaultonow use current time
1279 * @throws moodle_exception
1280 * @return bool validation of checkdate
1282 public function checkdate($defaultonow = true) {
1283 if (!checkdate($this->month
, $this->day
, $this->year
)) {
1285 $now = usergetdate(time());
1286 $this->day
= intval($now['mday']);
1287 $this->month
= intval($now['mon']);
1288 $this->year
= intval($now['year']);
1291 throw new moodle_exception('invaliddate');
1298 * Gets todays timestamp for the calendar
1300 * @return int today timestamp
1302 public function timestamp_today() {
1306 * Gets tomorrows timestamp for the calendar
1308 * @return int tomorrow timestamp
1310 public function timestamp_tomorrow() {
1311 return strtotime('+1 day', $this->time
);
1314 * Adds the pretend blocks for the calendar
1316 * @param core_calendar_renderer $renderer
1317 * @param bool $showfilters display filters, false is set as default
1318 * @param string|null $view preference view options (eg: day, month, upcoming)
1320 public function add_sidecalendar_blocks(core_calendar_renderer
$renderer, $showfilters=false, $view=null) {
1323 if (!has_capability('moodle/block:view', $PAGE->context
) ) {
1328 $filters = new block_contents();
1329 $filters->content
= $renderer->event_filter();
1330 $filters->footer
= '';
1331 $filters->title
= get_string('eventskey', 'calendar');
1332 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT
);
1337 * Getter method for the calendar's view mode.
1341 public function get_viewmode(): string {
1342 return $this->viewmode
;
1346 * Setter method for the calendar's view mode.
1348 * @param string $viewmode
1350 public function set_viewmode(string $viewmode): void
{
1351 $this->viewmode
= $viewmode;
1356 * Get calendar events.
1358 * @param int $tstart Start time of time range for events
1359 * @param int $tend End time of time range for events
1360 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
1361 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
1362 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
1363 * @param boolean $withduration whether only events starting within time range selected
1364 * or events in progress/already started selected as well
1365 * @param boolean $ignorehidden whether to select only visible events or all events
1366 * @param array|int|boolean $categories array of categories, category id or boolean for all/no course events
1367 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
1369 function calendar_get_events($tstart, $tend, $users, $groups, $courses,
1370 $withduration = true, $ignorehidden = true, $categories = []) {
1376 if (empty($users) && empty($groups) && empty($courses) && empty($categories)) {
1380 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
1381 // Events from a number of users
1382 if(!empty($whereclause)) $whereclause .= ' OR';
1383 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED
);
1384 $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)";
1385 $params = array_merge($params, $inparamsusers);
1386 } else if($users === true) {
1387 // Events from ALL users
1388 if(!empty($whereclause)) $whereclause .= ' OR';
1389 $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)';
1390 } else if($users === false) {
1391 // No user at all, do nothing
1394 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
1395 // Events from a number of groups
1396 if(!empty($whereclause)) $whereclause .= ' OR';
1397 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED
);
1398 $whereclause .= " e.groupid $insqlgroups ";
1399 $params = array_merge($params, $inparamsgroups);
1400 } else if($groups === true) {
1401 // Events from ALL groups
1402 if(!empty($whereclause)) $whereclause .= ' OR ';
1403 $whereclause .= ' e.groupid != 0';
1405 // boolean false (no groups at all): we don't need to do anything
1407 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
1408 if(!empty($whereclause)) $whereclause .= ' OR';
1409 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED
);
1410 $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
1411 $params = array_merge($params, $inparamscourses);
1412 } else if ($courses === true) {
1413 // Events from ALL courses
1414 if(!empty($whereclause)) $whereclause .= ' OR';
1415 $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
1418 if ((is_array($categories) && !empty($categories)) ||
is_numeric($categories)) {
1419 if (!empty($whereclause)) {
1420 $whereclause .= ' OR';
1422 list($insqlcategories, $inparamscategories) = $DB->get_in_or_equal($categories, SQL_PARAMS_NAMED
);
1423 $whereclause .= " (e.groupid = 0 AND e.courseid = 0 AND e.categoryid $insqlcategories)";
1424 $params = array_merge($params, $inparamscategories);
1425 } else if ($categories === true) {
1426 // Events from ALL categories.
1427 if (!empty($whereclause)) {
1428 $whereclause .= ' OR';
1430 $whereclause .= ' (e.groupid = 0 AND e.courseid = 0 AND e.categoryid != 0)';
1433 // Security check: if, by now, we have NOTHING in $whereclause, then it means
1434 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
1435 // events no matter what. Allowing the code to proceed might return a completely
1436 // valid query with only time constraints, thus selecting ALL events in that time frame!
1437 if(empty($whereclause)) {
1442 $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1445 $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1447 if(!empty($whereclause)) {
1448 // We have additional constraints
1449 $whereclause = $timeclause.' AND ('.$whereclause.')';
1452 // Just basic time filtering
1453 $whereclause = $timeclause;
1456 if ($ignorehidden) {
1457 $whereclause .= ' AND e.visible = 1';
1462 LEFT JOIN {modules} m ON e.modulename = m.name
1463 -- Non visible modules will have a value of 0.
1464 WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
1465 ORDER BY e.timestart";
1466 $events = $DB->get_records_sql($sql, $params);
1468 if ($events === false) {
1475 * Return the days of the week.
1477 * @return array array of days
1479 function calendar_get_days() {
1480 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1481 return $calendartype->get_weekdays();
1485 * Get the subscription from a given id.
1488 * @param int $id id of the subscription
1489 * @return stdClass Subscription record from DB
1490 * @throws moodle_exception for an invalid id
1492 function calendar_get_subscription($id) {
1495 $cache = \cache
::make('core', 'calendar_subscriptions');
1496 $subscription = $cache->get($id);
1497 if (empty($subscription)) {
1498 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST
);
1499 $cache->set($id, $subscription);
1502 return $subscription;
1506 * Gets the first day of the week.
1508 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
1512 function calendar_get_starting_weekday() {
1513 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1514 return $calendartype->get_starting_weekday();
1518 * Get a HTML link to a course.
1520 * @param int|stdClass $course the course id or course object
1521 * @return string a link to the course (as HTML); empty if the course id is invalid
1523 function calendar_get_courselink($course) {
1528 if (!is_object($course)) {
1529 $course = calendar_get_course_cached($coursecache, $course);
1531 $context = \context_course
::instance($course->id
);
1532 $fullname = format_string($course->fullname
, true, array('context' => $context));
1533 $url = new \
moodle_url('/course/view.php', array('id' => $course->id
));
1534 $link = \html_writer
::link($url, $fullname);
1540 * Get current module cache.
1542 * Only use this method if you do not know courseid. Otherwise use:
1543 * get_fast_modinfo($courseid)->instances[$modulename][$instance]
1545 * @param array $modulecache in memory module cache
1546 * @param string $modulename name of the module
1547 * @param int $instance module instance number
1548 * @return stdClass|bool $module information
1550 function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
1551 if (!isset($modulecache[$modulename . '_' . $instance])) {
1552 $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
1555 return $modulecache[$modulename . '_' . $instance];
1559 * Get current course cache.
1561 * @param array $coursecache list of course cache
1562 * @param int $courseid id of the course
1563 * @return stdClass $coursecache[$courseid] return the specific course cache
1565 function calendar_get_course_cached(&$coursecache, $courseid) {
1566 if (!isset($coursecache[$courseid])) {
1567 $coursecache[$courseid] = get_course($courseid);
1569 return $coursecache[$courseid];
1573 * Get group from groupid for calendar display
1575 * @param int $groupid
1576 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1578 function calendar_get_group_cached($groupid) {
1579 static $groupscache = array();
1580 if (!isset($groupscache[$groupid])) {
1581 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1583 return $groupscache[$groupid];
1587 * Add calendar event metadata
1589 * @deprecated since 3.9
1591 * @param stdClass $event event info
1592 * @return stdClass $event metadata
1594 function calendar_add_event_metadata($event) {
1595 debugging('This function is no longer used', DEBUG_DEVELOPER
);
1596 global $CFG, $OUTPUT;
1598 // Support multilang in event->name.
1599 $event->name
= format_string($event->name
, true);
1601 if (!empty($event->modulename
)) { // Activity event.
1602 // The module name is set. I will assume that it has to be displayed, and
1603 // also that it is an automatically-generated event. And of course that the
1604 // instace id and modulename are set correctly.
1605 $instances = get_fast_modinfo($event->courseid
)->get_instances_of($event->modulename
);
1606 if (!array_key_exists($event->instance
, $instances)) {
1609 $module = $instances[$event->instance
];
1611 $modulename = $module->get_module_type_name(false);
1612 if (get_string_manager()->string_exists($event->eventtype
, $event->modulename
)) {
1613 // Will be used as alt text if the event icon.
1614 $eventtype = get_string($event->eventtype
, $event->modulename
);
1619 $event->icon
= '<img src="' . s($module->get_icon_url()) . '" alt="' . s($eventtype) .
1620 '" title="' . s($modulename) . '" class="icon" />';
1621 $event->referer
= html_writer
::link($module->url
, $event->name
);
1622 $event->courselink
= calendar_get_courselink($module->get_course());
1623 $event->cmid
= $module->id
;
1624 } else if ($event->courseid
== SITEID
) { // Site event.
1625 $event->icon
= '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
1626 get_string('siteevent', 'calendar') . '" class="icon" />';
1627 $event->cssclass
= 'calendar_event_site';
1628 } else if ($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) { // Course event.
1629 $event->icon
= '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
1630 get_string('courseevent', 'calendar') . '" class="icon" />';
1631 $event->courselink
= calendar_get_courselink($event->courseid
);
1632 $event->cssclass
= 'calendar_event_course';
1633 } else if ($event->groupid
) { // Group event.
1634 if ($group = calendar_get_group_cached($event->groupid
)) {
1635 $groupname = format_string($group->name
, true, \context_course
::instance($group->courseid
));
1639 $event->icon
= \html_writer
::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
1640 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
1641 $event->courselink
= calendar_get_courselink($event->courseid
) . ', ' . $groupname;
1642 $event->cssclass
= 'calendar_event_group';
1643 } else if ($event->userid
) { // User event.
1644 $event->icon
= '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
1645 get_string('userevent', 'calendar') . '" class="icon" />';
1646 $event->cssclass
= 'calendar_event_user';
1653 * Get calendar events by id.
1656 * @param array $eventids list of event ids
1657 * @return array Array of event entries, empty array if nothing found
1659 function calendar_get_events_by_id($eventids) {
1662 if (!is_array($eventids) ||
empty($eventids)) {
1666 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
1667 $wheresql = "id $wheresql";
1669 return $DB->get_records_select('event', $wheresql, $params);
1673 * Get control options for calendar.
1675 * @deprecated since Moodle 4.3
1676 * @param string $type of calendar
1677 * @param array $data calendar information
1678 * @return string $content return available control for the calendar in html
1680 function calendar_top_controls($type, $data) {
1681 debugging(__FUNCTION__
. ' has been deprecated and should not be used anymore.', DEBUG_DEVELOPER
);
1683 global $PAGE, $OUTPUT;
1685 // Get the calendar type we are using.
1686 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1690 // Ensure course id passed if relevant.
1692 if (!empty($data['id'])) {
1693 $courseid = '&course=' . $data['id'];
1696 // If we are passing a month and year then we need to convert this to a timestamp to
1697 // support multiple calendars. No where in core should these be passed, this logic
1698 // here is for third party plugins that may use this function.
1699 if (!empty($data['m']) && !empty($date['y'])) {
1700 if (!isset($data['d'])) {
1703 if (!checkdate($data['m'], $data['d'], $data['y'])) {
1706 $time = make_timestamp($data['y'], $data['m'], $data['d']);
1708 } else if (!empty($data['time'])) {
1709 $time = $data['time'];
1714 // Get the date for the calendar type.
1715 $date = $calendartype->timestamp_to_date_array($time);
1717 $urlbase = $PAGE->url
;
1719 // We need to get the previous and next months in certain cases.
1720 if ($type == 'frontpage' ||
$type == 'course' ||
$type == 'month') {
1721 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1722 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
1723 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
1724 $prevmonthtime['hour'], $prevmonthtime['minute']);
1726 $nextmonth = calendar_add_month($date['mon'], $date['year']);
1727 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
1728 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
1729 $nextmonthtime['hour'], $nextmonthtime['minute']);
1734 $prevlink = calendar_get_link_previous(get_string('monthprev', 'calendar'), $urlbase, false, false, false,
1735 true, $prevmonthtime);
1736 $nextlink = calendar_get_link_next(get_string('monthnext', 'calendar'), $urlbase, false, false, false, true,
1738 $calendarlink = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', array('view' => 'month')),
1739 false, false, false, $time);
1741 if (!empty($data['id'])) {
1742 $calendarlink->param('course', $data['id']);
1747 $content .= \html_writer
::start_tag('div', array('class' => 'calendar-controls'));
1748 $content .= $prevlink . '<span class="hide"> | </span>';
1749 $content .= \html_writer
::tag('span', \html_writer
::link($calendarlink,
1750 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1751 ), array('class' => 'current'));
1752 $content .= '<span class="hide"> | </span>' . $right;
1753 $content .= "<span class=\"clearer\"><!-- --></span>\n";
1754 $content .= \html_writer
::end_tag('div');
1758 $prevlink = calendar_get_link_previous(get_string('monthprev', 'calendar'), $urlbase, false, false, false,
1759 true, $prevmonthtime);
1760 $nextlink = calendar_get_link_next(get_string('monthnext', 'calendar'), $urlbase, false, false, false,
1761 true, $nextmonthtime);
1762 $calendarlink = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', array('view' => 'month')),
1763 false, false, false, $time);
1765 if (!empty($data['id'])) {
1766 $calendarlink->param('course', $data['id']);
1769 $content .= \html_writer
::start_tag('div', array('class' => 'calendar-controls'));
1770 $content .= $prevlink . '<span class="hide"> | </span>';
1771 $content .= \html_writer
::tag('span', \html_writer
::link($calendarlink,
1772 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1773 ), array('class' => 'current'));
1774 $content .= '<span class="hide"> | </span>' . $nextlink;
1775 $content .= "<span class=\"clearer\"><!-- --></span>";
1776 $content .= \html_writer
::end_tag('div');
1779 $calendarlink = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', array('view' => 'upcoming')),
1780 false, false, false, $time);
1781 if (!empty($data['id'])) {
1782 $calendarlink->param('course', $data['id']);
1784 $calendarlink = \html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1785 $content .= \html_writer
::tag('div', $calendarlink, array('class' => 'centered'));
1788 $calendarlink = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', array('view' => 'month')),
1789 false, false, false, $time);
1790 if (!empty($data['id'])) {
1791 $calendarlink->param('course', $data['id']);
1793 $calendarlink = \html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1794 $content .= \html_writer
::tag('h3', $calendarlink);
1797 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1798 'view.php?view=month' . $courseid . '&', false, false, false, false, $prevmonthtime);
1799 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1800 'view.php?view=month' . $courseid . '&', false, false, false, false, $nextmonthtime);
1802 $content .= \html_writer
::start_tag('div', array('class' => 'calendar-controls'));
1803 $content .= $prevlink . '<span class="hide"> | </span>';
1804 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1805 $content .= '<span class="hide"> | </span>' . $nextlink;
1806 $content .= '<span class="clearer"><!-- --></span>';
1807 $content .= \html_writer
::end_tag('div')."\n";
1810 $days = calendar_get_days();
1812 $prevtimestamp = strtotime('-1 day', $time);
1813 $nexttimestamp = strtotime('+1 day', $time);
1815 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1816 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1818 $prevname = $days[$prevdate['wday']]['fullname'];
1819 $nextname = $days[$nextdate['wday']]['fullname'];
1820 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&', false, false,
1821 false, false, $prevtimestamp);
1822 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&', false, false, false,
1823 false, $nexttimestamp);
1825 $content .= \html_writer
::start_tag('div', array('class' => 'calendar-controls'));
1826 $content .= $prevlink;
1827 $content .= '<span class="hide"> | </span><span class="current">' .userdate($time,
1828 get_string('strftimedaydate')) . '</span>';
1829 $content .= '<span class="hide"> | </span>' . $nextlink;
1830 $content .= "<span class=\"clearer\"><!-- --></span>";
1831 $content .= \html_writer
::end_tag('div') . "\n";
1840 * Return the representation day.
1842 * @param int $tstamp Timestamp in GMT
1843 * @param int|bool $now current Unix timestamp
1844 * @param bool $usecommonwords
1845 * @return string the formatted date/time
1847 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1848 static $shortformat;
1850 if (empty($shortformat)) {
1851 $shortformat = get_string('strftimedayshort');
1854 if ($now === false) {
1858 // To have it in one place, if a change is needed.
1859 $formal = userdate($tstamp, $shortformat);
1861 $datestamp = usergetdate($tstamp);
1862 $datenow = usergetdate($now);
1864 if ($usecommonwords == false) {
1865 // We don't want words, just a date.
1867 } else if ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1868 return get_string('today', 'calendar');
1869 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1870 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12
1871 && $datenow['yday'] == 1)) {
1872 return get_string('yesterday', 'calendar');
1873 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] +
1 ) ||
1874 ($datestamp['year'] == $datenow['year'] +
1 && $datenow['mday'] == 31 && $datenow['mon'] == 12
1875 && $datestamp['yday'] == 1)) {
1876 return get_string('tomorrow', 'calendar');
1883 * return the formatted representation time.
1886 * @param int $time the timestamp in UTC, as obtained from the database
1887 * @return string the formatted date/time
1889 function calendar_time_representation($time) {
1890 static $langtimeformat = null;
1892 if ($langtimeformat === null) {
1893 $langtimeformat = get_string('strftimetime');
1896 $timeformat = get_user_preferences('calendar_timeformat');
1897 if (empty($timeformat)) {
1898 $timeformat = get_config(null, 'calendar_site_timeformat');
1901 // Allow language customization of selected time format.
1902 if ($timeformat === CALENDAR_TF_12
) {
1903 $timeformat = get_string('strftimetime12', 'langconfig');
1904 } else if ($timeformat === CALENDAR_TF_24
) {
1905 $timeformat = get_string('strftimetime24', 'langconfig');
1908 return userdate($time, empty($timeformat) ?
$langtimeformat : $timeformat);
1912 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1914 * @param string|moodle_url $linkbase
1915 * @param int $d The number of the day.
1916 * @param int $m The number of the month.
1917 * @param int $y The number of the year.
1918 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1919 * $m and $y are kept for backwards compatibility.
1920 * @return moodle_url|null $linkbase
1922 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1923 if (empty($linkbase)) {
1927 if (!($linkbase instanceof \moodle_url
)) {
1928 $linkbase = new \
moodle_url($linkbase);
1931 $linkbase->param('time', calendar_get_timestamp($d, $m, $y, $time));
1937 * Build and return a previous month HTML link, with an arrow.
1939 * @deprecated since Moodle 4.3
1940 * @param string $text The text label.
1941 * @param string|moodle_url $linkbase The URL stub.
1942 * @param int $d The number of the date.
1943 * @param int $m The number of the month.
1944 * @param int $y year The number of the year.
1945 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1946 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1947 * $m and $y are kept for backwards compatibility.
1948 * @return string HTML string.
1950 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1951 debugging(__FUNCTION__
. ' has been deprecated and should not be used anymore.', DEBUG_DEVELOPER
);
1953 $href = calendar_get_link_href(new \
moodle_url($linkbase), $d, $m, $y, $time);
1960 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1961 'data-drop-zone' => 'nav-link',
1964 return link_arrow_left($text, $href->out(false), $accesshide, 'previous', $attrs);
1968 * Build and return a next month HTML link, with an arrow.
1970 * @deprecated since Moodle 4.3
1971 * @param string $text The text label.
1972 * @param string|moodle_url $linkbase The URL stub.
1973 * @param int $d the number of the Day
1974 * @param int $m The number of the month.
1975 * @param int $y The number of the year.
1976 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1977 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1978 * $m and $y are kept for backwards compatibility.
1979 * @return string HTML string.
1981 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1982 debugging(__FUNCTION__
. ' has been deprecated and should not be used anymore.', DEBUG_DEVELOPER
);
1984 $href = calendar_get_link_href(new \
moodle_url($linkbase), $d, $m, $y, $time);
1991 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1992 'data-drop-zone' => 'nav-link',
1995 return link_arrow_right($text, $href->out(false), $accesshide, 'next', $attrs);
1999 * Return the number of days in month.
2001 * @param int $month the number of the month.
2002 * @param int $year the number of the year
2005 function calendar_days_in_month($month, $year) {
2006 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2007 return $calendartype->get_num_days_in_month($year, $month);
2011 * Get the next following month.
2013 * @param int $month the number of the month.
2014 * @param int $year the number of the year.
2015 * @return array the following month
2017 function calendar_add_month($month, $year) {
2018 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2019 return $calendartype->get_next_month($year, $month);
2023 * Get the previous month.
2025 * @param int $month the number of the month.
2026 * @param int $year the number of the year.
2027 * @return array previous month
2029 function calendar_sub_month($month, $year) {
2030 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2031 return $calendartype->get_prev_month($year, $month);
2035 * Get per-day basis events
2037 * @param array $events list of events
2038 * @param int $month the number of the month
2039 * @param int $year the number of the year
2040 * @param array $eventsbyday event on specific day
2041 * @param array $durationbyday duration of the event in days
2042 * @param array $typesbyday event type (eg: site, course, user, or group)
2043 * @param array $courses list of courses
2046 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
2047 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2049 $eventsbyday = array();
2050 $typesbyday = array();
2051 $durationbyday = array();
2053 if ($events === false) {
2057 foreach ($events as $event) {
2058 $startdate = $calendartype->timestamp_to_date_array($event->timestart
);
2059 if ($event->timeduration
) {
2060 $enddate = $calendartype->timestamp_to_date_array($event->timestart +
$event->timeduration
- 1);
2062 $enddate = $startdate;
2065 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair.
2066 if (!($startdate['year'] * 13 +
$startdate['mon'] <= $year * 13 +
$month) &&
2067 ($enddate['year'] * 13 +
$enddate['mon'] >= $year * 13 +
$month)) {
2071 $eventdaystart = intval($startdate['mday']);
2073 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2074 // Give the event to its day.
2075 $eventsbyday[$eventdaystart][] = $event->id
;
2077 // Mark the day as having such an event.
2078 if ($event->courseid
== SITEID
&& $event->groupid
== 0) {
2079 $typesbyday[$eventdaystart]['startsite'] = true;
2080 // Set event class for site event.
2081 $events[$event->id
]->class = 'calendar_event_site';
2082 } else if ($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) {
2083 $typesbyday[$eventdaystart]['startcourse'] = true;
2084 // Set event class for course event.
2085 $events[$event->id
]->class = 'calendar_event_course';
2086 } else if ($event->groupid
) {
2087 $typesbyday[$eventdaystart]['startgroup'] = true;
2088 // Set event class for group event.
2089 $events[$event->id
]->class = 'calendar_event_group';
2090 } else if ($event->userid
) {
2091 $typesbyday[$eventdaystart]['startuser'] = true;
2092 // Set event class for user event.
2093 $events[$event->id
]->class = 'calendar_event_user';
2097 if ($event->timeduration
== 0) {
2098 // Proceed with the next.
2102 // The event starts on $month $year or before.
2103 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2104 $lowerbound = intval($startdate['mday']);
2109 // Also, it ends on $month $year or later.
2110 if ($enddate['mon'] == $month && $enddate['year'] == $year) {
2111 $upperbound = intval($enddate['mday']);
2113 $upperbound = calendar_days_in_month($month, $year);
2116 // Mark all days between $lowerbound and $upperbound (inclusive) as duration.
2117 for ($i = $lowerbound +
1; $i <= $upperbound; ++
$i) {
2118 $durationbyday[$i][] = $event->id
;
2119 if ($event->courseid
== SITEID
&& $event->groupid
== 0) {
2120 $typesbyday[$i]['durationsite'] = true;
2121 } else if ($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) {
2122 $typesbyday[$i]['durationcourse'] = true;
2123 } else if ($event->groupid
) {
2124 $typesbyday[$i]['durationgroup'] = true;
2125 } else if ($event->userid
) {
2126 $typesbyday[$i]['durationuser'] = true;
2135 * Returns the courses to load events for.
2137 * @param array $courseeventsfrom An array of courses to load calendar events for
2138 * @param bool $ignorefilters specify the use of filters, false is set as default
2139 * @param stdClass $user The user object. This defaults to the global $USER object.
2140 * @return array An array of courses, groups, and user to load calendar events for based upon filters
2142 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false, ?stdClass
$user = null) {
2145 if (is_null($user)) {
2153 // Get the capabilities that allow seeing group events from all groups.
2154 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
2156 $isvaliduser = !empty($user->id
);
2158 if ($ignorefilters ||
calendar_show_event_type(CALENDAR_EVENT_COURSE
, $user)) {
2159 $courses = array_keys($courseeventsfrom);
2161 if ($ignorefilters ||
calendar_show_event_type(CALENDAR_EVENT_SITE
, $user)) {
2162 $courses[] = SITEID
;
2164 $courses = array_unique($courses);
2167 if (!empty($courses) && in_array(SITEID
, $courses)) {
2168 // Sort courses for consistent colour highlighting.
2169 // Effectively ignoring SITEID as setting as last course id.
2170 $key = array_search(SITEID
, $courses);
2171 unset($courses[$key]);
2172 $courses[] = SITEID
;
2175 if ($ignorefilters ||
($isvaliduser && calendar_show_event_type(CALENDAR_EVENT_USER
, $user))) {
2176 $userid = $user->id
;
2179 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP
, $user) ||
$ignorefilters)) {
2180 if (!empty($CFG->calendar_adminseesall
) && has_any_capability($allgroupscaps, \context_system
::instance())) {
2182 } else if ($isvaliduser) {
2184 foreach ($courseeventsfrom as $courseid => $course) {
2185 if ($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
2186 if (has_all_capabilities($allgroupscaps, \context_course
::instance($courseid))) {
2187 // User can access all groups in this course.
2188 // Get all the groups in this course.
2189 $coursegroups = groups_get_all_groups($course->id
, 0, 0, 'g.id');
2190 $groupids = array_merge($groupids, array_keys($coursegroups));
2192 // User can only access their own groups.
2193 // Get the groups the user is in.
2194 $coursegroups = groups_get_user_groups($course->id
, $user->id
);
2195 $groupids = array_merge($groupids, $coursegroups['0']);
2199 if (!empty($groupids)) {
2204 if (empty($courses)) {
2208 return array($courses, $group, $userid);
2212 * Can current user manage a non user event in system context.
2214 * @param calendar_event|stdClass $event event object
2217 function calendar_can_manage_non_user_event_in_system($event) {
2218 $sitecontext = \context_system
::instance();
2219 $isuserevent = $event->eventtype
== 'user';
2220 $canmanageentries = has_capability('moodle/calendar:manageentries', $sitecontext);
2221 // If user has manageentries at site level and it's not user event, return true.
2222 if ($canmanageentries && !$isuserevent) {
2230 * Return the capability for viewing a calendar event.
2232 * @param calendar_event $event event object
2235 function calendar_view_event_allowed(calendar_event
$event) {
2238 // Anyone can see site events.
2239 if ($event->courseid
&& $event->courseid
== SITEID
) {
2243 if (calendar_can_manage_non_user_event_in_system($event)) {
2247 if (!empty($event->groupid
)) {
2248 // If it is a group event we need to be able to manage events in the course, or be in the group.
2249 if (has_capability('moodle/calendar:manageentries', $event->context
) ||
2250 has_capability('moodle/calendar:managegroupentries', $event->context
)) {
2254 $mycourses = enrol_get_my_courses('id');
2255 return isset($mycourses[$event->courseid
]) && groups_is_member($event->groupid
);
2256 } else if ($event->modulename
) {
2257 // If this is a module event we need to be able to see the module.
2258 $coursemodules = [];
2260 // Override events do not have the courseid set.
2261 if ($event->courseid
) {
2262 $courseid = $event->courseid
;
2263 $coursemodules = get_fast_modinfo($event->courseid
)->instances
;
2265 $cmraw = get_coursemodule_from_instance($event->modulename
, $event->instance
, 0, false, MUST_EXIST
);
2266 $courseid = $cmraw->course
;
2267 $coursemodules = get_fast_modinfo($cmraw->course
)->instances
;
2269 $hasmodule = isset($coursemodules[$event->modulename
]);
2270 $hasinstance = isset($coursemodules[$event->modulename
][$event->instance
]);
2272 // If modinfo doesn't know about the module, return false to be safe.
2273 if (!$hasmodule ||
!$hasinstance) {
2277 // Must be able to see the course and the module - MDL-59304.
2278 $cm = $coursemodules[$event->modulename
][$event->instance
];
2279 if (!$cm->uservisible
) {
2282 $mycourses = enrol_get_my_courses('id');
2283 return isset($mycourses[$courseid]);
2284 } else if ($event->categoryid
) {
2285 // If this is a category we need to be able to see the category.
2286 $cat = \core_course_category
::get($event->categoryid
, IGNORE_MISSING
);
2291 } else if (!empty($event->courseid
)) {
2292 // If it is a course event we need to be able to manage events in the course, or be in the course.
2293 if (has_capability('moodle/calendar:manageentries', $event->context
)) {
2297 return can_access_course(get_course($event->courseid
));
2298 } else if ($event->userid
) {
2299 return calendar_can_manage_user_event($event);
2301 throw new moodle_exception('unknown event type');
2308 * Return the capability for editing calendar event.
2310 * @param calendar_event $event event object
2311 * @param bool $manualedit is the event being edited manually by the user
2312 * @return bool capability to edit event
2314 function calendar_edit_event_allowed($event, $manualedit = false) {
2317 // Must be logged in.
2318 if (!isloggedin()) {
2322 // Can not be using guest account.
2323 if (isguestuser()) {
2327 if ($manualedit && !empty($event->modulename
)) {
2328 $hascallback = component_callback_exists(
2329 'mod_' . $event->modulename
,
2330 'core_calendar_event_timestart_updated'
2333 if (!$hascallback) {
2334 // If the activity hasn't implemented the correct callback
2335 // to handle changes to it's events then don't allow any
2336 // manual changes to them.
2340 $coursemodules = get_fast_modinfo($event->courseid
)->instances
;
2341 $hasmodule = isset($coursemodules[$event->modulename
]);
2342 $hasinstance = isset($coursemodules[$event->modulename
][$event->instance
]);
2344 // If modinfo doesn't know about the module, return false to be safe.
2345 if (!$hasmodule ||
!$hasinstance) {
2349 $coursemodule = $coursemodules[$event->modulename
][$event->instance
];
2350 $context = context_module
::instance($coursemodule->id
);
2351 // This is the capability that allows a user to modify the activity
2352 // settings. Since the activity generated this event we need to check
2353 // that the current user has the same capability before allowing them
2354 // to update the event because the changes to the event will be
2355 // reflected within the activity.
2356 return has_capability('moodle/course:manageactivities', $context);
2359 if ($manualedit && !empty($event->component
)) {
2360 // TODO possibly we can later add a callback similar to core_calendar_event_timestart_updated in the modules.
2364 // You cannot edit URL based calendar subscription events presently.
2365 if (!empty($event->subscriptionid
)) {
2366 if (!empty($event->subscription
->url
)) {
2367 // This event can be updated externally, so it cannot be edited.
2372 if (calendar_can_manage_non_user_event_in_system($event)) {
2376 // If groupid is set, it's definitely a group event.
2377 if (!empty($event->groupid
)) {
2378 // Allow users to add/edit group events if -
2379 // 1) They have manageentries for the course OR
2380 // 2) They have managegroupentries AND are in the group.
2381 $group = $DB->get_record('groups', array('id' => $event->groupid
));
2383 has_capability('moodle/calendar:manageentries', $event->context
) ||
2384 (has_capability('moodle/calendar:managegroupentries', $event->context
)
2385 && groups_is_member($event->groupid
)));
2386 } else if (!empty($event->courseid
)) {
2387 // If groupid is not set, but course is set, it's definitely a course event.
2388 return has_capability('moodle/calendar:manageentries', $event->context
);
2389 } else if (!empty($event->categoryid
)) {
2390 // If groupid is not set, but category is set, it's definitely a category event.
2391 return has_capability('moodle/calendar:manageentries', $event->context
);
2392 } else if (!empty($event->userid
) && $event->userid
== $USER->id
) {
2393 // If course is not set, but userid id set, it's a user event.
2394 return (has_capability('moodle/calendar:manageownentries',
2395 context_user
::instance($event->userid
)));
2396 } else if (!empty($event->userid
)) {
2397 return calendar_can_manage_user_event($event);
2404 * Can current user edit/delete/add an user event?
2406 * @param calendar_event|stdClass $event event object
2409 function calendar_can_manage_user_event($event): bool {
2412 if (!($event instanceof \calendar_event
)) {
2413 $event = new \
calendar_event(clone($event));
2416 $canmanage = has_capability('moodle/calendar:manageentries', $event->context
);
2417 $canmanageown = has_capability('moodle/calendar:manageownentries', $event->context
);
2418 $ismyevent = $event->userid
== $USER->id
;
2419 $isadminevent = is_siteadmin($event->userid
);
2421 if ($canmanageown && $ismyevent) {
2425 // In site context, user must have login and calendar:manageentries permissions
2426 // ... to manage other user's events except admin users.
2427 if ($canmanage && !$isadminevent) {
2435 * Return the capability for deleting a calendar event.
2437 * @param calendar_event $event The event object
2438 * @return bool Whether the user has permission to delete the event or not.
2440 function calendar_delete_event_allowed($event) {
2441 // Only allow delete if you have capabilities and it is not an module or component event.
2442 return (calendar_edit_event_allowed($event) && empty($event->modulename
) && empty($event->component
));
2446 * Returns the default courses to display on the calendar when there isn't a specific
2447 * course to display.
2449 * @param int $courseid (optional) If passed, an additional course can be returned for admins (the current course).
2450 * @param string $fields Comma separated list of course fields to return.
2451 * @param bool $canmanage If true, this will return the list of courses the user can create events in, rather
2452 * than the list of courses they see events from (an admin can always add events in a course
2453 * calendar, even if they are not enrolled in the course).
2454 * @param int $userid (optional) The user which this function returns the default courses for.
2455 * By default the current user.
2456 * @return array $courses Array of courses to display
2458 function calendar_get_default_courses($courseid = null, $fields = '*', $canmanage = false, ?
int $userid = null) {
2462 if (!isloggedin()) {
2465 $userid = $USER->id
;
2468 if ((!empty($CFG->calendar_adminseesall
) ||
$canmanage) &&
2469 has_capability('moodle/calendar:manageentries', context_system
::instance(), $userid)) {
2471 // Add a c. prefix to every field as expected by get_courses function.
2472 $fieldlist = explode(',', $fields);
2474 $prefixedfields = array_map(function($value) {
2475 return 'c.' . trim(strtolower($value));
2478 $courses = get_courses('all', 'c.shortname', implode(',', $prefixedfields));
2480 $courses = enrol_get_users_courses($userid, true, $fields, 'c.shortname');
2483 if ($courseid && $courseid != SITEID
) {
2484 if (empty($courses[$courseid]) && has_capability('moodle/calendar:manageentries', context_system
::instance(), $userid)) {
2485 // Allow a site admin to see calendars from courses he is not enrolled in.
2486 // This will come from $COURSE.
2487 $courses[$courseid] = get_course($courseid);
2495 * Get event format time.
2497 * @param calendar_event $event event object
2498 * @param int $now current time in gmt
2499 * @param array $linkparams list of params for event link
2500 * @param bool $usecommonwords the words as formatted date/time.
2501 * @param int $showtime determine the show time GMT timestamp
2502 * @return string $eventtime link/string for event time
2504 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
2505 $starttime = $event->timestart
;
2506 $endtime = $event->timestart +
$event->timeduration
;
2508 if (empty($linkparams) ||
!is_array($linkparams)) {
2509 $linkparams = array();
2512 $linkparams['view'] = 'day';
2514 // OK, now to get a meaningful display.
2515 // Check if there is a duration for this event.
2516 if ($event->timeduration
) {
2517 // Get the midnight of the day the event will start.
2518 $usermidnightstart = usergetmidnight($starttime);
2519 // Get the midnight of the day the event will end.
2520 $usermidnightend = usergetmidnight($endtime);
2521 // Check if we will still be on the same day.
2522 if ($usermidnightstart == $usermidnightend) {
2523 // Check if we are running all day.
2524 if ($event->timeduration
== DAYSECS
) {
2525 $time = get_string('allday', 'calendar');
2526 } else { // Specify the time we will be running this from.
2527 $datestart = calendar_time_representation($starttime);
2528 $dateend = calendar_time_representation($endtime);
2529 $time = $datestart . ' <strong>»</strong> ' . $dateend;
2532 // Set printable representation.
2534 $day = calendar_day_representation($event->timestart
, $now, $usecommonwords);
2535 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $endtime);
2536 $eventtime = \html_writer
::link($url, $day) . ', ' . $time;
2540 } else { // It must spans two or more days.
2541 $daystart = calendar_day_representation($event->timestart
, $now, $usecommonwords) . ', ';
2542 if ($showtime == $usermidnightstart) {
2545 $timestart = calendar_time_representation($event->timestart
);
2546 $dayend = calendar_day_representation($event->timestart +
$event->timeduration
, $now, $usecommonwords) . ', ';
2547 if ($showtime == $usermidnightend) {
2550 $timeend = calendar_time_representation($event->timestart +
$event->timeduration
);
2552 // Set printable representation.
2553 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2554 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $endtime);
2555 $eventtime = $timestart . ' <strong>»</strong> ' . \html_writer
::link($url, $dayend) . $timeend;
2557 // The event is in the future, print start and end links.
2558 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $starttime);
2559 $eventtime = \html_writer
::link($url, $daystart) . $timestart . ' <strong>»</strong> ';
2561 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $endtime);
2562 $eventtime .= \html_writer
::link($url, $dayend) . $timeend;
2565 } else { // There is no time duration.
2566 $time = calendar_time_representation($event->timestart
);
2567 // Set printable representation.
2569 $day = calendar_day_representation($event->timestart
, $now, $usecommonwords);
2570 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $starttime);
2571 $eventtime = \html_writer
::link($url, $day) . ', ' . trim($time);
2577 // Check if It has expired.
2578 if ($event->timestart +
$event->timeduration
< $now) {
2579 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2586 * Format event location property
2588 * @param calendar_event $event
2591 function calendar_format_event_location(calendar_event
$event): string {
2592 $location = format_text($event->location
, FORMAT_PLAIN
, ['context' => $event->context
]);
2594 // If it looks like a link, convert it to one.
2595 if (preg_match('/^https?:\/\//i', $location) && clean_param($location, PARAM_URL
)) {
2596 $location = \html_writer
::link($location, $location, [
2597 'title' => get_string('eventnamelocation', 'core_calendar', ['name' => $event->name
, 'location' => $location]),
2605 * Checks to see if the requested type of event should be shown for the given user.
2607 * @param int $type The type to check the display for (default is to display all)
2608 * @param stdClass|int|null $user The user to check for - by default the current user
2609 * @return bool True if the tyep should be displayed false otherwise
2611 function calendar_show_event_type($type, $user = null) {
2612 $default = CALENDAR_EVENT_SITE + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER
;
2614 if ((int)get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2616 if (!isset($SESSION->calendarshoweventtype
)) {
2617 $SESSION->calendarshoweventtype
= $default;
2619 return $SESSION->calendarshoweventtype
& $type;
2621 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2626 * Sets the display of the event type given $display.
2628 * If $display = true the event type will be shown.
2629 * If $display = false the event type will NOT be shown.
2630 * If $display = null the current value will be toggled and saved.
2632 * @param int $type object of CALENDAR_EVENT_XXX
2633 * @param bool $display option to display event type
2634 * @param stdClass|int $user moodle user object or id, null means current user
2636 function calendar_set_event_type_display($type, $display = null, $user = null) {
2637 $persist = (int)get_user_preferences('calendar_persistflt', 0, $user);
2638 $default = CALENDAR_EVENT_SITE + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP
2639 + CALENDAR_EVENT_USER + CALENDAR_EVENT_COURSECAT
;
2640 if ($persist === 0) {
2642 if (!isset($SESSION->calendarshoweventtype
)) {
2643 $SESSION->calendarshoweventtype
= $default;
2645 $preference = $SESSION->calendarshoweventtype
;
2647 $preference = get_user_preferences('calendar_savedflt', $default, $user);
2649 $current = $preference & $type;
2650 if ($display === null) {
2651 $display = !$current;
2653 if ($display && !$current) {
2654 $preference +
= $type;
2655 } else if (!$display && $current) {
2656 $preference -= $type;
2658 if ($persist === 0) {
2659 $SESSION->calendarshoweventtype
= $preference;
2661 if ($preference == $default) {
2662 unset_user_preference('calendar_savedflt', $user);
2664 set_user_preference('calendar_savedflt', $preference, $user);
2670 * Get calendar's allowed types.
2672 * @param stdClass $allowed list of allowed edit for event type
2673 * @param stdClass|int $course object of a course or course id
2674 * @param array $groups array of groups for the given course
2675 * @param stdClass|int $category object of a category
2677 function calendar_get_allowed_types(&$allowed, $course = null, $groups = null, $category = null) {
2680 $allowed = new \
stdClass();
2681 $allowed->user
= has_capability('moodle/calendar:manageownentries', \context_system
::instance());
2682 $allowed->groups
= false;
2683 $allowed->courses
= false;
2684 $allowed->categories
= false;
2685 $allowed->site
= has_capability('moodle/calendar:manageentries', \context_course
::instance(SITEID
));
2686 $getgroupsfunc = function($course, $context, $user) use ($groups) {
2687 if ($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
2688 if (has_capability('moodle/site:accessallgroups', $context)) {
2689 return is_null($groups) ?
groups_get_all_groups($course->id
) : $groups;
2691 if (is_null($groups)) {
2692 return groups_get_all_groups($course->id
, $user->id
);
2694 return array_filter($groups, function($group) use ($user) {
2695 return isset($group->members
[$user->id
]);
2704 if (!empty($course)) {
2705 if (!is_object($course)) {
2706 $course = $DB->get_record('course', array('id' => $course), 'id, groupmode, groupmodeforce', MUST_EXIST
);
2708 if ($course->id
!= SITEID
) {
2709 $coursecontext = \context_course
::instance($course->id
);
2710 $allowed->user
= has_capability('moodle/calendar:manageownentries', $coursecontext);
2712 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2713 $allowed->courses
= array($course->id
=> 1);
2714 $allowed->groups
= $getgroupsfunc($course, $coursecontext, $USER);
2715 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
2716 $allowed->groups
= $getgroupsfunc($course, $coursecontext, $USER);
2721 if (!empty($category)) {
2722 $catcontext = \context_coursecat
::instance($category->id
);
2723 if (has_capability('moodle/category:manage', $catcontext)) {
2724 $allowed->categories
= [$category->id
=> 1];
2730 * See if user can add calendar entries at all used to print the "New Event" button.
2732 * @param stdClass $course object of a course or course id
2733 * @return bool has the capability to add at least one event type
2735 function calendar_user_can_add_event($course) {
2736 if (!isloggedin() ||
isguestuser()) {
2740 calendar_get_allowed_types($allowed, $course);
2742 return (bool)($allowed->user ||
$allowed->groups ||
$allowed->courses ||
$allowed->categories ||
$allowed->site
);
2746 * Check wether the current user is permitted to add events.
2748 * @param stdClass $event object of event
2749 * @return bool has the capability to add event
2751 function calendar_add_event_allowed($event) {
2754 // Can not be using guest account.
2755 if (!isloggedin() or isguestuser()) {
2759 if (calendar_can_manage_non_user_event_in_system($event)) {
2763 switch ($event->eventtype
) {
2765 return has_capability('moodle/category:manage', $event->context
);
2767 return has_capability('moodle/calendar:manageentries', $event->context
);
2769 // Allow users to add/edit group events if -
2770 // 1) They have manageentries (= entries for whole course).
2771 // 2) They have managegroupentries AND are in the group.
2772 $group = $DB->get_record('groups', array('id' => $event->groupid
));
2774 has_capability('moodle/calendar:manageentries', $event->context
) ||
2775 (has_capability('moodle/calendar:managegroupentries', $event->context
)
2776 && groups_is_member($event->groupid
)));
2778 return calendar_can_manage_user_event($event);
2780 return has_capability('moodle/calendar:manageentries', $event->context
);
2782 return has_capability('moodle/calendar:manageentries', $event->context
);
2787 * Returns option list for the poll interval setting.
2789 * @return array An array of poll interval options. Interval => description.
2791 function calendar_get_pollinterval_choices() {
2793 '0' => get_string('never', 'calendar'),
2794 HOURSECS
=> get_string('hourly', 'calendar'),
2795 DAYSECS
=> get_string('daily', 'calendar'),
2796 WEEKSECS
=> get_string('weekly', 'calendar'),
2797 '2628000' => get_string('monthly', 'calendar'),
2798 YEARSECS
=> get_string('annually', 'calendar')
2803 * Returns option list of available options for the calendar event type, given the current user and course.
2805 * @param int $courseid The id of the course
2806 * @return array An array containing the event types the user can create.
2808 function calendar_get_eventtype_choices($courseid) {
2810 $allowed = new \stdClass
;
2811 calendar_get_allowed_types($allowed, $courseid);
2813 if ($allowed->user
) {
2814 $choices['user'] = get_string('userevents', 'calendar');
2816 if ($allowed->site
) {
2817 $choices['site'] = get_string('siteevents', 'calendar');
2819 if (!empty($allowed->courses
)) {
2820 $choices['course'] = get_string('courseevents', 'calendar');
2822 if (!empty($allowed->categories
)) {
2823 $choices['category'] = get_string('categoryevents', 'calendar');
2825 if (!empty($allowed->groups
) and is_array($allowed->groups
)) {
2826 $choices['group'] = get_string('group');
2829 return array($choices, $allowed->groups
);
2833 * Add an iCalendar subscription to the database.
2835 * @param stdClass $sub The subscription object (e.g. from the form)
2836 * @return int The insert ID, if any.
2838 function calendar_add_subscription($sub) {
2839 global $DB, $USER, $SITE;
2841 // Undo the form definition work around to allow us to have two different
2842 // course selectors present depending on which event type the user selects.
2843 if (!empty($sub->groupcourseid
)) {
2844 $sub->courseid
= $sub->groupcourseid
;
2845 unset($sub->groupcourseid
);
2848 // Default course id if none is set.
2849 if (empty($sub->courseid
)) {
2850 if ($sub->eventtype
=== 'site') {
2851 $sub->courseid
= SITEID
;
2857 if ($sub->eventtype
=== 'site') {
2858 $sub->courseid
= $SITE->id
;
2859 } else if ($sub->eventtype
=== 'group' ||
$sub->eventtype
=== 'course') {
2860 $sub->courseid
= $sub->courseid
;
2861 } else if ($sub->eventtype
=== 'category') {
2862 $sub->categoryid
= $sub->categoryid
;
2867 $sub->userid
= $USER->id
;
2869 // File subscriptions never update.
2870 if (empty($sub->url
)) {
2871 $sub->pollinterval
= 0;
2874 if (!empty($sub->name
)) {
2875 if (empty($sub->id
)) {
2876 $id = $DB->insert_record('event_subscriptions', $sub);
2877 // We cannot cache the data here because $sub is not complete.
2879 // Trigger event, calendar subscription added.
2880 $eventparams = array('objectid' => $sub->id
,
2881 'context' => calendar_get_calendar_context($sub),
2883 'eventtype' => $sub->eventtype
,
2886 switch ($sub->eventtype
) {
2888 $eventparams['other']['categoryid'] = $sub->categoryid
;
2891 $eventparams['other']['courseid'] = $sub->courseid
;
2894 $eventparams['other']['courseid'] = $sub->courseid
;
2895 $eventparams['other']['groupid'] = $sub->groupid
;
2898 $eventparams['other']['courseid'] = $sub->courseid
;
2901 $event = \core\event\calendar_subscription_created
::create($eventparams);
2905 // Why are we doing an update here?
2906 calendar_update_subscription($sub);
2910 throw new \
moodle_exception('errorbadsubscription', 'importcalendar');
2915 * Add an iCalendar event to the Moodle calendar.
2917 * @param stdClass $event The RFC-2445 iCalendar event
2918 * @param int $unused Deprecated
2919 * @param int $subscriptionid The iCalendar subscription ID
2920 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2921 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2922 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2924 function calendar_add_icalendar_event($event, $unused, $subscriptionid, $timezone='UTC') {
2927 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2928 if (empty($event->properties
['SUMMARY'])) {
2932 $name = $event->properties
['SUMMARY'][0]->value
;
2933 $name = str_replace('\n', '<br />', $name);
2934 $name = str_replace('\\', '', $name);
2935 $name = preg_replace('/\s+/u', ' ', $name);
2937 $eventrecord = new \stdClass
;
2938 $eventrecord->name
= clean_param($name, PARAM_NOTAGS
);
2940 if (empty($event->properties
['DESCRIPTION'][0]->value
)) {
2943 $description = $event->properties
['DESCRIPTION'][0]->value
;
2944 $description = clean_param($description, PARAM_NOTAGS
);
2945 $description = str_replace('\n', '<br />', $description);
2946 $description = str_replace('\\', '', $description);
2947 $description = preg_replace('/\s+/u', ' ', $description);
2949 $eventrecord->description
= $description;
2951 // Probably a repeating event with RRULE etc. TODO: skip for now.
2952 if (empty($event->properties
['DTSTART'][0]->value
)) {
2956 if (isset($event->properties
['DTSTART'][0]->parameters
['TZID'])) {
2957 $tz = $event->properties
['DTSTART'][0]->parameters
['TZID'];
2961 $tz = \core_date
::normalise_timezone($tz);
2962 $eventrecord->timestart
= strtotime($event->properties
['DTSTART'][0]->value
. ' ' . $tz);
2963 if (empty($event->properties
['DTEND'])) {
2964 $eventrecord->timeduration
= 0; // No duration if no end time specified.
2966 if (isset($event->properties
['DTEND'][0]->parameters
['TZID'])) {
2967 $endtz = $event->properties
['DTEND'][0]->parameters
['TZID'];
2971 $endtz = \core_date
::normalise_timezone($endtz);
2972 $eventrecord->timeduration
= strtotime($event->properties
['DTEND'][0]->value
. ' ' . $endtz) - $eventrecord->timestart
;
2975 // Check to see if it should be treated as an all day event.
2976 if ($eventrecord->timeduration
== DAYSECS
) {
2977 // Check to see if the event started at Midnight on the imported calendar.
2978 date_default_timezone_set($timezone);
2979 if (date('H:i:s', $eventrecord->timestart
) === "00:00:00") {
2980 // This event should be an all day event. This is not correct, we don't do anything differently for all day events.
2982 $eventrecord->timeduration
= 0;
2984 \core_date
::set_default_server_timezone();
2987 $eventrecord->location
= empty($event->properties
['LOCATION'][0]->value
) ?
'' :
2988 trim(str_replace('\\', '', $event->properties
['LOCATION'][0]->value
));
2989 $eventrecord->uuid
= $event->properties
['UID'][0]->value
;
2990 $eventrecord->timemodified
= time();
2992 // Add the iCal subscription details if required.
2993 // We should never do anything with an event without a subscription reference.
2994 $sub = calendar_get_subscription($subscriptionid);
2995 $eventrecord->subscriptionid
= $subscriptionid;
2996 $eventrecord->userid
= $sub->userid
;
2997 $eventrecord->groupid
= $sub->groupid
;
2998 $eventrecord->courseid
= $sub->courseid
;
2999 $eventrecord->categoryid
= $sub->categoryid
;
3000 $eventrecord->eventtype
= $sub->eventtype
;
3002 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid
,
3003 'subscriptionid' => $eventrecord->subscriptionid
))) {
3005 // Compare iCal event data against the moodle event to see if something has changed.
3006 $result = array_diff((array) $eventrecord, (array) $updaterecord);
3008 // Unset timemodified field because it's always going to be different.
3009 unset($result['timemodified']);
3011 if (count($result)) {
3012 $eventrecord->id
= $updaterecord->id
;
3013 $return = CALENDAR_IMPORT_EVENT_UPDATED
; // Update.
3015 return CALENDAR_IMPORT_EVENT_SKIPPED
;
3018 $return = CALENDAR_IMPORT_EVENT_INSERTED
; // Insert.
3021 if ($createdevent = \calendar_event
::create($eventrecord, false)) {
3022 if (!empty($event->properties
['RRULE'])) {
3023 // Repeating events.
3024 date_default_timezone_set($tz); // Change time zone to parse all events.
3025 $rrule = new \core_calendar\rrule_manager
($event->properties
['RRULE'][0]->value
);
3026 $rrule->parse_rrule();
3027 $rrule->create_events($createdevent);
3028 \core_date
::set_default_server_timezone(); // Change time zone back to what it was.
3037 * Delete subscription and all related events.
3039 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
3041 function calendar_delete_subscription($subscription) {
3044 if (!is_object($subscription)) {
3045 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST
);
3048 // Delete subscription and related events.
3049 $DB->delete_records('event', array('subscriptionid' => $subscription->id
));
3050 $DB->delete_records('event_subscriptions', array('id' => $subscription->id
));
3051 \cache_helper
::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id
));
3053 // Trigger event, calendar subscription deleted.
3054 $eventparams = array('objectid' => $subscription->id
,
3055 'context' => calendar_get_calendar_context($subscription),
3057 'eventtype' => $subscription->eventtype
,
3060 switch ($subscription->eventtype
) {
3062 $eventparams['other']['categoryid'] = $subscription->categoryid
;
3065 $eventparams['other']['courseid'] = $subscription->courseid
;
3068 $eventparams['other']['courseid'] = $subscription->courseid
;
3069 $eventparams['other']['groupid'] = $subscription->groupid
;
3072 $eventparams['other']['courseid'] = $subscription->courseid
;
3074 $event = \core\event\calendar_subscription_deleted
::create($eventparams);
3079 * From a URL, fetch the calendar and return an iCalendar object.
3081 * @param string $url The iCalendar URL
3082 * @return iCalendar The iCalendar object
3084 function calendar_get_icalendar($url) {
3087 require_once($CFG->libdir
. '/filelib.php');
3088 require_once($CFG->libdir
. '/bennu/bennu.inc.php');
3090 $curl = new \
curl();
3091 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
3092 $calendar = $curl->get($url);
3094 // Http code validation should actually be the job of curl class.
3095 if (!$calendar ||
$curl->info
['http_code'] != 200 ||
!empty($curl->errorno
)) {
3096 throw new \
moodle_exception('errorinvalidicalurl', 'calendar');
3099 $ical = new \
iCalendar();
3100 $ical->unserialize($calendar);
3106 * Import events from an iCalendar object into a course calendar.
3108 * @param iCalendar $ical The iCalendar object.
3109 * @param int|null $subscriptionid The subscription ID.
3110 * @return array A log of the import progress, including errors.
3112 function calendar_import_events_from_ical(iCalendar
$ical, ?
int $subscriptionid = null): array {
3121 // Large calendars take a while...
3123 \core_php_time_limit
::raise(300);
3126 // Start with a safe default timezone.
3129 // Grab the timezone from the iCalendar file to be used later.
3130 if (isset($ical->properties
['X-WR-TIMEZONE'][0]->value
)) {
3131 $timezone = $ical->properties
['X-WR-TIMEZONE'][0]->value
;
3133 } else if (isset($ical->properties
['PRODID'][0]->value
)) {
3134 // If the timezone was not found, check to se if this is MS exchange / Office 365 which uses Windows timezones.
3135 if (strncmp($ical->properties
['PRODID'][0]->value
, 'Microsoft', 9) == 0) {
3136 if (isset($ical->components
['VTIMEZONE'][0]->properties
['TZID'][0]->value
)) {
3137 $tzname = $ical->components
['VTIMEZONE'][0]->properties
['TZID'][0]->value
;
3138 $timezone = IntlTimeZone
::getIDForWindowsID($tzname);
3144 foreach ($ical->components
['VEVENT'] as $event) {
3145 $icaluuids[] = $event->properties
['UID'][0]->value
;
3146 $res = calendar_add_icalendar_event($event, null, $subscriptionid, $timezone);
3148 case CALENDAR_IMPORT_EVENT_UPDATED
:
3151 case CALENDAR_IMPORT_EVENT_INSERTED
:
3154 case CALENDAR_IMPORT_EVENT_SKIPPED
:
3158 if (empty($event->properties
['SUMMARY'])) {
3159 $errors[] = '(' . get_string('notitle', 'calendar') . ')';
3161 $errors[] = $event->properties
['SUMMARY'][0]->value
;
3167 $existing = $DB->get_field('event_subscriptions', 'lastupdated', ['id' => $subscriptionid]);
3168 if (!empty($existing)) {
3169 $eventsuuids = $DB->get_records_menu('event', ['subscriptionid' => $subscriptionid], '', 'id, uuid');
3171 $icaleventscount = count($icaluuids);
3173 if (count($eventsuuids) > $icaleventscount) {
3174 foreach ($eventsuuids as $eventid => $eventuuid) {
3175 if (!in_array($eventuuid, $icaluuids)) {
3176 $tobedeleted[] = $eventid;
3179 if (!empty($tobedeleted)) {
3180 $DB->delete_records_list('event', 'id', $tobedeleted);
3181 $deletedcount = count($tobedeleted);
3187 'eventsimported' => $eventcount,
3188 'eventsskipped' => $skippedcount,
3189 'eventsupdated' => $updatecount,
3190 'eventsdeleted' => $deletedcount,
3191 'haserror' => !empty($errors),
3192 'errors' => $errors,
3199 * Fetch a calendar subscription and update the events in the calendar.
3201 * @param int $subscriptionid The course ID for the calendar.
3202 * @return array A log of the import progress, including errors.
3204 function calendar_update_subscription_events($subscriptionid) {
3205 $sub = calendar_get_subscription($subscriptionid);
3207 // Don't update a file subscription.
3208 if (empty($sub->url
)) {
3209 return 'File subscription not updated.';
3212 $ical = calendar_get_icalendar($sub->url
);
3213 $return = calendar_import_events_from_ical($ical, $subscriptionid);
3214 $sub->lastupdated
= time();
3216 calendar_update_subscription($sub);
3222 * Update a calendar subscription. Also updates the associated cache.
3224 * @param stdClass|array $subscription Subscription record.
3225 * @throws coding_exception If something goes wrong
3228 function calendar_update_subscription($subscription) {
3231 if (is_array($subscription)) {
3232 $subscription = (object)$subscription;
3234 if (empty($subscription->id
) ||
!$DB->record_exists('event_subscriptions', array('id' => $subscription->id
))) {
3235 throw new \
coding_exception('Cannot update a subscription without a valid id');
3238 $DB->update_record('event_subscriptions', $subscription);
3241 $cache = \cache
::make('core', 'calendar_subscriptions');
3242 $cache->set($subscription->id
, $subscription);
3244 // Trigger event, calendar subscription updated.
3245 $eventparams = array('userid' => $subscription->userid
,
3246 'objectid' => $subscription->id
,
3247 'context' => calendar_get_calendar_context($subscription),
3249 'eventtype' => $subscription->eventtype
,
3252 switch ($subscription->eventtype
) {
3254 $eventparams['other']['categoryid'] = $subscription->categoryid
;
3257 $eventparams['other']['courseid'] = $subscription->courseid
;
3260 $eventparams['other']['courseid'] = $subscription->courseid
;
3261 $eventparams['other']['groupid'] = $subscription->groupid
;
3264 $eventparams['other']['courseid'] = $subscription->courseid
;
3266 $event = \core\event\calendar_subscription_updated
::create($eventparams);
3271 * Checks to see if the user can edit a given subscription feed.
3273 * @param mixed $subscriptionorid Subscription object or id
3274 * @return bool true if current user can edit the subscription else false
3276 function calendar_can_edit_subscription($subscriptionorid) {
3278 if (is_array($subscriptionorid)) {
3279 $subscription = (object)$subscriptionorid;
3280 } else if (is_object($subscriptionorid)) {
3281 $subscription = $subscriptionorid;
3283 $subscription = calendar_get_subscription($subscriptionorid);
3286 $allowed = new \stdClass
;
3287 $courseid = $subscription->courseid
;
3288 $categoryid = $subscription->categoryid
;
3289 $groupid = $subscription->groupid
;
3292 if (!empty($categoryid)) {
3293 $category = \core_course_category
::get($categoryid);
3295 calendar_get_allowed_types($allowed, $courseid, null, $category);
3296 switch ($subscription->eventtype
) {
3298 return ($USER->id
== $subscription->userid
&& $allowed->user
);
3300 if (isset($allowed->courses
[$courseid])) {
3301 return $allowed->courses
[$courseid];
3306 if (isset($allowed->categories
[$categoryid])) {
3307 return $allowed->categories
[$categoryid];
3312 return $allowed->site
;
3314 if (isset($allowed->groups
[$groupid])) {
3315 return $allowed->groups
[$groupid];
3325 * Helper function to determine the context of a calendar subscription.
3326 * Subscriptions can be created in two contexts COURSE, or USER.
3328 * @param stdClass $subscription
3329 * @return context instance
3331 function calendar_get_calendar_context($subscription) {
3332 // Determine context based on calendar type.
3333 if ($subscription->eventtype
=== 'site') {
3334 $context = \context_course
::instance(SITEID
);
3335 } else if ($subscription->eventtype
=== 'group' ||
$subscription->eventtype
=== 'course') {
3336 $context = \context_course
::instance($subscription->courseid
);
3338 $context = \context_user
::instance($subscription->userid
);
3344 * Implements callback user_preferences, lists preferences that users are allowed to update directly
3346 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3350 function core_calendar_user_preferences() {
3352 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS
, 'null' => NULL_NOT_ALLOWED
, 'default' => '0',
3353 'choices' => array('0', CALENDAR_TF_12
, CALENDAR_TF_24
)
3355 $preferences['calendar_startwday'] = array('type' => PARAM_INT
, 'null' => NULL_NOT_ALLOWED
, 'default' => 0,
3356 'choices' => array(0, 1, 2, 3, 4, 5, 6));
3357 $preferences['calendar_maxevents'] = array('type' => PARAM_INT
, 'choices' => range(1, 20));
3358 $preferences['calendar_lookahead'] = array('type' => PARAM_INT
, 'null' => NULL_NOT_ALLOWED
, 'default' => 365,
3359 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3360 $preferences['calendar_persistflt'] = array('type' => PARAM_INT
, 'null' => NULL_NOT_ALLOWED
, 'default' => 0,
3361 'choices' => array(0, 1));
3362 return $preferences;
3366 * Get legacy calendar events
3368 * @param int $tstart Start time of time range for events
3369 * @param int $tend End time of time range for events
3370 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3371 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3372 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3373 * @param boolean $withduration whether only events starting within time range selected
3374 * or events in progress/already started selected as well
3375 * @param boolean $ignorehidden whether to select only visible events or all events
3376 * @param array $categories array of category ids and/or objects.
3377 * @param int $limitnum Number of events to fetch or zero to fetch all.
3379 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3381 function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses,
3382 $withduration = true, $ignorehidden = true, $categories = [], $limitnum = 0) {
3383 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3384 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3385 // parameters, but with the new API method, only null and arrays are accepted.
3386 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3387 // If parameter is true, return null.
3388 if ($param === true) {
3392 // If parameter is false, return an empty array.
3393 if ($param === false) {
3397 // If the parameter is a scalar value, enclose it in an array.
3398 if (!is_array($param)) {
3402 // No normalisation required.
3404 }, [$users, $groups, $courses, $categories]);
3406 // If a single user is provided, we can use that for capability checks.
3407 // Otherwise current logged in user is used - See MDL-58768.
3408 if (is_array($userparam) && count($userparam) == 1) {
3409 \core_calendar\local\event\container
::set_requesting_user($userparam[0]);
3411 $mapper = \core_calendar\local\event\container
::get_event_mapper();
3412 $events = \core_calendar\local\api
::get_events(
3429 return array_reduce($events, function($carry, $event) use ($mapper) {
3430 return $carry +
[$event->get_id() => $mapper->from_event_to_stdclass($event)];
3436 * Get the calendar view output.
3438 * @param \calendar_information $calendar The calendar being represented
3439 * @param string $view The type of calendar to have displayed
3440 * @param bool $includenavigation Whether to include navigation
3441 * @param bool $skipevents Whether to load the events or not
3442 * @param int $lookahead Overwrites site and users's lookahead setting.
3443 * @return array[array, string]
3445 function calendar_get_view(\calendar_information
$calendar, $view, $includenavigation = true, bool $skipevents = false,
3446 ?
int $lookahead = null) {
3449 $renderer = $PAGE->get_renderer('core_calendar');
3450 $type = \core_calendar\type_factory
::get_calendar_instance();
3452 // Calculate the bounds of the month.
3453 $calendardate = $type->timestamp_to_date_array($calendar->time
);
3455 $date = new \
DateTime('now', core_date
::get_user_timezone_object(99));
3458 if ($view === 'day') {
3459 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday']);
3460 $date->setTimestamp($tstart);
3461 $date->modify('+1 day');
3462 } else if ($view === 'upcoming' ||
$view === 'upcoming_mini') {
3463 // Number of days in the future that will be used to fetch events.
3465 if (isset($CFG->calendar_lookahead
)) {
3466 $defaultlookahead = intval($CFG->calendar_lookahead
);
3468 $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD
;
3470 $lookahead = get_user_preferences('calendar_lookahead', $defaultlookahead);
3473 // Maximum number of events to be displayed on upcoming view.
3474 $defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS
;
3475 if (isset($CFG->calendar_maxevents
)) {
3476 $defaultmaxevents = intval($CFG->calendar_maxevents
);
3478 $eventlimit = get_user_preferences('calendar_maxevents', $defaultmaxevents);
3480 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday'],
3481 $calendardate['hours']);
3482 $date->setTimestamp($tstart);
3483 $date->modify('+' . $lookahead . ' days');
3485 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], 1);
3486 $monthdays = $type->get_num_days_in_month($calendardate['year'], $calendardate['mon']);
3487 $date->setTimestamp($tstart);
3488 $date->modify('+' . $monthdays . ' days');
3490 if ($view === 'mini' ||
$view === 'minithree') {
3491 $template = 'core_calendar/calendar_mini';
3493 $template = 'core_calendar/calendar_month';
3497 // We need to extract 1 second to ensure that we don't get into the next day.
3498 $date->modify('-1 second');
3499 $tend = $date->getTimestamp();
3501 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3502 // If parameter is true, return null.
3503 if ($param === true) {
3507 // If parameter is false, return an empty array.
3508 if ($param === false) {
3512 // If the parameter is a scalar value, enclose it in an array.
3513 if (!is_array($param)) {
3517 // No normalisation required.
3519 }, [$calendar->users
, $calendar->groups
, $calendar->courses
, $calendar->categories
]);
3524 $events = \core_calendar\local\api
::get_events(
3540 if ($proxy = $event->get_course_module()) {
3541 $cminfo = $proxy->get_proxied_instance();
3542 return $cminfo->uservisible
;
3545 if ($proxy = $event->get_category()) {
3546 $category = $proxy->get_proxied_instance();
3548 return $category->is_uservisible();
3557 'events' => $events,
3558 'cache' => new \core_calendar\external\
events_related_objects_cache($events),
3563 $calendar->set_viewmode($view);
3564 if ($view == "month" ||
$view == "monthblock" ||
$view == "mini" ||
$view == "minithree" ) {
3565 $month = new \core_calendar\external\
month_exporter($calendar, $type, $related);
3566 $month->set_includenavigation($includenavigation);
3567 $month->set_initialeventsloaded(!$skipevents);
3568 $month->set_showcoursefilter(($view == "month" ||
$view == "monthblock"));
3569 $data = $month->export($renderer);
3570 } else if ($view == "day") {
3571 $day = new \core_calendar\external\
calendar_day_exporter($calendar, $related);
3572 $data = $day->export($renderer);
3573 $data->viewingday
= true;
3574 $data->showviewselector
= true;
3575 $template = 'core_calendar/calendar_day';
3576 } else if ($view == "upcoming" ||
$view == "upcoming_mini") {
3577 $upcoming = new \core_calendar\external\
calendar_upcoming_exporter($calendar, $related);
3578 $data = $upcoming->export($renderer);
3580 if ($view == "upcoming") {
3581 $template = 'core_calendar/calendar_upcoming';
3582 $data->viewingupcoming
= true;
3583 $data->showviewselector
= true;
3584 } else if ($view == "upcoming_mini") {
3585 $template = 'core_calendar/calendar_upcoming_mini';
3589 // Check if $data has events.
3590 if (isset($data->events
)) {
3591 // Let's check and sanitize all "name" in $data->events before it's sent to front end.
3592 foreach ($data->events
as $d) {
3593 $name = $d->name ??
null;
3594 // Encode special characters if our decoded name does not match the original name.
3595 if ($name && (html_entity_decode($name) !== $name)) {
3596 $d->name
= htmlspecialchars(html_entity_decode($name), ENT_QUOTES
, 'utf-8');
3601 return [$data, $template];
3605 * Request and render event form fragment.
3607 * @param array $args The fragment arguments.
3608 * @return string The rendered mform fragment.
3610 function calendar_output_fragment_event_form($args) {
3611 global $CFG, $OUTPUT, $USER;
3612 require_once($CFG->libdir
. '/grouplib.php');
3615 $eventid = isset($args['eventid']) ?
clean_param($args['eventid'], PARAM_INT
) : null;
3616 $starttime = isset($args['starttime']) ?
clean_param($args['starttime'], PARAM_INT
) : null;
3617 $courseid = (isset($args['courseid']) && $args['courseid'] != SITEID
) ?
clean_param($args['courseid'], PARAM_INT
) : null;
3618 $categoryid = isset($args['categoryid']) ?
clean_param($args['categoryid'], PARAM_INT
) : null;
3620 $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
3621 $context = \context_user
::instance($USER->id
);
3622 $editoroptions = \core_calendar\local\event\forms\create
::build_editor_options($context);
3623 $formoptions = ['editoroptions' => $editoroptions, 'courseid' => $courseid];
3627 parse_str(clean_param($args['formdata'], PARAM_TEXT
), $data);
3628 if (isset($data['description']['itemid'])) {
3629 $draftitemid = $data['description']['itemid'];
3634 $formoptions['starttime'] = $starttime;
3636 // Let's check first which event types user can add.
3637 $eventtypes = calendar_get_allowed_event_types($courseid);
3638 $formoptions['eventtypes'] = $eventtypes;
3640 if (is_null($eventid)) {
3641 if (!empty($courseid)) {
3642 $groupcoursedata = groups_get_course_data($courseid);
3643 $formoptions['groups'] = [];
3644 foreach ($groupcoursedata->groups
as $groupid => $groupdata) {
3645 $formoptions['groups'][$groupid] = $groupdata->name
;
3649 $mform = new \core_calendar\local\event\forms\
create(
3659 // If the user is on course context and is allowed to add course events set the event type default to course.
3660 if (!empty($courseid) && !empty($eventtypes['course'])) {
3661 $data['eventtype'] = 'course';
3662 $data['courseid'] = $courseid;
3663 $data['groupcourseid'] = $courseid;
3664 } else if (!empty($categoryid) && !empty($eventtypes['category'])) {
3665 $data['eventtype'] = 'category';
3666 $data['categoryid'] = $categoryid;
3667 } else if (!empty($groupcoursedata) && !empty($eventtypes['group'])) {
3668 $data['groupcourseid'] = $courseid;
3669 $data['groups'] = $groupcoursedata->groups
;
3671 $mform->set_data($data);
3673 $event = calendar_event
::load($eventid);
3675 if (!calendar_edit_event_allowed($event)) {
3676 throw new \
moodle_exception('nopermissiontoupdatecalendar');
3679 $mapper = new \core_calendar\local\event\mappers\
create_update_form_mapper();
3680 $eventdata = $mapper->from_legacy_event_to_data($event);
3681 $data = array_merge((array) $eventdata, $data);
3682 $event->count_repeats();
3683 $formoptions['event'] = $event;
3685 if (!empty($event->courseid
)) {
3686 $groupcoursedata = groups_get_course_data($event->courseid
);
3687 $formoptions['groups'] = [];
3688 foreach ($groupcoursedata->groups
as $groupid => $groupdata) {
3689 $formoptions['groups'][$groupid] = $groupdata->name
;
3693 $data['description']['text'] = file_prepare_draft_area(
3695 $event->context
->id
,
3697 'event_description',
3700 $data['description']['text']
3702 $data['description']['itemid'] = $draftitemid;
3704 $mform = new \core_calendar\local\event\forms\
update(
3713 $mform->set_data($data);
3715 // Check to see if this event is part of a subscription or import.
3716 // If so display a warning on edit.
3717 if (isset($event->subscriptionid
) && ($event->subscriptionid
!= null)) {
3718 $renderable = new \core\output\notification
(
3719 get_string('eventsubscriptioneditwarning', 'calendar'),
3720 \core\output\notification
::NOTIFY_INFO
3723 $html .= $OUTPUT->render($renderable);
3728 $mform->is_validated();
3731 $html .= $mform->render();
3736 * Calculate the timestamp from the supplied Gregorian Year, Month, and Day.
3738 * @param int $d The day
3739 * @param int $m The month
3740 * @param int $y The year
3741 * @param int $time The timestamp to use instead of a separate y/m/d.
3742 * @return int The timestamp
3744 function calendar_get_timestamp($d, $m, $y, $time = 0) {
3745 // If a day, month and year were passed then convert it to a timestamp. If these were passed
3746 // then we can assume the day, month and year are passed as Gregorian, as no where in core
3747 // should we be passing these values rather than the time.
3748 if (!empty($d) && !empty($m) && !empty($y)) {
3749 if (checkdate($m, $d, $y)) {
3750 $time = make_timestamp($y, $m, $d);
3754 } else if (empty($time)) {
3762 * Get the calendar footer options.
3764 * @param calendar_information $calendar The calendar information object.
3765 * @param array $options Display options for the footer. If an option is not set, a default value will be provided.
3767 * - showfullcalendarlink - bool - Whether to show the full calendar link or not. Defaults to false.
3769 * @return array The data for template and template name.
3771 function calendar_get_footer_options($calendar, array $options = []) {
3772 global $CFG, $USER, $PAGE;
3774 // Generate hash for iCal link.
3775 $authtoken = calendar_get_export_token($USER);
3777 $renderer = $PAGE->get_renderer('core_calendar');
3778 $footer = new \core_calendar\external\footer_options_exporter
($calendar, $USER->id
, $authtoken, $options);
3779 $data = $footer->export($renderer);
3780 $template = 'core_calendar/footer_options';
3782 return [$data, $template];
3786 * Get the list of potential calendar filter types as a type => name
3791 function calendar_get_filter_types() {
3801 return array_map(function($type) {
3803 'eventtype' => $type,
3804 'name' => get_string("eventtype{$type}", "calendar"),
3806 'key' => 'i/' . $type . 'event',
3807 'component' => 'core'
3813 * Check whether the specified event type is valid.
3815 * @param string $type
3818 function calendar_is_valid_eventtype($type) {
3826 return in_array($type, $validtypes);
3830 * Get event types the user can create event based on categories, courses and groups
3831 * the logged in user belongs to.
3833 * @param int|null $courseid The course id.
3834 * @return array The array of allowed types.
3836 function calendar_get_allowed_event_types(?
int $courseid = null) {
3837 global $DB, $CFG, $USER;
3847 if (!empty($courseid) && $courseid != SITEID
) {
3848 $context = \context_course
::instance($courseid);
3849 $types['user'] = has_capability('moodle/calendar:manageownentries', $context);
3850 calendar_internal_update_course_and_group_permission($courseid, $context, $types);
3853 if (has_capability('moodle/calendar:manageentries', \context_course
::instance(SITEID
))) {
3854 $types['site'] = true;
3857 if (has_capability('moodle/calendar:manageownentries', \context_system
::instance())) {
3858 $types['user'] = true;
3860 if (core_course_category
::has_manage_capability_on_any()) {
3861 $types['category'] = true;
3864 // We still don't know if the user can create group and course events, so iterate over the courses to find out
3865 // if the user has capabilities in one of the courses.
3866 if ($types['course'] == false ||
$types['group'] == false) {
3867 if ($CFG->calendar_adminseesall
&& has_capability('moodle/calendar:manageentries', context_system
::instance())) {
3868 $sql = "SELECT c.id, " . context_helper
::get_preload_record_columns_sql('ctx') . "
3870 JOIN {context} ctx ON ctx.contextlevel = ? AND ctx.instanceid = c.id
3872 SELECT DISTINCT courseid FROM {groups}
3874 $courseswithgroups = $DB->get_recordset_sql($sql, [CONTEXT_COURSE
]);
3875 foreach ($courseswithgroups as $course) {
3876 context_helper
::preload_from_record($course);
3877 $context = context_course
::instance($course->id
);
3879 if (has_capability('moodle/calendar:manageentries', $context)) {
3880 if (has_any_capability(['moodle/site:accessallgroups', 'moodle/calendar:managegroupentries'], $context)) {
3881 // The user can manage group entries or access any group.
3882 $types['group'] = true;
3883 $types['course'] = true;
3888 $courseswithgroups->close();
3890 if (false === $types['course']) {
3891 // Course is still not confirmed. There may have been no courses with a group in them.
3892 $ctxfields = context_helper
::get_preload_record_columns_sql('ctx');
3894 c.id, c.visible, {$ctxfields}
3896 JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
3898 'contextlevel' => CONTEXT_COURSE
,
3900 $courses = $DB->get_recordset_sql($sql, $params);
3901 foreach ($courses as $course) {
3902 context_helper
::preload_from_record($course);
3903 $context = context_course
::instance($course->id
);
3904 if (has_capability('moodle/calendar:manageentries', $context)) {
3905 $types['course'] = true;
3913 $courses = calendar_get_default_courses(null, 'id');
3914 if (empty($courses)) {
3918 $courseids = array_map(function($c) {
3922 // Check whether the user has access to create events within courses which have groups.
3923 list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED
);
3924 $sql = "SELECT c.id, " . context_helper
::get_preload_record_columns_sql('ctx') . "
3926 JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3928 AND c.id IN (SELECT DISTINCT courseid FROM {groups})";
3929 $params['contextlevel'] = CONTEXT_COURSE
;
3930 $courseswithgroups = $DB->get_recordset_sql($sql, $params);
3931 foreach ($courseswithgroups as $coursewithgroup) {
3932 context_helper
::preload_from_record($coursewithgroup);
3933 $context = context_course
::instance($coursewithgroup->id
);
3935 calendar_internal_update_course_and_group_permission($coursewithgroup->id
, $context, $types);
3937 // Okay, course and group event types are allowed, no need to keep the loop iteration.
3938 if ($types['course'] == true && $types['group'] == true) {
3942 $courseswithgroups->close();
3944 if (false === $types['course']) {
3945 list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED
);
3946 $contextsql = "SELECT c.id, " . context_helper
::get_preload_record_columns_sql('ctx') . "
3948 JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3950 $params['contextlevel'] = CONTEXT_COURSE
;
3951 $contextrecords = $DB->get_recordset_sql($contextsql, $params);
3952 foreach ($contextrecords as $course) {
3953 context_helper
::preload_from_record($course);
3954 $coursecontext = context_course
::instance($course->id
);
3955 if (has_capability('moodle/calendar:manageentries', $coursecontext)
3956 && ($courseid == $course->id ||
empty($courseid))) {
3957 $types['course'] = true;
3961 $contextrecords->close();
3971 * Given a course id, and context, updates the permission types array to add the 'course' or 'group'
3972 * permission if it is relevant for that course.
3974 * For efficiency, if they already have 'course' or 'group' then it skips checks.
3976 * Do not call this function directly, it is only for use by calendar_get_allowed_event_types().
3978 * @param int $courseid Course id
3979 * @param context $context Context for that course
3980 * @param array $types Current permissions
3982 function calendar_internal_update_course_and_group_permission(int $courseid, context
$context, array &$types) {
3983 if (!$types['course']) {
3984 // If they have manageentries permission on the course, then they can update this course.
3985 if (has_capability('moodle/calendar:manageentries', $context)) {
3986 $types['course'] = true;
3989 // To update group events they must have EITHER manageentries OR managegroupentries.
3990 if (!$types['group'] && (has_capability('moodle/calendar:manageentries', $context) ||
3991 has_capability('moodle/calendar:managegroupentries', $context))) {
3992 // And they also need for a group to exist on the course.
3993 $groups = groups_get_all_groups($courseid);
3994 if (!empty($groups)) {
3995 // And either accessallgroups, or belong to one of the groups.
3996 if (has_capability('moodle/site:accessallgroups', $context)) {
3997 $types['group'] = true;
3999 foreach ($groups as $group) {
4000 if (groups_is_member($group->id
)) {
4001 $types['group'] = true;
4011 * Get the auth token for exporting the given user calendar.
4012 * @param stdClass $user The user to export the calendar for
4014 * @return string The export token.
4016 function calendar_get_export_token(stdClass
$user): string {
4019 return sha1($user->id
. $DB->get_field('user', 'password', ['id' => $user->id
]) . $CFG->calendar_exportsalt
);
4023 * Get the list of URL parameters for calendar expport and import links.
4027 function calendar_get_export_import_link_params(): array {
4031 if ($courseid = $PAGE->url
->get_param('course')) {
4032 $params['course'] = $courseid;
4034 if ($categoryid = $PAGE->url
->get_param('category')) {
4035 $params['category'] = $categoryid;
4042 * Implements the inplace editable feature.
4044 * @param string $itemtype Type of the inplace editable element
4045 * @param int $itemid Id of the item to edit
4046 * @param int $newvalue New value of the item
4047 * @return \core\output\inplace_editable
4049 function calendar_inplace_editable(string $itemtype, int $itemid, int $newvalue): \core\output\inplace_editable
{
4052 if ($itemtype === 'refreshinterval') {
4054 $subscription = calendar_get_subscription($itemid);
4055 $context = calendar_get_calendar_context($subscription);
4056 external_api
::validate_context($context);
4058 $updateresult = \core_calendar\output\refreshintervalcollection
::update($itemid, $newvalue);
4060 $refreshresults = calendar_update_subscription_events($itemid);
4061 \core\notification
::add($OUTPUT->render_from_template(
4062 'core_calendar/subscription_update_result',
4063 array_merge($refreshresults, [
4064 'subscriptionname' => s($subscription->name
),
4066 ), \core\notification
::INFO
);
4068 return $updateresult;
4071 external_api
::validate_context(context_system
::instance());