2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * @package core_calendar
21 * @copyright 2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 if (!defined('MOODLE_INTERNAL')) {
27 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
31 * These are read by the administration component to provide default values
35 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
37 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
40 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
42 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
45 * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
47 define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
49 // This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
50 // Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
53 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
55 define('CALENDAR_DEFAULT_WEEKEND', 65);
58 * CALENDAR_URL - path to calendar's folder
60 define('CALENDAR_URL', $CFG->wwwroot
.'/calendar/');
63 * CALENDAR_TF_24 - Calendar time in 24 hours format
65 define('CALENDAR_TF_24', '%H:%M');
68 * CALENDAR_TF_12 - Calendar time in 12 hours format
70 define('CALENDAR_TF_12', '%I:%M %p');
73 * CALENDAR_EVENT_SITE - Site calendar event types
75 define('CALENDAR_EVENT_SITE', 1);
78 * CALENDAR_EVENT_COURSE - Course calendar event types
80 define('CALENDAR_EVENT_COURSE', 2);
83 * CALENDAR_EVENT_GROUP - group calendar event types
85 define('CALENDAR_EVENT_GROUP', 4);
88 * CALENDAR_EVENT_USER - user calendar event types
90 define('CALENDAR_EVENT_USER', 8);
93 * CALENDAR_EVENT_COURSECAT - Course category calendar event types
95 define('CALENDAR_EVENT_COURSECAT', 16);
98 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
100 define('CALENDAR_IMPORT_FROM_FILE', 0);
103 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
105 define('CALENDAR_IMPORT_FROM_URL', 1);
108 * CALENDAR_IMPORT_EVENT_UPDATED_SKIPPED - imported event was skipped
110 define('CALENDAR_IMPORT_EVENT_SKIPPED', -1);
113 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
115 define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
118 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
120 define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
123 * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
125 define('CALENDAR_SUBSCRIPTION_UPDATE', 1);
128 * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
130 define('CALENDAR_SUBSCRIPTION_REMOVE', 2);
133 * CALENDAR_EVENT_USER_OVERRIDE_PRIORITY - Constant for the user override priority.
135 define('CALENDAR_EVENT_USER_OVERRIDE_PRIORITY', 0);
138 * CALENDAR_EVENT_TYPE_STANDARD - Standard events.
140 define('CALENDAR_EVENT_TYPE_STANDARD', 0);
143 * CALENDAR_EVENT_TYPE_ACTION - Action events.
145 define('CALENDAR_EVENT_TYPE_ACTION', 1);
148 * Manage calendar events.
150 * This class provides the required functionality in order to manage calendar events.
151 * It was introduced as part of Moodle 2.0 and was created in order to provide a
152 * better framework for dealing with calendar events in particular regard to file
153 * handling through the new file API.
155 * @package core_calendar
157 * @copyright 2009 Sam Hemelryk
158 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
160 * @property int $id The id within the event table
161 * @property string $name The name of the event
162 * @property string $description The description of the event
163 * @property int $format The format of the description FORMAT_?
164 * @property int $courseid The course the event is associated with (0 if none)
165 * @property int $groupid The group the event is associated with (0 if none)
166 * @property int $userid The user the event is associated with (0 if none)
167 * @property int $repeatid If this is a repeated event this will be set to the
169 * @property string $component If created by a plugin/component (other than module), the full frankenstyle name of a component
170 * @property string $modulename If added by a module this will be the module name
171 * @property int $instance If added by a module this will be the module instance
172 * @property string $eventtype The event type
173 * @property int $timestart The start time as a timestamp
174 * @property int $timeduration The duration of the event in seconds
175 * @property int $timeusermidnight User midnight for the event
176 * @property int $visible 1 if the event is visible
177 * @property int $uuid ?
178 * @property int $sequence ?
179 * @property int $timemodified The time last modified as a timestamp
181 class calendar_event
{
183 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
184 protected $properties = null;
186 /** @var string The converted event discription with file paths resolved.
187 * This gets populated when someone requests description for the first time */
188 protected $_description = null;
190 /** @var array The options to use with this description editor */
191 protected $editoroptions = array(
193 'forcehttps' => false,
196 'trusttext' => false);
198 /** @var object The context to use with the description editor */
199 protected $editorcontext = null;
202 * Instantiates a new event and optionally populates its properties with the data provided.
204 * @param \stdClass $data Optional. An object containing the properties to for
207 public function __construct($data = null) {
210 // First convert to object if it is not already (should either be object or assoc array).
211 if (!is_object($data)) {
212 $data = (object) $data;
215 $this->editoroptions
['maxbytes'] = $CFG->maxbytes
;
217 $data->eventrepeats
= 0;
219 if (empty($data->id
)) {
223 if (!empty($data->subscriptionid
)) {
224 $data->subscription
= calendar_get_subscription($data->subscriptionid
);
227 // Default to a user event.
228 if (empty($data->eventtype
)) {
229 $data->eventtype
= 'user';
232 // Default to the current user.
233 if (empty($data->userid
)) {
234 $data->userid
= $USER->id
;
237 if (!empty($data->timeduration
) && is_array($data->timeduration
)) {
238 $data->timeduration
= make_timestamp(
239 $data->timeduration
['year'], $data->timeduration
['month'], $data->timeduration
['day'],
240 $data->timeduration
['hour'], $data->timeduration
['minute']) - $data->timestart
;
243 if (!empty($data->description
) && is_array($data->description
)) {
244 $data->format
= $data->description
['format'];
245 $data->description
= $data->description
['text'];
246 } else if (empty($data->description
)) {
247 $data->description
= '';
248 $data->format
= editors_get_preferred_format();
251 // Ensure form is defaulted correctly.
252 if (empty($data->format
)) {
253 $data->format
= editors_get_preferred_format();
256 if (empty($data->component
)) {
257 $data->component
= null;
260 $this->properties
= $data;
266 * Attempts to call a set_$key method if one exists otherwise falls back
267 * to simply set the property.
269 * @param string $key property name
270 * @param mixed $value value of the property
272 public function __set($key, $value) {
273 if (method_exists($this, 'set_'.$key)) {
274 $this->{'set_'.$key}($value);
276 $this->properties
->{$key} = $value;
282 * Attempts to call a get_$key method to return the property and ralls over
283 * to return the raw property.
285 * @param string $key property name
286 * @return mixed property value
287 * @throws \coding_exception
289 public function __get($key) {
290 if (method_exists($this, 'get_'.$key)) {
291 return $this->{'get_'.$key}();
293 if (!property_exists($this->properties
, $key)) {
294 throw new \
coding_exception('Undefined property requested');
296 return $this->properties
->{$key};
300 * Magic isset method.
302 * PHP needs an isset magic method if you use the get magic method and
303 * still want empty calls to work.
305 * @param string $key $key property name
306 * @return bool|mixed property value, false if property is not exist
308 public function __isset($key) {
309 return !empty($this->properties
->{$key});
313 * Calculate the context value needed for an event.
315 * Event's type can be determine by the available value store in $data
316 * It is important to check for the existence of course/courseid to determine
318 * Default value is set to CONTEXT_USER
320 * @return \stdClass The context object.
322 protected function calculate_context() {
326 if (isset($this->properties
->categoryid
) && $this->properties
->categoryid
> 0) {
327 $context = \context_coursecat
::instance($this->properties
->categoryid
);
328 } else if (isset($this->properties
->courseid
) && $this->properties
->courseid
> 0) {
329 $context = \context_course
::instance($this->properties
->courseid
);
330 } else if (isset($this->properties
->course
) && $this->properties
->course
> 0) {
331 $context = \context_course
::instance($this->properties
->course
);
332 } else if (isset($this->properties
->groupid
) && $this->properties
->groupid
> 0) {
333 $group = $DB->get_record('groups', array('id' => $this->properties
->groupid
));
334 $context = \context_course
::instance($group->courseid
);
335 } else if (isset($this->properties
->userid
) && $this->properties
->userid
> 0
336 && $this->properties
->userid
== $USER->id
) {
337 $context = \context_user
::instance($this->properties
->userid
);
338 } else if (isset($this->properties
->userid
) && $this->properties
->userid
> 0
339 && $this->properties
->userid
!= $USER->id
&&
340 !empty($this->properties
->modulename
) &&
341 isset($this->properties
->instance
) && $this->properties
->instance
> 0) {
342 $cm = get_coursemodule_from_instance($this->properties
->modulename
, $this->properties
->instance
, 0,
344 $context = \context_course
::instance($cm->course
);
346 $context = \context_user
::instance($this->properties
->userid
);
353 * Returns the context for this event. The context is calculated
354 * the first time is is requested and then stored in a member
355 * variable to be returned each subsequent time.
357 * This is a magical getter function that will be called when
358 * ever the context property is accessed, e.g. $event->context.
362 protected function get_context() {
363 if (!isset($this->properties
->context
)) {
364 $this->properties
->context
= $this->calculate_context();
367 return $this->properties
->context
;
371 * Returns an array of editoroptions for this event.
373 * @return array event editor options
375 protected function get_editoroptions() {
376 return $this->editoroptions
;
380 * Returns an event description: Called by __get
381 * Please use $blah = $event->description;
383 * @return string event description
385 protected function get_description() {
388 require_once($CFG->libdir
. '/filelib.php');
390 if ($this->_description
=== null) {
391 // Check if we have already resolved the context for this event.
392 if ($this->editorcontext
=== null) {
393 // Switch on the event type to decide upon the appropriate context to use for this event.
394 $this->editorcontext
= $this->get_context();
395 if (!calendar_is_valid_eventtype($this->properties
->eventtype
)) {
396 return clean_text($this->properties
->description
, $this->properties
->format
);
400 // Work out the item id for the editor, if this is a repeated event
401 // then the files will be associated with the original.
402 if (!empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
403 $itemid = $this->properties
->repeatid
;
405 $itemid = $this->properties
->id
;
408 // Convert file paths in the description so that things display correctly.
409 $this->_description
= file_rewrite_pluginfile_urls($this->properties
->description
, 'pluginfile.php',
410 $this->editorcontext
->id
, 'calendar', 'event_description', $itemid);
411 // Clean the text so no nasties get through.
412 $this->_description
= clean_text($this->_description
, $this->properties
->format
);
415 // Finally return the description.
416 return $this->_description
;
420 * Return the number of repeat events there are in this events series.
422 * @return int number of event repeated
424 public function count_repeats() {
426 if (!empty($this->properties
->repeatid
)) {
427 $this->properties
->eventrepeats
= $DB->count_records('event',
428 array('repeatid' => $this->properties
->repeatid
));
429 // We don't want to count ourselves.
430 $this->properties
->eventrepeats
--;
432 return $this->properties
->eventrepeats
;
436 * Update or create an event within the database
438 * Pass in a object containing the event properties and this function will
439 * insert it into the database and deal with any associated files
441 * Capability checking should be performed if the user is directly manipulating the event
442 * and no other capability has been tested. However if the event is not being manipulated
443 * directly by the user and another capability has been checked for them to do this then
444 * capabilites should not be checked.
446 * For example if a user is editing an event in the calendar the check should be true,
447 * but if you are updating an event in an activities settings are changed then the calendar
448 * capabilites should not be checked.
450 * @see self::create()
451 * @see self::update()
453 * @param \stdClass $data object of event
454 * @param bool $checkcapability If Moodle should check the user can manage the calendar events for this call or not.
455 * @return bool event updated
457 public function update($data, $checkcapability=true) {
460 foreach ($data as $key => $value) {
461 $this->properties
->$key = $value;
464 $this->properties
->timemodified
= time();
465 $usingeditor = (!empty($this->properties
->description
) && is_array($this->properties
->description
));
467 // Prepare event data.
469 'context' => $this->get_context(),
470 'objectid' => $this->properties
->id
,
472 'repeatid' => empty($this->properties
->repeatid
) ?
0 : $this->properties
->repeatid
,
473 'timestart' => $this->properties
->timestart
,
474 'name' => $this->properties
->name
478 if (empty($this->properties
->id
) ||
$this->properties
->id
< 1) {
479 if ($checkcapability) {
480 if (!calendar_add_event_allowed($this->properties
)) {
481 print_error('nopermissiontoupdatecalendar');
486 switch ($this->properties
->eventtype
) {
488 $this->properties
->courseid
= 0;
489 $this->properties
->course
= 0;
490 $this->properties
->groupid
= 0;
491 $this->properties
->userid
= $USER->id
;
494 $this->properties
->courseid
= SITEID
;
495 $this->properties
->course
= SITEID
;
496 $this->properties
->groupid
= 0;
497 $this->properties
->userid
= $USER->id
;
500 $this->properties
->groupid
= 0;
501 $this->properties
->userid
= $USER->id
;
504 $this->properties
->groupid
= 0;
505 $this->properties
->category
= 0;
506 $this->properties
->userid
= $USER->id
;
509 $this->properties
->userid
= $USER->id
;
512 // We should NEVER get here, but just incase we do lets fail gracefully.
513 $usingeditor = false;
517 // If we are actually using the editor, we recalculate the context because some default values
518 // were set when calculate_context() was called from the constructor.
520 $this->properties
->context
= $this->calculate_context();
521 $this->editorcontext
= $this->get_context();
524 $editor = $this->properties
->description
;
525 $this->properties
->format
= $this->properties
->description
['format'];
526 $this->properties
->description
= $this->properties
->description
['text'];
529 // Insert the event into the database.
530 $this->properties
->id
= $DB->insert_record('event', $this->properties
);
533 $this->properties
->description
= file_save_draft_area_files(
535 $this->editorcontext
->id
,
538 $this->properties
->id
,
539 $this->editoroptions
,
541 $this->editoroptions
['forcehttps']);
542 $DB->set_field('event', 'description', $this->properties
->description
,
543 array('id' => $this->properties
->id
));
546 // Log the event entry.
547 $eventargs['objectid'] = $this->properties
->id
;
548 $eventargs['context'] = $this->get_context();
549 $event = \core\event\calendar_event_created
::create($eventargs);
552 $repeatedids = array();
554 if (!empty($this->properties
->repeat
)) {
555 $this->properties
->repeatid
= $this->properties
->id
;
556 $DB->set_field('event', 'repeatid', $this->properties
->repeatid
, array('id' => $this->properties
->id
));
558 $eventcopy = clone($this->properties
);
559 unset($eventcopy->id
);
561 $timestart = new \
DateTime('@' . $eventcopy->timestart
);
562 $timestart->setTimezone(\core_date
::get_user_timezone_object());
564 for ($i = 1; $i < $eventcopy->repeats
; $i++
) {
566 $timestart->add(new \
DateInterval('P7D'));
567 $eventcopy->timestart
= $timestart->getTimestamp();
569 // Get the event id for the log record.
570 $eventcopyid = $DB->insert_record('event', $eventcopy);
572 // If the context has been set delete all associated files.
574 $fs = get_file_storage();
575 $files = $fs->get_area_files($this->editorcontext
->id
, 'calendar', 'event_description',
576 $this->properties
->id
);
577 foreach ($files as $file) {
578 $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
582 $repeatedids[] = $eventcopyid;
585 $eventargs['objectid'] = $eventcopyid;
586 $eventargs['other']['timestart'] = $eventcopy->timestart
;
587 $event = \core\event\calendar_event_created
::create($eventargs);
595 if ($checkcapability) {
596 if (!calendar_edit_event_allowed($this->properties
)) {
597 print_error('nopermissiontoupdatecalendar');
602 if ($this->editorcontext
!== null) {
603 $this->properties
->description
= file_save_draft_area_files(
604 $this->properties
->description
['itemid'],
605 $this->editorcontext
->id
,
608 $this->properties
->id
,
609 $this->editoroptions
,
610 $this->properties
->description
['text'],
611 $this->editoroptions
['forcehttps']);
613 $this->properties
->format
= $this->properties
->description
['format'];
614 $this->properties
->description
= $this->properties
->description
['text'];
618 $event = $DB->get_record('event', array('id' => $this->properties
->id
));
620 $updaterepeated = (!empty($this->properties
->repeatid
) && !empty($this->properties
->repeateditall
));
622 if ($updaterepeated) {
631 // Note: Group and course id may not be set. If not, keep their current values.
633 $this->properties
->name
,
634 $this->properties
->description
,
635 $this->properties
->timeduration
,
637 isset($this->properties
->groupid
) ?
$this->properties
->groupid
: $event->groupid
,
638 isset($this->properties
->courseid
) ?
$this->properties
->courseid
: $event->courseid
,
641 // Note: Only update start date, if it was changed by the user.
642 if ($this->properties
->timestart
!= $event->timestart
) {
643 $timestartoffset = $this->properties
->timestart
- $event->timestart
;
644 $sqlset .= ', timestart = timestart + ?';
645 $params[] = $timestartoffset;
648 // Note: Only update location, if it was changed by the user.
649 $updatelocation = (!empty($this->properties
->location
) && $this->properties
->location
!== $event->location
);
650 if ($updatelocation) {
651 $sqlset .= ', location = ?';
652 $params[] = $this->properties
->location
;
656 $sql = "UPDATE {event}
660 $params[] = $event->repeatid
;
661 $DB->execute($sql, $params);
663 // Trigger an update event for each of the calendar event.
664 $events = $DB->get_records('event', array('repeatid' => $event->repeatid
), '', '*');
665 foreach ($events as $calendarevent) {
666 $eventargs['objectid'] = $calendarevent->id
;
667 $eventargs['other']['timestart'] = $calendarevent->timestart
;
668 $event = \core\event\calendar_event_updated
::create($eventargs);
669 $event->add_record_snapshot('event', $calendarevent);
673 $DB->update_record('event', $this->properties
);
674 $event = self
::load($this->properties
->id
);
675 $this->properties
= $event->properties();
677 // Trigger an update event.
678 $event = \core\event\calendar_event_updated
::create($eventargs);
679 $event->add_record_snapshot('event', $this->properties
);
688 * Deletes an event and if selected an repeated events in the same series
690 * This function deletes an event, any associated events if $deleterepeated=true,
691 * and cleans up any files associated with the events.
693 * @see self::delete()
695 * @param bool $deleterepeated delete event repeatedly
696 * @return bool succession of deleting event
698 public function delete($deleterepeated = false) {
701 // If $this->properties->id is not set then something is wrong.
702 if (empty($this->properties
->id
)) {
703 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER
);
706 $calevent = $DB->get_record('event', array('id' => $this->properties
->id
), '*', MUST_EXIST
);
708 $DB->delete_records('event', array('id' => $this->properties
->id
));
710 // Trigger an event for the delete action.
712 'context' => $this->get_context(),
713 'objectid' => $this->properties
->id
,
715 'repeatid' => empty($this->properties
->repeatid
) ?
0 : $this->properties
->repeatid
,
716 'timestart' => $this->properties
->timestart
,
717 'name' => $this->properties
->name
719 $event = \core\event\calendar_event_deleted
::create($eventargs);
720 $event->add_record_snapshot('event', $calevent);
723 // If we are deleting parent of a repeated event series, promote the next event in the series as parent.
724 if (($this->properties
->id
== $this->properties
->repeatid
) && !$deleterepeated) {
725 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC",
726 array($this->properties
->id
), IGNORE_MULTIPLE
);
727 if (!empty($newparent)) {
728 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?",
729 array($newparent, $this->properties
->id
));
730 // Get all records where the repeatid is the same as the event being removed.
731 $events = $DB->get_records('event', array('repeatid' => $newparent));
732 // For each of the returned events trigger an update event.
733 foreach ($events as $calendarevent) {
734 // Trigger an event for the update.
735 $eventargs['objectid'] = $calendarevent->id
;
736 $eventargs['other']['timestart'] = $calendarevent->timestart
;
737 $event = \core\event\calendar_event_updated
::create($eventargs);
738 $event->add_record_snapshot('event', $calendarevent);
744 // If the editor context hasn't already been set then set it now.
745 if ($this->editorcontext
=== null) {
746 $this->editorcontext
= $this->get_context();
749 // If the context has been set delete all associated files.
750 if ($this->editorcontext
!== null) {
751 $fs = get_file_storage();
752 $files = $fs->get_area_files($this->editorcontext
->id
, 'calendar', 'event_description', $this->properties
->id
);
753 foreach ($files as $file) {
758 // If we need to delete repeated events then we will fetch them all and delete one by one.
759 if ($deleterepeated && !empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
760 // Get all records where the repeatid is the same as the event being removed.
761 $events = $DB->get_records('event', array('repeatid' => $this->properties
->repeatid
));
762 // For each of the returned events populate an event object and call delete.
763 // make sure the arg passed is false as we are already deleting all repeats.
764 foreach ($events as $event) {
765 $event = new calendar_event($event);
766 $event->delete(false);
774 * Fetch all event properties.
776 * This function returns all of the events properties as an object and optionally
777 * can prepare an editor for the description field at the same time. This is
778 * designed to work when the properties are going to be used to set the default
779 * values of a moodle forms form.
781 * @param bool $prepareeditor If set to true a editor is prepared for use with
782 * the mforms editor element. (for description)
783 * @return \stdClass Object containing event properties
785 public function properties($prepareeditor = false) {
788 // First take a copy of the properties. We don't want to actually change the
789 // properties or we'd forever be converting back and forwards between an
790 // editor formatted description and not.
791 $properties = clone($this->properties
);
792 // Clean the description here.
793 $properties->description
= clean_text($properties->description
, $properties->format
);
795 // If set to true we need to prepare the properties for use with an editor
796 // and prepare the file area.
797 if ($prepareeditor) {
799 // We may or may not have a property id. If we do then we need to work
800 // out the context so we can copy the existing files to the draft area.
801 if (!empty($properties->id
)) {
803 if ($properties->eventtype
=== 'site') {
805 $this->editorcontext
= $this->get_context();
806 } else if ($properties->eventtype
=== 'user') {
808 $this->editorcontext
= $this->get_context();
809 } else if ($properties->eventtype
=== 'group' ||
$properties->eventtype
=== 'course') {
810 // First check the course is valid.
811 $course = $DB->get_record('course', array('id' => $properties->courseid
));
813 print_error('invalidcourse');
816 $this->editorcontext
= $this->get_context();
817 // We have a course and are within the course context so we had
818 // better use the courses max bytes value.
819 $this->editoroptions
['maxbytes'] = $course->maxbytes
;
820 } else if ($properties->eventtype
=== 'category') {
821 // First check the course is valid.
822 \core_course_category
::get($properties->categoryid
, MUST_EXIST
, true);
824 $this->editorcontext
= $this->get_context();
826 // If we get here we have a custom event type as used by some
827 // modules. In this case the event will have been added by
828 // code and we won't need the editor.
829 $this->editoroptions
['maxbytes'] = 0;
830 $this->editoroptions
['maxfiles'] = 0;
833 if (empty($this->editorcontext
) ||
empty($this->editorcontext
->id
)) {
836 // Get the context id that is what we really want.
837 $contextid = $this->editorcontext
->id
;
841 // If we get here then this is a new event in which case we don't need a
842 // context as there is no existing files to copy to the draft area.
846 // If the contextid === false we don't support files so no preparing
848 if ($contextid !== false) {
849 // Just encase it has already been submitted.
850 $draftiddescription = file_get_submitted_draft_itemid('description');
851 // Prepare the draft area, this copies existing files to the draft area as well.
852 $properties->description
= file_prepare_draft_area($draftiddescription, $contextid, 'calendar',
853 'event_description', $properties->id
, $this->editoroptions
, $properties->description
);
855 $draftiddescription = 0;
858 // Structure the description field as the editor requires.
859 $properties->description
= array('text' => $properties->description
, 'format' => $properties->format
,
860 'itemid' => $draftiddescription);
863 // Finally return the properties.
868 * Toggles the visibility of an event
870 * @param null|bool $force If it is left null the events visibility is flipped,
871 * If it is false the event is made hidden, if it is true it
873 * @return bool if event is successfully updated, toggle will be visible
875 public function toggle_visibility($force = null) {
878 // Set visible to the default if it is not already set.
879 if (empty($this->properties
->visible
)) {
880 $this->properties
->visible
= 1;
883 if ($force === true ||
($force !== false && $this->properties
->visible
== 0)) {
884 // Make this event visible.
885 $this->properties
->visible
= 1;
887 // Make this event hidden.
888 $this->properties
->visible
= 0;
891 // Update the database to reflect this change.
892 $success = $DB->set_field('event', 'visible', $this->properties
->visible
, array('id' => $this->properties
->id
));
893 $calendarevent = $DB->get_record('event', array('id' => $this->properties
->id
), '*', MUST_EXIST
);
895 // Prepare event data.
897 'context' => $this->get_context(),
898 'objectid' => $this->properties
->id
,
900 'repeatid' => empty($this->properties
->repeatid
) ?
0 : $this->properties
->repeatid
,
901 'timestart' => $this->properties
->timestart
,
902 'name' => $this->properties
->name
905 $event = \core\event\calendar_event_updated
::create($eventargs);
906 $event->add_record_snapshot('event', $calendarevent);
913 * Returns an event object when provided with an event id.
915 * This function makes use of MUST_EXIST, if the event id passed in is invalid
916 * it will result in an exception being thrown.
918 * @param int|object $param event object or event id
919 * @return calendar_event
921 public static function load($param) {
923 if (is_object($param)) {
924 $event = new calendar_event($param);
926 $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST
);
927 $event = new calendar_event($event);
933 * Creates a new event and returns an event object.
935 * Capability checking should be performed if the user is directly creating the event
936 * and no other capability has been tested. However if the event is not being created
937 * directly by the user and another capability has been checked for them to do this then
938 * capabilites should not be checked.
940 * For example if a user is creating an event in the calendar the check should be true,
941 * but if you are creating an event in an activity when it is created then the calendar
942 * capabilites should not be checked.
944 * @param \stdClass|array $properties An object containing event properties
945 * @param bool $checkcapability If Moodle should check the user can manage the calendar events for this call or not.
946 * @throws \coding_exception
948 * @return calendar_event|bool The event object or false if it failed
950 public static function create($properties, $checkcapability = true) {
951 if (is_array($properties)) {
952 $properties = (object)$properties;
954 if (!is_object($properties)) {
955 throw new \
coding_exception('When creating an event properties should be either an object or an assoc array');
957 $event = new calendar_event($properties);
958 if ($event->update($properties, $checkcapability)) {
966 * Format the event name using the external API.
968 * This function should we used when text formatting is required in external functions.
970 * @return string Formatted name.
972 public function format_external_name() {
973 if ($this->editorcontext
=== null) {
974 // Switch on the event type to decide upon the appropriate context to use for this event.
975 $this->editorcontext
= $this->get_context();
978 return external_format_string($this->properties
->name
, $this->editorcontext
->id
);
982 * Format the text using the external API.
984 * This function should we used when text formatting is required in external functions.
986 * @return array an array containing the text formatted and the text format
988 public function format_external_text() {
990 if ($this->editorcontext
=== null) {
991 // Switch on the event type to decide upon the appropriate context to use for this event.
992 $this->editorcontext
= $this->get_context();
994 if (!calendar_is_valid_eventtype($this->properties
->eventtype
)) {
995 // We don't have a context here, do a normal format_text.
996 return external_format_text($this->properties
->description
, $this->properties
->format
, $this->editorcontext
->id
);
1000 // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
1001 if (!empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
1002 $itemid = $this->properties
->repeatid
;
1004 $itemid = $this->properties
->id
;
1007 return external_format_text($this->properties
->description
, $this->properties
->format
, $this->editorcontext
->id
,
1008 'calendar', 'event_description', $itemid);
1013 * Calendar information class
1015 * This class is used simply to organise the information pertaining to a calendar
1016 * and is used primarily to make information easily available.
1018 * @package core_calendar
1019 * @category calendar
1020 * @copyright 2010 Sam Hemelryk
1021 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1023 class calendar_information
{
1026 * @var int The timestamp
1028 * Rather than setting the day, month and year we will set a timestamp which will be able
1029 * to be used by multiple calendars.
1033 /** @var int A course id */
1034 public $courseid = null;
1036 /** @var array An array of categories */
1037 public $categories = array();
1039 /** @var int The current category */
1040 public $categoryid = null;
1042 /** @var array An array of courses */
1043 public $courses = array();
1045 /** @var array An array of groups */
1046 public $groups = array();
1048 /** @var array An array of users */
1049 public $users = array();
1051 /** @var context The anticipated context that the calendar is viewed in */
1052 public $context = null;
1054 /** @var string The calendar's view mode. */
1055 protected $viewmode;
1058 * Creates a new instance
1060 * @param int $day the number of the day
1061 * @param int $month the number of the month
1062 * @param int $year the number of the year
1063 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
1064 * and $calyear to support multiple calendars
1066 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
1067 // If a day, month and year were passed then convert it to a timestamp. If these were passed
1068 // then we can assume the day, month and year are passed as Gregorian, as no where in core
1069 // should we be passing these values rather than the time. This is done for BC.
1070 if (!empty($day) ||
!empty($month) ||
!empty($year)) {
1071 $date = usergetdate(time());
1073 $day = $date['mday'];
1075 if (empty($month)) {
1076 $month = $date['mon'];
1079 $year = $date['year'];
1081 if (checkdate($month, $day, $year)) {
1082 $time = make_timestamp($year, $month, $day);
1088 $this->set_time($time);
1092 * Creates and set up a instance.
1094 * @param int $time the unixtimestamp representing the date we want to view.
1095 * @param int $courseid The ID of the course the user wishes to view.
1096 * @param int $categoryid The ID of the category the user wishes to view
1097 * If a courseid is specified, this value is ignored.
1098 * @return calendar_information
1100 public static function create($time, int $courseid, int $categoryid = null) : calendar_information
{
1101 $calendar = new static(0, 0, 0, $time);
1102 if ($courseid != SITEID
&& !empty($courseid)) {
1103 // Course ID must be valid and existing.
1104 $course = get_course($courseid);
1105 $calendar->context
= context_course
::instance($course->id
);
1107 if (!$course->visible
&& !is_role_switched($course->id
)) {
1108 require_capability('moodle/course:viewhiddencourses', $calendar->context
);
1111 $courses = [$course->id
=> $course];
1112 $category = (\core_course_category
::get($course->category
, MUST_EXIST
, true))->get_db_record();
1113 } else if (!empty($categoryid)) {
1114 $course = get_site();
1115 $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1117 // Filter available courses to those within this category or it's children.
1118 $ids = [$categoryid];
1119 $category = \core_course_category
::get($categoryid);
1120 $ids = array_merge($ids, array_keys($category->get_children()));
1121 $courses = array_filter($courses, function($course) use ($ids) {
1122 return array_search($course->category
, $ids) !== false;
1124 $category = $category->get_db_record();
1126 $calendar->context
= context_coursecat
::instance($categoryid);
1128 $course = get_site();
1129 $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1132 $calendar->context
= context_system
::instance();
1135 $calendar->set_sources($course, $courses, $category);
1141 * Set the time period of this instance.
1143 * @param int $time the unixtimestamp representing the date we want to view.
1146 public function set_time($time = null) {
1148 $this->time
= time();
1150 $this->time
= $time;
1157 * Initialize calendar information
1160 * @param stdClass $course object
1161 * @param array $coursestoload An array of courses [$course->id => $course]
1162 * @param bool $ignorefilters options to use filter
1164 public function prepare_for_view(stdClass
$course, array $coursestoload, $ignorefilters = false) {
1165 debugging('The prepare_for_view() function has been deprecated. Please update your code to use set_sources()',
1167 $this->set_sources($course, $coursestoload);
1171 * Set the sources for events within the calendar.
1173 * If no category is provided, then the category path for the current
1174 * course will be used.
1176 * @param stdClass $course The current course being viewed.
1177 * @param stdClass[] $courses The list of all courses currently accessible.
1178 * @param stdClass $category The current category to show.
1180 public function set_sources(stdClass
$course, array $courses, stdClass
$category = null) {
1183 // A cousre must always be specified.
1184 $this->course
= $course;
1185 $this->courseid
= $course->id
;
1187 list($courseids, $group, $user) = calendar_set_filters($courses);
1188 $this->courses
= $courseids;
1189 $this->groups
= $group;
1190 $this->users
= $user;
1192 // Do not show category events by default.
1193 $this->categoryid
= null;
1194 $this->categories
= null;
1196 // Determine the correct category information to show.
1197 // When called with a course, the category of that course is usually included too.
1198 // When a category was specifically requested, it should be requested with the site id.
1199 if (SITEID
!== $this->courseid
) {
1200 // A specific course was requested.
1201 // Fetch the category that this course is in, along with all parents.
1202 // Do not include child categories of this category, as the user many not have enrolments in those siblings or children.
1203 $category = \core_course_category
::get($course->category
, MUST_EXIST
, true);
1204 $this->categoryid
= $category->id
;
1206 $this->categories
= $category->get_parents();
1207 $this->categories
[] = $category->id
;
1208 } else if (null !== $category && $category->id
> 0) {
1209 // A specific category was requested.
1210 // Fetch all parents of this category, along with all children too.
1211 $category = \core_course_category
::get($category->id
);
1212 $this->categoryid
= $category->id
;
1214 // Build the category list.
1215 // This includes the current category.
1216 $this->categories
= $category->get_parents();
1217 $this->categories
[] = $category->id
;
1218 $this->categories
= array_merge($this->categories
, $category->get_all_children_ids());
1219 } else if (SITEID
=== $this->courseid
) {
1220 // The site was requested.
1221 // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
1223 // Grab the list of categories that this user has courses in.
1224 $coursecategories = array_flip(array_map(function($course) {
1225 return $course->category
;
1228 $calcatcache = cache
::make('core', 'calendar_categories');
1229 $this->categories
= $calcatcache->get('site');
1230 if ($this->categories
=== false) {
1231 // Use the category id as the key in the following array. That way we do not have to remove duplicates.
1233 foreach (\core_course_category
::get_all() as $category) {
1234 if (isset($coursecategories[$category->id
]) ||
1235 has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
1236 // If the user has access to a course in this category or can manage the category,
1237 // then they can see all parent categories too.
1238 $categories[$category->id
] = true;
1239 foreach ($category->get_parents() as $catid) {
1240 $categories[$catid] = true;
1244 $this->categories
= array_keys($categories);
1245 $calcatcache->set('site', $this->categories
);
1251 * Ensures the date for the calendar is correct and either sets it to now
1252 * or throws a moodle_exception if not
1254 * @param bool $defaultonow use current time
1255 * @throws moodle_exception
1256 * @return bool validation of checkdate
1258 public function checkdate($defaultonow = true) {
1259 if (!checkdate($this->month
, $this->day
, $this->year
)) {
1261 $now = usergetdate(time());
1262 $this->day
= intval($now['mday']);
1263 $this->month
= intval($now['mon']);
1264 $this->year
= intval($now['year']);
1267 throw new moodle_exception('invaliddate');
1274 * Gets todays timestamp for the calendar
1276 * @return int today timestamp
1278 public function timestamp_today() {
1282 * Gets tomorrows timestamp for the calendar
1284 * @return int tomorrow timestamp
1286 public function timestamp_tomorrow() {
1287 return strtotime('+1 day', $this->time
);
1290 * Adds the pretend blocks for the calendar
1292 * @param core_calendar_renderer $renderer
1293 * @param bool $showfilters display filters, false is set as default
1294 * @param string|null $view preference view options (eg: day, month, upcoming)
1296 public function add_sidecalendar_blocks(core_calendar_renderer
$renderer, $showfilters=false, $view=null) {
1299 if (!has_capability('moodle/block:view', $PAGE->context
) ) {
1304 $filters = new block_contents();
1305 $filters->content
= $renderer->event_filter();
1306 $filters->footer
= '';
1307 $filters->title
= get_string('eventskey', 'calendar');
1308 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT
);
1313 * Getter method for the calendar's view mode.
1317 public function get_viewmode(): string {
1318 return $this->viewmode
;
1322 * Setter method for the calendar's view mode.
1324 * @param string $viewmode
1326 public function set_viewmode(string $viewmode): void
{
1327 $this->viewmode
= $viewmode;
1332 * Get calendar events.
1334 * @param int $tstart Start time of time range for events
1335 * @param int $tend End time of time range for events
1336 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
1337 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
1338 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
1339 * @param boolean $withduration whether only events starting within time range selected
1340 * or events in progress/already started selected as well
1341 * @param boolean $ignorehidden whether to select only visible events or all events
1342 * @param array|int|boolean $categories array of categories, category id or boolean for all/no course events
1343 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
1345 function calendar_get_events($tstart, $tend, $users, $groups, $courses,
1346 $withduration = true, $ignorehidden = true, $categories = []) {
1352 if (empty($users) && empty($groups) && empty($courses) && empty($categories)) {
1356 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
1357 // Events from a number of users
1358 if(!empty($whereclause)) $whereclause .= ' OR';
1359 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED
);
1360 $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)";
1361 $params = array_merge($params, $inparamsusers);
1362 } else if($users === true) {
1363 // Events from ALL users
1364 if(!empty($whereclause)) $whereclause .= ' OR';
1365 $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)';
1366 } else if($users === false) {
1367 // No user at all, do nothing
1370 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
1371 // Events from a number of groups
1372 if(!empty($whereclause)) $whereclause .= ' OR';
1373 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED
);
1374 $whereclause .= " e.groupid $insqlgroups ";
1375 $params = array_merge($params, $inparamsgroups);
1376 } else if($groups === true) {
1377 // Events from ALL groups
1378 if(!empty($whereclause)) $whereclause .= ' OR ';
1379 $whereclause .= ' e.groupid != 0';
1381 // boolean false (no groups at all): we don't need to do anything
1383 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
1384 if(!empty($whereclause)) $whereclause .= ' OR';
1385 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED
);
1386 $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
1387 $params = array_merge($params, $inparamscourses);
1388 } else if ($courses === true) {
1389 // Events from ALL courses
1390 if(!empty($whereclause)) $whereclause .= ' OR';
1391 $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
1394 if ((is_array($categories) && !empty($categories)) ||
is_numeric($categories)) {
1395 if (!empty($whereclause)) {
1396 $whereclause .= ' OR';
1398 list($insqlcategories, $inparamscategories) = $DB->get_in_or_equal($categories, SQL_PARAMS_NAMED
);
1399 $whereclause .= " (e.groupid = 0 AND e.courseid = 0 AND e.categoryid $insqlcategories)";
1400 $params = array_merge($params, $inparamscategories);
1401 } else if ($categories === true) {
1402 // Events from ALL categories.
1403 if (!empty($whereclause)) {
1404 $whereclause .= ' OR';
1406 $whereclause .= ' (e.groupid = 0 AND e.courseid = 0 AND e.categoryid != 0)';
1409 // Security check: if, by now, we have NOTHING in $whereclause, then it means
1410 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
1411 // events no matter what. Allowing the code to proceed might return a completely
1412 // valid query with only time constraints, thus selecting ALL events in that time frame!
1413 if(empty($whereclause)) {
1418 $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1421 $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1423 if(!empty($whereclause)) {
1424 // We have additional constraints
1425 $whereclause = $timeclause.' AND ('.$whereclause.')';
1428 // Just basic time filtering
1429 $whereclause = $timeclause;
1432 if ($ignorehidden) {
1433 $whereclause .= ' AND e.visible = 1';
1438 LEFT JOIN {modules} m ON e.modulename = m.name
1439 -- Non visible modules will have a value of 0.
1440 WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
1441 ORDER BY e.timestart";
1442 $events = $DB->get_records_sql($sql, $params);
1444 if ($events === false) {
1451 * Return the days of the week.
1453 * @return array array of days
1455 function calendar_get_days() {
1456 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1457 return $calendartype->get_weekdays();
1461 * Get the subscription from a given id.
1464 * @param int $id id of the subscription
1465 * @return stdClass Subscription record from DB
1466 * @throws moodle_exception for an invalid id
1468 function calendar_get_subscription($id) {
1471 $cache = \cache
::make('core', 'calendar_subscriptions');
1472 $subscription = $cache->get($id);
1473 if (empty($subscription)) {
1474 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST
);
1475 $cache->set($id, $subscription);
1478 return $subscription;
1482 * Gets the first day of the week.
1484 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
1488 function calendar_get_starting_weekday() {
1489 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1490 return $calendartype->get_starting_weekday();
1494 * Get a HTML link to a course.
1496 * @param int|stdClass $course the course id or course object
1497 * @return string a link to the course (as HTML); empty if the course id is invalid
1499 function calendar_get_courselink($course) {
1504 if (!is_object($course)) {
1505 $course = calendar_get_course_cached($coursecache, $course);
1507 $context = \context_course
::instance($course->id
);
1508 $fullname = format_string($course->fullname
, true, array('context' => $context));
1509 $url = new \
moodle_url('/course/view.php', array('id' => $course->id
));
1510 $link = \html_writer
::link($url, $fullname);
1516 * Get current module cache.
1518 * Only use this method if you do not know courseid. Otherwise use:
1519 * get_fast_modinfo($courseid)->instances[$modulename][$instance]
1521 * @param array $modulecache in memory module cache
1522 * @param string $modulename name of the module
1523 * @param int $instance module instance number
1524 * @return stdClass|bool $module information
1526 function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
1527 if (!isset($modulecache[$modulename . '_' . $instance])) {
1528 $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
1531 return $modulecache[$modulename . '_' . $instance];
1535 * Get current course cache.
1537 * @param array $coursecache list of course cache
1538 * @param int $courseid id of the course
1539 * @return stdClass $coursecache[$courseid] return the specific course cache
1541 function calendar_get_course_cached(&$coursecache, $courseid) {
1542 if (!isset($coursecache[$courseid])) {
1543 $coursecache[$courseid] = get_course($courseid);
1545 return $coursecache[$courseid];
1549 * Get group from groupid for calendar display
1551 * @param int $groupid
1552 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1554 function calendar_get_group_cached($groupid) {
1555 static $groupscache = array();
1556 if (!isset($groupscache[$groupid])) {
1557 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1559 return $groupscache[$groupid];
1563 * Add calendar event metadata
1565 * @deprecated since 3.9
1567 * @param stdClass $event event info
1568 * @return stdClass $event metadata
1570 function calendar_add_event_metadata($event) {
1571 debugging('This function is no longer used', DEBUG_DEVELOPER
);
1572 global $CFG, $OUTPUT;
1574 // Support multilang in event->name.
1575 $event->name
= format_string($event->name
, true);
1577 if (!empty($event->modulename
)) { // Activity event.
1578 // The module name is set. I will assume that it has to be displayed, and
1579 // also that it is an automatically-generated event. And of course that the
1580 // instace id and modulename are set correctly.
1581 $instances = get_fast_modinfo($event->courseid
)->get_instances_of($event->modulename
);
1582 if (!array_key_exists($event->instance
, $instances)) {
1585 $module = $instances[$event->instance
];
1587 $modulename = $module->get_module_type_name(false);
1588 if (get_string_manager()->string_exists($event->eventtype
, $event->modulename
)) {
1589 // Will be used as alt text if the event icon.
1590 $eventtype = get_string($event->eventtype
, $event->modulename
);
1595 $event->icon
= '<img src="' . s($module->get_icon_url()) . '" alt="' . s($eventtype) .
1596 '" title="' . s($modulename) . '" class="icon" />';
1597 $event->referer
= html_writer
::link($module->url
, $event->name
);
1598 $event->courselink
= calendar_get_courselink($module->get_course());
1599 $event->cmid
= $module->id
;
1600 } else if ($event->courseid
== SITEID
) { // Site event.
1601 $event->icon
= '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
1602 get_string('siteevent', 'calendar') . '" class="icon" />';
1603 $event->cssclass
= 'calendar_event_site';
1604 } else if ($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) { // Course event.
1605 $event->icon
= '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
1606 get_string('courseevent', 'calendar') . '" class="icon" />';
1607 $event->courselink
= calendar_get_courselink($event->courseid
);
1608 $event->cssclass
= 'calendar_event_course';
1609 } else if ($event->groupid
) { // Group event.
1610 if ($group = calendar_get_group_cached($event->groupid
)) {
1611 $groupname = format_string($group->name
, true, \context_course
::instance($group->courseid
));
1615 $event->icon
= \html_writer
::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
1616 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
1617 $event->courselink
= calendar_get_courselink($event->courseid
) . ', ' . $groupname;
1618 $event->cssclass
= 'calendar_event_group';
1619 } else if ($event->userid
) { // User event.
1620 $event->icon
= '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
1621 get_string('userevent', 'calendar') . '" class="icon" />';
1622 $event->cssclass
= 'calendar_event_user';
1629 * Get calendar events by id.
1632 * @param array $eventids list of event ids
1633 * @return array Array of event entries, empty array if nothing found
1635 function calendar_get_events_by_id($eventids) {
1638 if (!is_array($eventids) ||
empty($eventids)) {
1642 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
1643 $wheresql = "id $wheresql";
1645 return $DB->get_records_select('event', $wheresql, $params);
1649 * Get control options for calendar.
1651 * @param string $type of calendar
1652 * @param array $data calendar information
1653 * @return string $content return available control for the calender in html
1655 function calendar_top_controls($type, $data) {
1656 global $PAGE, $OUTPUT;
1658 // Get the calendar type we are using.
1659 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1663 // Ensure course id passed if relevant.
1665 if (!empty($data['id'])) {
1666 $courseid = '&course=' . $data['id'];
1669 // If we are passing a month and year then we need to convert this to a timestamp to
1670 // support multiple calendars. No where in core should these be passed, this logic
1671 // here is for third party plugins that may use this function.
1672 if (!empty($data['m']) && !empty($date['y'])) {
1673 if (!isset($data['d'])) {
1676 if (!checkdate($data['m'], $data['d'], $data['y'])) {
1679 $time = make_timestamp($data['y'], $data['m'], $data['d']);
1681 } else if (!empty($data['time'])) {
1682 $time = $data['time'];
1687 // Get the date for the calendar type.
1688 $date = $calendartype->timestamp_to_date_array($time);
1690 $urlbase = $PAGE->url
;
1692 // We need to get the previous and next months in certain cases.
1693 if ($type == 'frontpage' ||
$type == 'course' ||
$type == 'month') {
1694 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1695 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
1696 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
1697 $prevmonthtime['hour'], $prevmonthtime['minute']);
1699 $nextmonth = calendar_add_month($date['mon'], $date['year']);
1700 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
1701 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
1702 $nextmonthtime['hour'], $nextmonthtime['minute']);
1707 $prevlink = calendar_get_link_previous(get_string('monthprev', 'calendar'), $urlbase, false, false, false,
1708 true, $prevmonthtime);
1709 $nextlink = calendar_get_link_next(get_string('monthnext', 'calendar'), $urlbase, false, false, false, true,
1711 $calendarlink = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', array('view' => 'month')),
1712 false, false, false, $time);
1714 if (!empty($data['id'])) {
1715 $calendarlink->param('course', $data['id']);
1720 $content .= \html_writer
::start_tag('div', array('class' => 'calendar-controls'));
1721 $content .= $prevlink . '<span class="hide"> | </span>';
1722 $content .= \html_writer
::tag('span', \html_writer
::link($calendarlink,
1723 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1724 ), array('class' => 'current'));
1725 $content .= '<span class="hide"> | </span>' . $right;
1726 $content .= "<span class=\"clearer\"><!-- --></span>\n";
1727 $content .= \html_writer
::end_tag('div');
1731 $prevlink = calendar_get_link_previous(get_string('monthprev', 'calendar'), $urlbase, false, false, false,
1732 true, $prevmonthtime);
1733 $nextlink = calendar_get_link_next(get_string('monthnext', 'calendar'), $urlbase, false, false, false,
1734 true, $nextmonthtime);
1735 $calendarlink = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', array('view' => 'month')),
1736 false, false, false, $time);
1738 if (!empty($data['id'])) {
1739 $calendarlink->param('course', $data['id']);
1742 $content .= \html_writer
::start_tag('div', array('class' => 'calendar-controls'));
1743 $content .= $prevlink . '<span class="hide"> | </span>';
1744 $content .= \html_writer
::tag('span', \html_writer
::link($calendarlink,
1745 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1746 ), array('class' => 'current'));
1747 $content .= '<span class="hide"> | </span>' . $nextlink;
1748 $content .= "<span class=\"clearer\"><!-- --></span>";
1749 $content .= \html_writer
::end_tag('div');
1752 $calendarlink = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', array('view' => 'upcoming')),
1753 false, false, false, $time);
1754 if (!empty($data['id'])) {
1755 $calendarlink->param('course', $data['id']);
1757 $calendarlink = \html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1758 $content .= \html_writer
::tag('div', $calendarlink, array('class' => 'centered'));
1761 $calendarlink = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', array('view' => 'month')),
1762 false, false, false, $time);
1763 if (!empty($data['id'])) {
1764 $calendarlink->param('course', $data['id']);
1766 $calendarlink = \html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1767 $content .= \html_writer
::tag('h3', $calendarlink);
1770 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1771 'view.php?view=month' . $courseid . '&', false, false, false, false, $prevmonthtime);
1772 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1773 'view.php?view=month' . $courseid . '&', false, false, false, false, $nextmonthtime);
1775 $content .= \html_writer
::start_tag('div', array('class' => 'calendar-controls'));
1776 $content .= $prevlink . '<span class="hide"> | </span>';
1777 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1778 $content .= '<span class="hide"> | </span>' . $nextlink;
1779 $content .= '<span class="clearer"><!-- --></span>';
1780 $content .= \html_writer
::end_tag('div')."\n";
1783 $days = calendar_get_days();
1785 $prevtimestamp = strtotime('-1 day', $time);
1786 $nexttimestamp = strtotime('+1 day', $time);
1788 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1789 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1791 $prevname = $days[$prevdate['wday']]['fullname'];
1792 $nextname = $days[$nextdate['wday']]['fullname'];
1793 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&', false, false,
1794 false, false, $prevtimestamp);
1795 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&', false, false, false,
1796 false, $nexttimestamp);
1798 $content .= \html_writer
::start_tag('div', array('class' => 'calendar-controls'));
1799 $content .= $prevlink;
1800 $content .= '<span class="hide"> | </span><span class="current">' .userdate($time,
1801 get_string('strftimedaydate')) . '</span>';
1802 $content .= '<span class="hide"> | </span>' . $nextlink;
1803 $content .= "<span class=\"clearer\"><!-- --></span>";
1804 $content .= \html_writer
::end_tag('div') . "\n";
1813 * Return the representation day.
1815 * @param int $tstamp Timestamp in GMT
1816 * @param int|bool $now current Unix timestamp
1817 * @param bool $usecommonwords
1818 * @return string the formatted date/time
1820 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1821 static $shortformat;
1823 if (empty($shortformat)) {
1824 $shortformat = get_string('strftimedayshort');
1827 if ($now === false) {
1831 // To have it in one place, if a change is needed.
1832 $formal = userdate($tstamp, $shortformat);
1834 $datestamp = usergetdate($tstamp);
1835 $datenow = usergetdate($now);
1837 if ($usecommonwords == false) {
1838 // We don't want words, just a date.
1840 } else if ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1841 return get_string('today', 'calendar');
1842 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1843 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12
1844 && $datenow['yday'] == 1)) {
1845 return get_string('yesterday', 'calendar');
1846 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] +
1 ) ||
1847 ($datestamp['year'] == $datenow['year'] +
1 && $datenow['mday'] == 31 && $datenow['mon'] == 12
1848 && $datestamp['yday'] == 1)) {
1849 return get_string('tomorrow', 'calendar');
1856 * return the formatted representation time.
1859 * @param int $time the timestamp in UTC, as obtained from the database
1860 * @return string the formatted date/time
1862 function calendar_time_representation($time) {
1863 static $langtimeformat = null;
1865 if ($langtimeformat === null) {
1866 $langtimeformat = get_string('strftimetime');
1869 $timeformat = get_user_preferences('calendar_timeformat');
1870 if (empty($timeformat)) {
1871 $timeformat = get_config(null, 'calendar_site_timeformat');
1874 // Allow language customization of selected time format.
1875 if ($timeformat === CALENDAR_TF_12
) {
1876 $timeformat = get_string('strftimetime12', 'langconfig');
1877 } else if ($timeformat === CALENDAR_TF_24
) {
1878 $timeformat = get_string('strftimetime24', 'langconfig');
1881 return userdate($time, empty($timeformat) ?
$langtimeformat : $timeformat);
1885 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1887 * @param string|moodle_url $linkbase
1888 * @param int $d The number of the day.
1889 * @param int $m The number of the month.
1890 * @param int $y The number of the year.
1891 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1892 * $m and $y are kept for backwards compatibility.
1893 * @return moodle_url|null $linkbase
1895 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1896 if (empty($linkbase)) {
1900 if (!($linkbase instanceof \moodle_url
)) {
1901 $linkbase = new \
moodle_url($linkbase);
1904 $linkbase->param('time', calendar_get_timestamp($d, $m, $y, $time));
1910 * Build and return a previous month HTML link, with an arrow.
1912 * @param string $text The text label.
1913 * @param string|moodle_url $linkbase The URL stub.
1914 * @param int $d The number of the date.
1915 * @param int $m The number of the month.
1916 * @param int $y year The number of the year.
1917 * @param bool $accesshide Default visible, or hide from all except screenreaders.
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 string HTML string.
1922 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1923 $href = calendar_get_link_href(new \
moodle_url($linkbase), $d, $m, $y, $time);
1930 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1931 'data-drop-zone' => 'nav-link',
1934 return link_arrow_left($text, $href->out(false), $accesshide, 'previous', $attrs);
1938 * Build and return a next month HTML link, with an arrow.
1940 * @param string $text The text label.
1941 * @param string|moodle_url $linkbase The URL stub.
1942 * @param int $d the number of the Day
1943 * @param int $m The number of the month.
1944 * @param int $y 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_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1951 $href = calendar_get_link_href(new \
moodle_url($linkbase), $d, $m, $y, $time);
1958 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1959 'data-drop-zone' => 'nav-link',
1962 return link_arrow_right($text, $href->out(false), $accesshide, 'next', $attrs);
1966 * Return the number of days in month.
1968 * @param int $month the number of the month.
1969 * @param int $year the number of the year
1972 function calendar_days_in_month($month, $year) {
1973 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1974 return $calendartype->get_num_days_in_month($year, $month);
1978 * Get the next following month.
1980 * @param int $month the number of the month.
1981 * @param int $year the number of the year.
1982 * @return array the following month
1984 function calendar_add_month($month, $year) {
1985 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1986 return $calendartype->get_next_month($year, $month);
1990 * Get the previous month.
1992 * @param int $month the number of the month.
1993 * @param int $year the number of the year.
1994 * @return array previous month
1996 function calendar_sub_month($month, $year) {
1997 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1998 return $calendartype->get_prev_month($year, $month);
2002 * Get per-day basis events
2004 * @param array $events list of events
2005 * @param int $month the number of the month
2006 * @param int $year the number of the year
2007 * @param array $eventsbyday event on specific day
2008 * @param array $durationbyday duration of the event in days
2009 * @param array $typesbyday event type (eg: site, course, user, or group)
2010 * @param array $courses list of courses
2013 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
2014 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2016 $eventsbyday = array();
2017 $typesbyday = array();
2018 $durationbyday = array();
2020 if ($events === false) {
2024 foreach ($events as $event) {
2025 $startdate = $calendartype->timestamp_to_date_array($event->timestart
);
2026 if ($event->timeduration
) {
2027 $enddate = $calendartype->timestamp_to_date_array($event->timestart +
$event->timeduration
- 1);
2029 $enddate = $startdate;
2032 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair.
2033 if (!($startdate['year'] * 13 +
$startdate['mon'] <= $year * 13 +
$month) &&
2034 ($enddate['year'] * 13 +
$enddate['mon'] >= $year * 13 +
$month)) {
2038 $eventdaystart = intval($startdate['mday']);
2040 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2041 // Give the event to its day.
2042 $eventsbyday[$eventdaystart][] = $event->id
;
2044 // Mark the day as having such an event.
2045 if ($event->courseid
== SITEID
&& $event->groupid
== 0) {
2046 $typesbyday[$eventdaystart]['startsite'] = true;
2047 // Set event class for site event.
2048 $events[$event->id
]->class = 'calendar_event_site';
2049 } else if ($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) {
2050 $typesbyday[$eventdaystart]['startcourse'] = true;
2051 // Set event class for course event.
2052 $events[$event->id
]->class = 'calendar_event_course';
2053 } else if ($event->groupid
) {
2054 $typesbyday[$eventdaystart]['startgroup'] = true;
2055 // Set event class for group event.
2056 $events[$event->id
]->class = 'calendar_event_group';
2057 } else if ($event->userid
) {
2058 $typesbyday[$eventdaystart]['startuser'] = true;
2059 // Set event class for user event.
2060 $events[$event->id
]->class = 'calendar_event_user';
2064 if ($event->timeduration
== 0) {
2065 // Proceed with the next.
2069 // The event starts on $month $year or before.
2070 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2071 $lowerbound = intval($startdate['mday']);
2076 // Also, it ends on $month $year or later.
2077 if ($enddate['mon'] == $month && $enddate['year'] == $year) {
2078 $upperbound = intval($enddate['mday']);
2080 $upperbound = calendar_days_in_month($month, $year);
2083 // Mark all days between $lowerbound and $upperbound (inclusive) as duration.
2084 for ($i = $lowerbound +
1; $i <= $upperbound; ++
$i) {
2085 $durationbyday[$i][] = $event->id
;
2086 if ($event->courseid
== SITEID
&& $event->groupid
== 0) {
2087 $typesbyday[$i]['durationsite'] = true;
2088 } else if ($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) {
2089 $typesbyday[$i]['durationcourse'] = true;
2090 } else if ($event->groupid
) {
2091 $typesbyday[$i]['durationgroup'] = true;
2092 } else if ($event->userid
) {
2093 $typesbyday[$i]['durationuser'] = true;
2102 * Returns the courses to load events for.
2104 * @param array $courseeventsfrom An array of courses to load calendar events for
2105 * @param bool $ignorefilters specify the use of filters, false is set as default
2106 * @param stdClass $user The user object. This defaults to the global $USER object.
2107 * @return array An array of courses, groups, and user to load calendar events for based upon filters
2109 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false, stdClass
$user = null) {
2112 if (is_null($user)) {
2120 // Get the capabilities that allow seeing group events from all groups.
2121 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
2123 $isvaliduser = !empty($user->id
);
2125 if ($ignorefilters ||
calendar_show_event_type(CALENDAR_EVENT_COURSE
, $user)) {
2126 $courses = array_keys($courseeventsfrom);
2128 if ($ignorefilters ||
calendar_show_event_type(CALENDAR_EVENT_SITE
, $user)) {
2129 $courses[] = SITEID
;
2131 $courses = array_unique($courses);
2134 if (!empty($courses) && in_array(SITEID
, $courses)) {
2135 // Sort courses for consistent colour highlighting.
2136 // Effectively ignoring SITEID as setting as last course id.
2137 $key = array_search(SITEID
, $courses);
2138 unset($courses[$key]);
2139 $courses[] = SITEID
;
2142 if ($ignorefilters ||
($isvaliduser && calendar_show_event_type(CALENDAR_EVENT_USER
, $user))) {
2143 $userid = $user->id
;
2146 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP
, $user) ||
$ignorefilters)) {
2148 if (count($courseeventsfrom) == 1) {
2149 $course = reset($courseeventsfrom);
2150 if (has_any_capability($allgroupscaps, \context_course
::instance($course->id
))) {
2151 $coursegroups = groups_get_all_groups($course->id
, 0, 0, 'g.id');
2152 $group = array_keys($coursegroups);
2155 if ($group === false) {
2156 if (!empty($CFG->calendar_adminseesall
) && has_any_capability($allgroupscaps, \context_system
::instance())) {
2158 } else if ($isvaliduser) {
2159 $groupids = array();
2160 foreach ($courseeventsfrom as $courseid => $course) {
2161 if ($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
2162 // If this course has groups, show events from all of those related to the current user.
2163 $coursegroups = groups_get_user_groups($course->id
, $user->id
);
2164 $groupids = array_merge($groupids, $coursegroups['0']);
2167 if (!empty($groupids)) {
2173 if (empty($courses)) {
2177 return array($courses, $group, $userid);
2181 * Can current user manage a non user event in system context.
2183 * @param calendar_event|stdClass $event event object
2186 function calendar_can_manage_non_user_event_in_system($event) {
2187 $sitecontext = \context_system
::instance();
2188 $isuserevent = $event->eventtype
== 'user';
2189 $canmanageentries = has_capability('moodle/calendar:manageentries', $sitecontext);
2190 // If user has manageentries at site level and it's not user event, return true.
2191 if ($canmanageentries && !$isuserevent) {
2199 * Return the capability for viewing a calendar event.
2201 * @param calendar_event $event event object
2204 function calendar_view_event_allowed(calendar_event
$event) {
2207 // Anyone can see site events.
2208 if ($event->courseid
&& $event->courseid
== SITEID
) {
2212 if (calendar_can_manage_non_user_event_in_system($event)) {
2216 if (!empty($event->groupid
)) {
2217 // If it is a group event we need to be able to manage events in the course, or be in the group.
2218 if (has_capability('moodle/calendar:manageentries', $event->context
) ||
2219 has_capability('moodle/calendar:managegroupentries', $event->context
)) {
2223 $mycourses = enrol_get_my_courses('id');
2224 return isset($mycourses[$event->courseid
]) && groups_is_member($event->groupid
);
2225 } else if ($event->modulename
) {
2226 // If this is a module event we need to be able to see the module.
2227 $coursemodules = [];
2229 // Override events do not have the courseid set.
2230 if ($event->courseid
) {
2231 $courseid = $event->courseid
;
2232 $coursemodules = get_fast_modinfo($event->courseid
)->instances
;
2234 $cmraw = get_coursemodule_from_instance($event->modulename
, $event->instance
, 0, false, MUST_EXIST
);
2235 $courseid = $cmraw->course
;
2236 $coursemodules = get_fast_modinfo($cmraw->course
)->instances
;
2238 $hasmodule = isset($coursemodules[$event->modulename
]);
2239 $hasinstance = isset($coursemodules[$event->modulename
][$event->instance
]);
2241 // If modinfo doesn't know about the module, return false to be safe.
2242 if (!$hasmodule ||
!$hasinstance) {
2246 // Must be able to see the course and the module - MDL-59304.
2247 $cm = $coursemodules[$event->modulename
][$event->instance
];
2248 if (!$cm->uservisible
) {
2251 $mycourses = enrol_get_my_courses('id');
2252 return isset($mycourses[$courseid]);
2253 } else if ($event->categoryid
) {
2254 // If this is a category we need to be able to see the category.
2255 $cat = \core_course_category
::get($event->categoryid
, IGNORE_MISSING
);
2260 } else if (!empty($event->courseid
)) {
2261 // If it is a course event we need to be able to manage events in the course, or be in the course.
2262 if (has_capability('moodle/calendar:manageentries', $event->context
)) {
2266 return can_access_course(get_course($event->courseid
));
2267 } else if ($event->userid
) {
2268 return calendar_can_manage_user_event($event);
2270 throw new moodle_exception('unknown event type');
2277 * Return the capability for editing calendar event.
2279 * @param calendar_event $event event object
2280 * @param bool $manualedit is the event being edited manually by the user
2281 * @return bool capability to edit event
2283 function calendar_edit_event_allowed($event, $manualedit = false) {
2286 // Must be logged in.
2287 if (!isloggedin()) {
2291 // Can not be using guest account.
2292 if (isguestuser()) {
2296 if ($manualedit && !empty($event->modulename
)) {
2297 $hascallback = component_callback_exists(
2298 'mod_' . $event->modulename
,
2299 'core_calendar_event_timestart_updated'
2302 if (!$hascallback) {
2303 // If the activity hasn't implemented the correct callback
2304 // to handle changes to it's events then don't allow any
2305 // manual changes to them.
2309 $coursemodules = get_fast_modinfo($event->courseid
)->instances
;
2310 $hasmodule = isset($coursemodules[$event->modulename
]);
2311 $hasinstance = isset($coursemodules[$event->modulename
][$event->instance
]);
2313 // If modinfo doesn't know about the module, return false to be safe.
2314 if (!$hasmodule ||
!$hasinstance) {
2318 $coursemodule = $coursemodules[$event->modulename
][$event->instance
];
2319 $context = context_module
::instance($coursemodule->id
);
2320 // This is the capability that allows a user to modify the activity
2321 // settings. Since the activity generated this event we need to check
2322 // that the current user has the same capability before allowing them
2323 // to update the event because the changes to the event will be
2324 // reflected within the activity.
2325 return has_capability('moodle/course:manageactivities', $context);
2328 if ($manualedit && !empty($event->component
)) {
2329 // TODO possibly we can later add a callback similar to core_calendar_event_timestart_updated in the modules.
2333 // You cannot edit URL based calendar subscription events presently.
2334 if (!empty($event->subscriptionid
)) {
2335 if (!empty($event->subscription
->url
)) {
2336 // This event can be updated externally, so it cannot be edited.
2341 if (calendar_can_manage_non_user_event_in_system($event)) {
2345 // If groupid is set, it's definitely a group event.
2346 if (!empty($event->groupid
)) {
2347 // Allow users to add/edit group events if -
2348 // 1) They have manageentries for the course OR
2349 // 2) They have managegroupentries AND are in the group.
2350 $group = $DB->get_record('groups', array('id' => $event->groupid
));
2352 has_capability('moodle/calendar:manageentries', $event->context
) ||
2353 (has_capability('moodle/calendar:managegroupentries', $event->context
)
2354 && groups_is_member($event->groupid
)));
2355 } else if (!empty($event->courseid
)) {
2356 // If groupid is not set, but course is set, it's definitely a course event.
2357 return has_capability('moodle/calendar:manageentries', $event->context
);
2358 } else if (!empty($event->categoryid
)) {
2359 // If groupid is not set, but category is set, it's definitely a category event.
2360 return has_capability('moodle/calendar:manageentries', $event->context
);
2361 } else if (!empty($event->userid
) && $event->userid
== $USER->id
) {
2362 // If course is not set, but userid id set, it's a user event.
2363 return (has_capability('moodle/calendar:manageownentries', $event->context
));
2364 } else if (!empty($event->userid
)) {
2365 return calendar_can_manage_user_event($event);
2372 * Can current user edit/delete/add an user event?
2374 * @param calendar_event|stdClass $event event object
2377 function calendar_can_manage_user_event($event): bool {
2380 if (!($event instanceof \calendar_event
)) {
2381 $event = new \
calendar_event(clone($event));
2384 $canmanage = has_capability('moodle/calendar:manageentries', $event->context
);
2385 $canmanageown = has_capability('moodle/calendar:manageownentries', $event->context
);
2386 $ismyevent = $event->userid
== $USER->id
;
2387 $isadminevent = is_siteadmin($event->userid
);
2389 if ($canmanageown && $ismyevent) {
2393 // In site context, user must have login and calendar:manageentries permissions
2394 // ... to manage other user's events except admin users.
2395 if ($canmanage && !$isadminevent) {
2403 * Return the capability for deleting a calendar event.
2405 * @param calendar_event $event The event object
2406 * @return bool Whether the user has permission to delete the event or not.
2408 function calendar_delete_event_allowed($event) {
2409 // Only allow delete if you have capabilities and it is not an module or component event.
2410 return (calendar_edit_event_allowed($event) && empty($event->modulename
) && empty($event->component
));
2414 * Returns the default courses to display on the calendar when there isn't a specific
2415 * course to display.
2417 * @param int $courseid (optional) If passed, an additional course can be returned for admins (the current course).
2418 * @param string $fields Comma separated list of course fields to return.
2419 * @param bool $canmanage If true, this will return the list of courses the user can create events in, rather
2420 * than the list of courses they see events from (an admin can always add events in a course
2421 * calendar, even if they are not enrolled in the course).
2422 * @param int $userid (optional) The user which this function returns the default courses for.
2423 * By default the current user.
2424 * @return array $courses Array of courses to display
2426 function calendar_get_default_courses($courseid = null, $fields = '*', $canmanage = false, int $userid = null) {
2430 if (!isloggedin()) {
2433 $userid = $USER->id
;
2436 if ((!empty($CFG->calendar_adminseesall
) ||
$canmanage) &&
2437 has_capability('moodle/calendar:manageentries', context_system
::instance(), $userid)) {
2439 // Add a c. prefix to every field as expected by get_courses function.
2440 $fieldlist = explode(',', $fields);
2442 $prefixedfields = array_map(function($value) {
2443 return 'c.' . trim(strtolower($value));
2446 $courses = get_courses('all', 'c.shortname', implode(',', $prefixedfields));
2448 $courses = enrol_get_users_courses($userid, true, $fields);
2451 if ($courseid && $courseid != SITEID
) {
2452 if (empty($courses[$courseid]) && has_capability('moodle/calendar:manageentries', context_system
::instance(), $userid)) {
2453 // Allow a site admin to see calendars from courses he is not enrolled in.
2454 // This will come from $COURSE.
2455 $courses[$courseid] = get_course($courseid);
2463 * Get event format time.
2465 * @param calendar_event $event event object
2466 * @param int $now current time in gmt
2467 * @param array $linkparams list of params for event link
2468 * @param bool $usecommonwords the words as formatted date/time.
2469 * @param int $showtime determine the show time GMT timestamp
2470 * @return string $eventtime link/string for event time
2472 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
2473 $starttime = $event->timestart
;
2474 $endtime = $event->timestart +
$event->timeduration
;
2476 if (empty($linkparams) ||
!is_array($linkparams)) {
2477 $linkparams = array();
2480 $linkparams['view'] = 'day';
2482 // OK, now to get a meaningful display.
2483 // Check if there is a duration for this event.
2484 if ($event->timeduration
) {
2485 // Get the midnight of the day the event will start.
2486 $usermidnightstart = usergetmidnight($starttime);
2487 // Get the midnight of the day the event will end.
2488 $usermidnightend = usergetmidnight($endtime);
2489 // Check if we will still be on the same day.
2490 if ($usermidnightstart == $usermidnightend) {
2491 // Check if we are running all day.
2492 if ($event->timeduration
== DAYSECS
) {
2493 $time = get_string('allday', 'calendar');
2494 } else { // Specify the time we will be running this from.
2495 $datestart = calendar_time_representation($starttime);
2496 $dateend = calendar_time_representation($endtime);
2497 $time = $datestart . ' <strong>»</strong> ' . $dateend;
2500 // Set printable representation.
2502 $day = calendar_day_representation($event->timestart
, $now, $usecommonwords);
2503 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $endtime);
2504 $eventtime = \html_writer
::link($url, $day) . ', ' . $time;
2508 } else { // It must spans two or more days.
2509 $daystart = calendar_day_representation($event->timestart
, $now, $usecommonwords) . ', ';
2510 if ($showtime == $usermidnightstart) {
2513 $timestart = calendar_time_representation($event->timestart
);
2514 $dayend = calendar_day_representation($event->timestart +
$event->timeduration
, $now, $usecommonwords) . ', ';
2515 if ($showtime == $usermidnightend) {
2518 $timeend = calendar_time_representation($event->timestart +
$event->timeduration
);
2520 // Set printable representation.
2521 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2522 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $endtime);
2523 $eventtime = $timestart . ' <strong>»</strong> ' . \html_writer
::link($url, $dayend) . $timeend;
2525 // The event is in the future, print start and end links.
2526 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $starttime);
2527 $eventtime = \html_writer
::link($url, $daystart) . $timestart . ' <strong>»</strong> ';
2529 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $endtime);
2530 $eventtime .= \html_writer
::link($url, $dayend) . $timeend;
2533 } else { // There is no time duration.
2534 $time = calendar_time_representation($event->timestart
);
2535 // Set printable representation.
2537 $day = calendar_day_representation($event->timestart
, $now, $usecommonwords);
2538 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $starttime);
2539 $eventtime = \html_writer
::link($url, $day) . ', ' . trim($time);
2545 // Check if It has expired.
2546 if ($event->timestart +
$event->timeduration
< $now) {
2547 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2554 * Checks to see if the requested type of event should be shown for the given user.
2556 * @param int $type The type to check the display for (default is to display all)
2557 * @param stdClass|int|null $user The user to check for - by default the current user
2558 * @return bool True if the tyep should be displayed false otherwise
2560 function calendar_show_event_type($type, $user = null) {
2561 $default = CALENDAR_EVENT_SITE + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER
;
2563 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2565 if (!isset($SESSION->calendarshoweventtype
)) {
2566 $SESSION->calendarshoweventtype
= $default;
2568 return $SESSION->calendarshoweventtype
& $type;
2570 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2575 * Sets the display of the event type given $display.
2577 * If $display = true the event type will be shown.
2578 * If $display = false the event type will NOT be shown.
2579 * If $display = null the current value will be toggled and saved.
2581 * @param int $type object of CALENDAR_EVENT_XXX
2582 * @param bool $display option to display event type
2583 * @param stdClass|int $user moodle user object or id, null means current user
2585 function calendar_set_event_type_display($type, $display = null, $user = null) {
2586 $persist = get_user_preferences('calendar_persistflt', 0, $user);
2587 $default = CALENDAR_EVENT_SITE + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP
2588 + CALENDAR_EVENT_USER + CALENDAR_EVENT_COURSECAT
;
2589 if ($persist === 0) {
2591 if (!isset($SESSION->calendarshoweventtype
)) {
2592 $SESSION->calendarshoweventtype
= $default;
2594 $preference = $SESSION->calendarshoweventtype
;
2596 $preference = get_user_preferences('calendar_savedflt', $default, $user);
2598 $current = $preference & $type;
2599 if ($display === null) {
2600 $display = !$current;
2602 if ($display && !$current) {
2603 $preference +
= $type;
2604 } else if (!$display && $current) {
2605 $preference -= $type;
2607 if ($persist === 0) {
2608 $SESSION->calendarshoweventtype
= $preference;
2610 if ($preference == $default) {
2611 unset_user_preference('calendar_savedflt', $user);
2613 set_user_preference('calendar_savedflt', $preference, $user);
2619 * Get calendar's allowed types.
2621 * @param stdClass $allowed list of allowed edit for event type
2622 * @param stdClass|int $course object of a course or course id
2623 * @param array $groups array of groups for the given course
2624 * @param stdClass|int $category object of a category
2626 function calendar_get_allowed_types(&$allowed, $course = null, $groups = null, $category = null) {
2629 $allowed = new \
stdClass();
2630 $allowed->user
= has_capability('moodle/calendar:manageownentries', \context_system
::instance());
2631 $allowed->groups
= false;
2632 $allowed->courses
= false;
2633 $allowed->categories
= false;
2634 $allowed->site
= has_capability('moodle/calendar:manageentries', \context_course
::instance(SITEID
));
2635 $getgroupsfunc = function($course, $context, $user) use ($groups) {
2636 if ($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
2637 if (has_capability('moodle/site:accessallgroups', $context)) {
2638 return is_null($groups) ?
groups_get_all_groups($course->id
) : $groups;
2640 if (is_null($groups)) {
2641 return groups_get_all_groups($course->id
, $user->id
);
2643 return array_filter($groups, function($group) use ($user) {
2644 return isset($group->members
[$user->id
]);
2653 if (!empty($course)) {
2654 if (!is_object($course)) {
2655 $course = $DB->get_record('course', array('id' => $course), 'id, groupmode, groupmodeforce', MUST_EXIST
);
2657 if ($course->id
!= SITEID
) {
2658 $coursecontext = \context_course
::instance($course->id
);
2659 $allowed->user
= has_capability('moodle/calendar:manageownentries', $coursecontext);
2661 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2662 $allowed->courses
= array($course->id
=> 1);
2663 $allowed->groups
= $getgroupsfunc($course, $coursecontext, $USER);
2664 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
2665 $allowed->groups
= $getgroupsfunc($course, $coursecontext, $USER);
2670 if (!empty($category)) {
2671 $catcontext = \context_coursecat
::instance($category->id
);
2672 if (has_capability('moodle/category:manage', $catcontext)) {
2673 $allowed->categories
= [$category->id
=> 1];
2679 * See if user can add calendar entries at all used to print the "New Event" button.
2681 * @param stdClass $course object of a course or course id
2682 * @return bool has the capability to add at least one event type
2684 function calendar_user_can_add_event($course) {
2685 if (!isloggedin() ||
isguestuser()) {
2689 calendar_get_allowed_types($allowed, $course);
2691 return (bool)($allowed->user ||
$allowed->groups ||
$allowed->courses ||
$allowed->categories ||
$allowed->site
);
2695 * Check wether the current user is permitted to add events.
2697 * @param stdClass $event object of event
2698 * @return bool has the capability to add event
2700 function calendar_add_event_allowed($event) {
2703 // Can not be using guest account.
2704 if (!isloggedin() or isguestuser()) {
2708 if (calendar_can_manage_non_user_event_in_system($event)) {
2712 switch ($event->eventtype
) {
2714 return has_capability('moodle/category:manage', $event->context
);
2716 return has_capability('moodle/calendar:manageentries', $event->context
);
2718 // Allow users to add/edit group events if -
2719 // 1) They have manageentries (= entries for whole course).
2720 // 2) They have managegroupentries AND are in the group.
2721 $group = $DB->get_record('groups', array('id' => $event->groupid
));
2723 has_capability('moodle/calendar:manageentries', $event->context
) ||
2724 (has_capability('moodle/calendar:managegroupentries', $event->context
)
2725 && groups_is_member($event->groupid
)));
2727 return calendar_can_manage_user_event($event);
2729 return has_capability('moodle/calendar:manageentries', $event->context
);
2731 return has_capability('moodle/calendar:manageentries', $event->context
);
2736 * Returns option list for the poll interval setting.
2738 * @return array An array of poll interval options. Interval => description.
2740 function calendar_get_pollinterval_choices() {
2742 '0' => get_string('never', 'calendar'),
2743 HOURSECS
=> get_string('hourly', 'calendar'),
2744 DAYSECS
=> get_string('daily', 'calendar'),
2745 WEEKSECS
=> get_string('weekly', 'calendar'),
2746 '2628000' => get_string('monthly', 'calendar'),
2747 YEARSECS
=> get_string('annually', 'calendar')
2752 * Returns option list of available options for the calendar event type, given the current user and course.
2754 * @param int $courseid The id of the course
2755 * @return array An array containing the event types the user can create.
2757 function calendar_get_eventtype_choices($courseid) {
2759 $allowed = new \stdClass
;
2760 calendar_get_allowed_types($allowed, $courseid);
2762 if ($allowed->user
) {
2763 $choices['user'] = get_string('userevents', 'calendar');
2765 if ($allowed->site
) {
2766 $choices['site'] = get_string('siteevents', 'calendar');
2768 if (!empty($allowed->courses
)) {
2769 $choices['course'] = get_string('courseevents', 'calendar');
2771 if (!empty($allowed->categories
)) {
2772 $choices['category'] = get_string('categoryevents', 'calendar');
2774 if (!empty($allowed->groups
) and is_array($allowed->groups
)) {
2775 $choices['group'] = get_string('group');
2778 return array($choices, $allowed->groups
);
2782 * Add an iCalendar subscription to the database.
2784 * @param stdClass $sub The subscription object (e.g. from the form)
2785 * @return int The insert ID, if any.
2787 function calendar_add_subscription($sub) {
2788 global $DB, $USER, $SITE;
2790 // Undo the form definition work around to allow us to have two different
2791 // course selectors present depending on which event type the user selects.
2792 if (!empty($sub->groupcourseid
)) {
2793 $sub->courseid
= $sub->groupcourseid
;
2794 unset($sub->groupcourseid
);
2797 // Default course id if none is set.
2798 if (empty($sub->courseid
)) {
2799 if ($sub->eventtype
=== 'site') {
2800 $sub->courseid
= SITEID
;
2806 if ($sub->eventtype
=== 'site') {
2807 $sub->courseid
= $SITE->id
;
2808 } else if ($sub->eventtype
=== 'group' ||
$sub->eventtype
=== 'course') {
2809 $sub->courseid
= $sub->courseid
;
2810 } else if ($sub->eventtype
=== 'category') {
2811 $sub->categoryid
= $sub->categoryid
;
2816 $sub->userid
= $USER->id
;
2818 // File subscriptions never update.
2819 if (empty($sub->url
)) {
2820 $sub->pollinterval
= 0;
2823 if (!empty($sub->name
)) {
2824 if (empty($sub->id
)) {
2825 $id = $DB->insert_record('event_subscriptions', $sub);
2826 // We cannot cache the data here because $sub is not complete.
2828 // Trigger event, calendar subscription added.
2829 $eventparams = array('objectid' => $sub->id
,
2830 'context' => calendar_get_calendar_context($sub),
2832 'eventtype' => $sub->eventtype
,
2835 switch ($sub->eventtype
) {
2837 $eventparams['other']['categoryid'] = $sub->categoryid
;
2840 $eventparams['other']['courseid'] = $sub->courseid
;
2843 $eventparams['other']['courseid'] = $sub->courseid
;
2844 $eventparams['other']['groupid'] = $sub->groupid
;
2847 $eventparams['other']['courseid'] = $sub->courseid
;
2850 $event = \core\event\calendar_subscription_created
::create($eventparams);
2854 // Why are we doing an update here?
2855 calendar_update_subscription($sub);
2859 print_error('errorbadsubscription', 'importcalendar');
2864 * Add an iCalendar event to the Moodle calendar.
2866 * @param stdClass $event The RFC-2445 iCalendar event
2867 * @param int $unused Deprecated
2868 * @param int $subscriptionid The iCalendar subscription ID
2869 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2870 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2871 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2873 function calendar_add_icalendar_event($event, $unused, $subscriptionid, $timezone='UTC') {
2876 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2877 if (empty($event->properties
['SUMMARY'])) {
2881 $name = $event->properties
['SUMMARY'][0]->value
;
2882 $name = str_replace('\n', '<br />', $name);
2883 $name = str_replace('\\', '', $name);
2884 $name = preg_replace('/\s+/u', ' ', $name);
2886 $eventrecord = new \stdClass
;
2887 $eventrecord->name
= clean_param($name, PARAM_NOTAGS
);
2889 if (empty($event->properties
['DESCRIPTION'][0]->value
)) {
2892 $description = $event->properties
['DESCRIPTION'][0]->value
;
2893 $description = clean_param($description, PARAM_NOTAGS
);
2894 $description = str_replace('\n', '<br />', $description);
2895 $description = str_replace('\\', '', $description);
2896 $description = preg_replace('/\s+/u', ' ', $description);
2898 $eventrecord->description
= $description;
2900 // Probably a repeating event with RRULE etc. TODO: skip for now.
2901 if (empty($event->properties
['DTSTART'][0]->value
)) {
2905 if (isset($event->properties
['DTSTART'][0]->parameters
['TZID'])) {
2906 $tz = $event->properties
['DTSTART'][0]->parameters
['TZID'];
2910 $tz = \core_date
::normalise_timezone($tz);
2911 $eventrecord->timestart
= strtotime($event->properties
['DTSTART'][0]->value
. ' ' . $tz);
2912 if (empty($event->properties
['DTEND'])) {
2913 $eventrecord->timeduration
= 0; // No duration if no end time specified.
2915 if (isset($event->properties
['DTEND'][0]->parameters
['TZID'])) {
2916 $endtz = $event->properties
['DTEND'][0]->parameters
['TZID'];
2920 $endtz = \core_date
::normalise_timezone($endtz);
2921 $eventrecord->timeduration
= strtotime($event->properties
['DTEND'][0]->value
. ' ' . $endtz) - $eventrecord->timestart
;
2924 // Check to see if it should be treated as an all day event.
2925 if ($eventrecord->timeduration
== DAYSECS
) {
2926 // Check to see if the event started at Midnight on the imported calendar.
2927 date_default_timezone_set($timezone);
2928 if (date('H:i:s', $eventrecord->timestart
) === "00:00:00") {
2929 // This event should be an all day event. This is not correct, we don't do anything differently for all day events.
2931 $eventrecord->timeduration
= 0;
2933 \core_date
::set_default_server_timezone();
2936 $eventrecord->location
= empty($event->properties
['LOCATION'][0]->value
) ?
'' :
2937 trim(str_replace('\\', '', $event->properties
['LOCATION'][0]->value
));
2938 $eventrecord->uuid
= $event->properties
['UID'][0]->value
;
2939 $eventrecord->timemodified
= time();
2941 // Add the iCal subscription details if required.
2942 // We should never do anything with an event without a subscription reference.
2943 $sub = calendar_get_subscription($subscriptionid);
2944 $eventrecord->subscriptionid
= $subscriptionid;
2945 $eventrecord->userid
= $sub->userid
;
2946 $eventrecord->groupid
= $sub->groupid
;
2947 $eventrecord->courseid
= $sub->courseid
;
2948 $eventrecord->categoryid
= $sub->categoryid
;
2949 $eventrecord->eventtype
= $sub->eventtype
;
2951 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid
,
2952 'subscriptionid' => $eventrecord->subscriptionid
))) {
2954 // Compare iCal event data against the moodle event to see if something has changed.
2955 $result = array_diff((array) $eventrecord, (array) $updaterecord);
2957 // Unset timemodified field because it's always going to be different.
2958 unset($result['timemodified']);
2960 if (count($result)) {
2961 $eventrecord->id
= $updaterecord->id
;
2962 $return = CALENDAR_IMPORT_EVENT_UPDATED
; // Update.
2964 return CALENDAR_IMPORT_EVENT_SKIPPED
;
2967 $return = CALENDAR_IMPORT_EVENT_INSERTED
; // Insert.
2970 if ($createdevent = \calendar_event
::create($eventrecord, false)) {
2971 if (!empty($event->properties
['RRULE'])) {
2972 // Repeating events.
2973 date_default_timezone_set($tz); // Change time zone to parse all events.
2974 $rrule = new \core_calendar\rrule_manager
($event->properties
['RRULE'][0]->value
);
2975 $rrule->parse_rrule();
2976 $rrule->create_events($createdevent);
2977 \core_date
::set_default_server_timezone(); // Change time zone back to what it was.
2986 * Delete subscription and all related events.
2988 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
2990 function calendar_delete_subscription($subscription) {
2993 if (!is_object($subscription)) {
2994 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST
);
2997 // Delete subscription and related events.
2998 $DB->delete_records('event', array('subscriptionid' => $subscription->id
));
2999 $DB->delete_records('event_subscriptions', array('id' => $subscription->id
));
3000 \cache_helper
::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id
));
3002 // Trigger event, calendar subscription deleted.
3003 $eventparams = array('objectid' => $subscription->id
,
3004 'context' => calendar_get_calendar_context($subscription),
3006 'eventtype' => $subscription->eventtype
,
3009 switch ($subscription->eventtype
) {
3011 $eventparams['other']['categoryid'] = $subscription->categoryid
;
3014 $eventparams['other']['courseid'] = $subscription->courseid
;
3017 $eventparams['other']['courseid'] = $subscription->courseid
;
3018 $eventparams['other']['groupid'] = $subscription->groupid
;
3021 $eventparams['other']['courseid'] = $subscription->courseid
;
3023 $event = \core\event\calendar_subscription_deleted
::create($eventparams);
3028 * From a URL, fetch the calendar and return an iCalendar object.
3030 * @param string $url The iCalendar URL
3031 * @return iCalendar The iCalendar object
3033 function calendar_get_icalendar($url) {
3036 require_once($CFG->libdir
. '/filelib.php');
3037 require_once($CFG->libdir
. '/bennu/bennu.inc.php');
3039 $curl = new \
curl();
3040 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
3041 $calendar = $curl->get($url);
3043 // Http code validation should actually be the job of curl class.
3044 if (!$calendar ||
$curl->info
['http_code'] != 200 ||
!empty($curl->errorno
)) {
3045 throw new \
moodle_exception('errorinvalidicalurl', 'calendar');
3048 $ical = new \
iCalendar();
3049 $ical->unserialize($calendar);
3055 * Import events from an iCalendar object into a course calendar.
3057 * @param iCalendar $ical The iCalendar object.
3058 * @param int|null $subscriptionid The subscription ID.
3059 * @return array A log of the import progress, including errors.
3061 function calendar_import_events_from_ical(iCalendar
$ical, int $subscriptionid = null): array {
3070 // Large calendars take a while...
3072 \core_php_time_limit
::raise(300);
3075 // Grab the timezone from the iCalendar file to be used later.
3076 if (isset($ical->properties
['X-WR-TIMEZONE'][0]->value
)) {
3077 $timezone = $ical->properties
['X-WR-TIMEZONE'][0]->value
;
3083 foreach ($ical->components
['VEVENT'] as $event) {
3084 $icaluuids[] = $event->properties
['UID'][0]->value
;
3085 $res = calendar_add_icalendar_event($event, null, $subscriptionid, $timezone);
3087 case CALENDAR_IMPORT_EVENT_UPDATED
:
3090 case CALENDAR_IMPORT_EVENT_INSERTED
:
3093 case CALENDAR_IMPORT_EVENT_SKIPPED
:
3097 if (empty($event->properties
['SUMMARY'])) {
3098 $errors[] = '(' . get_string('notitle', 'calendar') . ')';
3100 $errors[] = $event->properties
['SUMMARY'][0]->value
;
3106 $existing = $DB->get_field('event_subscriptions', 'lastupdated', ['id' => $subscriptionid]);
3107 if (!empty($existing)) {
3108 $eventsuuids = $DB->get_records_menu('event', ['subscriptionid' => $subscriptionid], '', 'id, uuid');
3110 $icaleventscount = count($icaluuids);
3112 if (count($eventsuuids) > $icaleventscount) {
3113 foreach ($eventsuuids as $eventid => $eventuuid) {
3114 if (!in_array($eventuuid, $icaluuids)) {
3115 $tobedeleted[] = $eventid;
3118 if (!empty($tobedeleted)) {
3119 $DB->delete_records_list('event', 'id', $tobedeleted);
3120 $deletedcount = count($tobedeleted);
3126 'eventsimported' => $eventcount,
3127 'eventsskipped' => $skippedcount,
3128 'eventsupdated' => $updatecount,
3129 'eventsdeleted' => $deletedcount,
3130 'haserror' => !empty($errors),
3131 'errors' => $errors,
3138 * Fetch a calendar subscription and update the events in the calendar.
3140 * @param int $subscriptionid The course ID for the calendar.
3141 * @return string A log of the import progress, including errors.
3143 function calendar_update_subscription_events($subscriptionid) {
3144 $sub = calendar_get_subscription($subscriptionid);
3146 // Don't update a file subscription.
3147 if (empty($sub->url
)) {
3148 return 'File subscription not updated.';
3151 $ical = calendar_get_icalendar($sub->url
);
3152 $return = calendar_import_events_from_ical($ical, $subscriptionid);
3153 $sub->lastupdated
= time();
3155 calendar_update_subscription($sub);
3161 * Update a calendar subscription. Also updates the associated cache.
3163 * @param stdClass|array $subscription Subscription record.
3164 * @throws coding_exception If something goes wrong
3167 function calendar_update_subscription($subscription) {
3170 if (is_array($subscription)) {
3171 $subscription = (object)$subscription;
3173 if (empty($subscription->id
) ||
!$DB->record_exists('event_subscriptions', array('id' => $subscription->id
))) {
3174 throw new \
coding_exception('Cannot update a subscription without a valid id');
3177 $DB->update_record('event_subscriptions', $subscription);
3180 $cache = \cache
::make('core', 'calendar_subscriptions');
3181 $cache->set($subscription->id
, $subscription);
3183 // Trigger event, calendar subscription updated.
3184 $eventparams = array('userid' => $subscription->userid
,
3185 'objectid' => $subscription->id
,
3186 'context' => calendar_get_calendar_context($subscription),
3188 'eventtype' => $subscription->eventtype
,
3191 switch ($subscription->eventtype
) {
3193 $eventparams['other']['categoryid'] = $subscription->categoryid
;
3196 $eventparams['other']['courseid'] = $subscription->courseid
;
3199 $eventparams['other']['courseid'] = $subscription->courseid
;
3200 $eventparams['other']['groupid'] = $subscription->groupid
;
3203 $eventparams['other']['courseid'] = $subscription->courseid
;
3205 $event = \core\event\calendar_subscription_updated
::create($eventparams);
3210 * Checks to see if the user can edit a given subscription feed.
3212 * @param mixed $subscriptionorid Subscription object or id
3213 * @return bool true if current user can edit the subscription else false
3215 function calendar_can_edit_subscription($subscriptionorid) {
3217 if (is_array($subscriptionorid)) {
3218 $subscription = (object)$subscriptionorid;
3219 } else if (is_object($subscriptionorid)) {
3220 $subscription = $subscriptionorid;
3222 $subscription = calendar_get_subscription($subscriptionorid);
3225 $allowed = new \stdClass
;
3226 $courseid = $subscription->courseid
;
3227 $categoryid = $subscription->categoryid
;
3228 $groupid = $subscription->groupid
;
3231 if (!empty($categoryid)) {
3232 $category = \core_course_category
::get($categoryid);
3234 calendar_get_allowed_types($allowed, $courseid, null, $category);
3235 switch ($subscription->eventtype
) {
3237 return ($USER->id
== $subscription->userid
&& $allowed->user
);
3239 if (isset($allowed->courses
[$courseid])) {
3240 return $allowed->courses
[$courseid];
3245 if (isset($allowed->categories
[$categoryid])) {
3246 return $allowed->categories
[$categoryid];
3251 return $allowed->site
;
3253 if (isset($allowed->groups
[$groupid])) {
3254 return $allowed->groups
[$groupid];
3264 * Helper function to determine the context of a calendar subscription.
3265 * Subscriptions can be created in two contexts COURSE, or USER.
3267 * @param stdClass $subscription
3268 * @return context instance
3270 function calendar_get_calendar_context($subscription) {
3271 // Determine context based on calendar type.
3272 if ($subscription->eventtype
=== 'site') {
3273 $context = \context_course
::instance(SITEID
);
3274 } else if ($subscription->eventtype
=== 'group' ||
$subscription->eventtype
=== 'course') {
3275 $context = \context_course
::instance($subscription->courseid
);
3277 $context = \context_user
::instance($subscription->userid
);
3283 * Implements callback user_preferences, lists preferences that users are allowed to update directly
3285 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3289 function core_calendar_user_preferences() {
3291 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS
, 'null' => NULL_NOT_ALLOWED
, 'default' => '0',
3292 'choices' => array('0', CALENDAR_TF_12
, CALENDAR_TF_24
)
3294 $preferences['calendar_startwday'] = array('type' => PARAM_INT
, 'null' => NULL_NOT_ALLOWED
, 'default' => 0,
3295 'choices' => array(0, 1, 2, 3, 4, 5, 6));
3296 $preferences['calendar_maxevents'] = array('type' => PARAM_INT
, 'choices' => range(1, 20));
3297 $preferences['calendar_lookahead'] = array('type' => PARAM_INT
, 'null' => NULL_NOT_ALLOWED
, 'default' => 365,
3298 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3299 $preferences['calendar_persistflt'] = array('type' => PARAM_INT
, 'null' => NULL_NOT_ALLOWED
, 'default' => 0,
3300 'choices' => array(0, 1));
3301 return $preferences;
3305 * Get legacy calendar events
3307 * @param int $tstart Start time of time range for events
3308 * @param int $tend End time of time range for events
3309 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3310 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3311 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3312 * @param boolean $withduration whether only events starting within time range selected
3313 * or events in progress/already started selected as well
3314 * @param boolean $ignorehidden whether to select only visible events or all events
3315 * @param array $categories array of category ids and/or objects.
3316 * @param int $limitnum Number of events to fetch or zero to fetch all.
3318 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3320 function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses,
3321 $withduration = true, $ignorehidden = true, $categories = [], $limitnum = 0) {
3322 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3323 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3324 // parameters, but with the new API method, only null and arrays are accepted.
3325 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3326 // If parameter is true, return null.
3327 if ($param === true) {
3331 // If parameter is false, return an empty array.
3332 if ($param === false) {
3336 // If the parameter is a scalar value, enclose it in an array.
3337 if (!is_array($param)) {
3341 // No normalisation required.
3343 }, [$users, $groups, $courses, $categories]);
3345 // If a single user is provided, we can use that for capability checks.
3346 // Otherwise current logged in user is used - See MDL-58768.
3347 if (is_array($userparam) && count($userparam) == 1) {
3348 \core_calendar\local\event\container
::set_requesting_user($userparam[0]);
3350 $mapper = \core_calendar\local\event\container
::get_event_mapper();
3351 $events = \core_calendar\local\api
::get_events(
3368 return array_reduce($events, function($carry, $event) use ($mapper) {
3369 return $carry +
[$event->get_id() => $mapper->from_event_to_stdclass($event)];
3375 * Get the calendar view output.
3377 * @param \calendar_information $calendar The calendar being represented
3378 * @param string $view The type of calendar to have displayed
3379 * @param bool $includenavigation Whether to include navigation
3380 * @param bool $skipevents Whether to load the events or not
3381 * @param int $lookahead Overwrites site and users's lookahead setting.
3382 * @return array[array, string]
3384 function calendar_get_view(\calendar_information
$calendar, $view, $includenavigation = true, bool $skipevents = false,
3385 ?
int $lookahead = null) {
3388 $renderer = $PAGE->get_renderer('core_calendar');
3389 $type = \core_calendar\type_factory
::get_calendar_instance();
3391 // Calculate the bounds of the month.
3392 $calendardate = $type->timestamp_to_date_array($calendar->time
);
3394 $date = new \
DateTime('now', core_date
::get_user_timezone_object(99));
3397 if ($view === 'day') {
3398 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday']);
3399 $date->setTimestamp($tstart);
3400 $date->modify('+1 day');
3401 } else if ($view === 'upcoming' ||
$view === 'upcoming_mini') {
3402 // Number of days in the future that will be used to fetch events.
3404 if (isset($CFG->calendar_lookahead
)) {
3405 $defaultlookahead = intval($CFG->calendar_lookahead
);
3407 $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD
;
3409 $lookahead = get_user_preferences('calendar_lookahead', $defaultlookahead);
3412 // Maximum number of events to be displayed on upcoming view.
3413 $defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS
;
3414 if (isset($CFG->calendar_maxevents
)) {
3415 $defaultmaxevents = intval($CFG->calendar_maxevents
);
3417 $eventlimit = get_user_preferences('calendar_maxevents', $defaultmaxevents);
3419 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday'],
3420 $calendardate['hours']);
3421 $date->setTimestamp($tstart);
3422 $date->modify('+' . $lookahead . ' days');
3424 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], 1);
3425 $monthdays = $type->get_num_days_in_month($calendardate['year'], $calendardate['mon']);
3426 $date->setTimestamp($tstart);
3427 $date->modify('+' . $monthdays . ' days');
3429 if ($view === 'mini' ||
$view === 'minithree') {
3430 $template = 'core_calendar/calendar_mini';
3432 $template = 'core_calendar/calendar_month';
3436 // We need to extract 1 second to ensure that we don't get into the next day.
3437 $date->modify('-1 second');
3438 $tend = $date->getTimestamp();
3440 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3441 // If parameter is true, return null.
3442 if ($param === true) {
3446 // If parameter is false, return an empty array.
3447 if ($param === false) {
3451 // If the parameter is a scalar value, enclose it in an array.
3452 if (!is_array($param)) {
3456 // No normalisation required.
3458 }, [$calendar->users
, $calendar->groups
, $calendar->courses
, $calendar->categories
]);
3463 $events = \core_calendar\local\api
::get_events(
3479 if ($proxy = $event->get_course_module()) {
3480 $cminfo = $proxy->get_proxied_instance();
3481 return $cminfo->uservisible
;
3484 if ($proxy = $event->get_category()) {
3485 $category = $proxy->get_proxied_instance();
3487 return $category->is_uservisible();
3496 'events' => $events,
3497 'cache' => new \core_calendar\external\
events_related_objects_cache($events),
3502 $calendar->set_viewmode($view);
3503 if ($view == "month" ||
$view == "monthblock" ||
$view == "mini" ||
$view == "minithree" ) {
3504 $month = new \core_calendar\external\
month_exporter($calendar, $type, $related);
3505 $month->set_includenavigation($includenavigation);
3506 $month->set_initialeventsloaded(!$skipevents);
3507 $month->set_showcoursefilter(($view == "month" ||
$view == "monthblock"));
3508 $data = $month->export($renderer);
3509 } else if ($view == "day") {
3510 $day = new \core_calendar\external\
calendar_day_exporter($calendar, $related);
3511 $data = $day->export($renderer);
3512 $data->viewingday
= true;
3513 $data->showviewselector
= true;
3514 $template = 'core_calendar/calendar_day';
3515 } else if ($view == "upcoming" ||
$view == "upcoming_mini") {
3516 $upcoming = new \core_calendar\external\
calendar_upcoming_exporter($calendar, $related);
3517 $data = $upcoming->export($renderer);
3519 if ($view == "upcoming") {
3520 $template = 'core_calendar/calendar_upcoming';
3521 $data->viewingupcoming
= true;
3522 $data->showviewselector
= true;
3523 } else if ($view == "upcoming_mini") {
3524 $template = 'core_calendar/calendar_upcoming_mini';
3528 return [$data, $template];
3532 * Request and render event form fragment.
3534 * @param array $args The fragment arguments.
3535 * @return string The rendered mform fragment.
3537 function calendar_output_fragment_event_form($args) {
3538 global $CFG, $OUTPUT, $USER;
3539 require_once($CFG->libdir
. '/grouplib.php');
3542 $eventid = isset($args['eventid']) ?
clean_param($args['eventid'], PARAM_INT
) : null;
3543 $starttime = isset($args['starttime']) ?
clean_param($args['starttime'], PARAM_INT
) : null;
3544 $courseid = (isset($args['courseid']) && $args['courseid'] != SITEID
) ?
clean_param($args['courseid'], PARAM_INT
) : null;
3545 $categoryid = isset($args['categoryid']) ?
clean_param($args['categoryid'], PARAM_INT
) : null;
3547 $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
3548 $context = \context_user
::instance($USER->id
);
3549 $editoroptions = \core_calendar\local\event\forms\create
::build_editor_options($context);
3550 $formoptions = ['editoroptions' => $editoroptions, 'courseid' => $courseid];
3554 parse_str(clean_param($args['formdata'], PARAM_TEXT
), $data);
3555 if (isset($data['description']['itemid'])) {
3556 $draftitemid = $data['description']['itemid'];
3561 $formoptions['starttime'] = $starttime;
3563 // Let's check first which event types user can add.
3564 $eventtypes = calendar_get_allowed_event_types($courseid);
3565 $formoptions['eventtypes'] = $eventtypes;
3567 if (is_null($eventid)) {
3568 if (!empty($courseid)) {
3569 $groupcoursedata = groups_get_course_data($courseid);
3570 $formoptions['groups'] = [];
3571 foreach ($groupcoursedata->groups
as $groupid => $groupdata) {
3572 $formoptions['groups'][$groupid] = $groupdata->name
;
3576 $mform = new \core_calendar\local\event\forms\
create(
3586 // If the user is on course context and is allowed to add course events set the event type default to course.
3587 if (!empty($courseid) && !empty($eventtypes['course'])) {
3588 $data['eventtype'] = 'course';
3589 $data['courseid'] = $courseid;
3590 $data['groupcourseid'] = $courseid;
3591 } else if (!empty($categoryid) && !empty($eventtypes['category'])) {
3592 $data['eventtype'] = 'category';
3593 $data['categoryid'] = $categoryid;
3594 } else if (!empty($groupcoursedata) && !empty($eventtypes['group'])) {
3595 $data['groupcourseid'] = $courseid;
3596 $data['groups'] = $groupcoursedata->groups
;
3598 $mform->set_data($data);
3600 $event = calendar_event
::load($eventid);
3602 if (!calendar_edit_event_allowed($event)) {
3603 print_error('nopermissiontoupdatecalendar');
3606 $mapper = new \core_calendar\local\event\mappers\
create_update_form_mapper();
3607 $eventdata = $mapper->from_legacy_event_to_data($event);
3608 $data = array_merge((array) $eventdata, $data);
3609 $event->count_repeats();
3610 $formoptions['event'] = $event;
3612 if (!empty($event->courseid
)) {
3613 $groupcoursedata = groups_get_course_data($event->courseid
);
3614 $formoptions['groups'] = [];
3615 foreach ($groupcoursedata->groups
as $groupid => $groupdata) {
3616 $formoptions['groups'][$groupid] = $groupdata->name
;
3620 $data['description']['text'] = file_prepare_draft_area(
3622 $event->context
->id
,
3624 'event_description',
3627 $data['description']['text']
3629 $data['description']['itemid'] = $draftitemid;
3631 $mform = new \core_calendar\local\event\forms\
update(
3640 $mform->set_data($data);
3642 // Check to see if this event is part of a subscription or import.
3643 // If so display a warning on edit.
3644 if (isset($event->subscriptionid
) && ($event->subscriptionid
!= null)) {
3645 $renderable = new \core\output\notification
(
3646 get_string('eventsubscriptioneditwarning', 'calendar'),
3647 \core\output\notification
::NOTIFY_INFO
3650 $html .= $OUTPUT->render($renderable);
3655 $mform->is_validated();
3658 $html .= $mform->render();
3663 * Calculate the timestamp from the supplied Gregorian Year, Month, and Day.
3665 * @param int $d The day
3666 * @param int $m The month
3667 * @param int $y The year
3668 * @param int $time The timestamp to use instead of a separate y/m/d.
3669 * @return int The timestamp
3671 function calendar_get_timestamp($d, $m, $y, $time = 0) {
3672 // If a day, month and year were passed then convert it to a timestamp. If these were passed
3673 // then we can assume the day, month and year are passed as Gregorian, as no where in core
3674 // should we be passing these values rather than the time.
3675 if (!empty($d) && !empty($m) && !empty($y)) {
3676 if (checkdate($m, $d, $y)) {
3677 $time = make_timestamp($y, $m, $d);
3681 } else if (empty($time)) {
3689 * Get the calendar footer options.
3691 * @param calendar_information $calendar The calendar information object.
3692 * @param array $options Display options for the footer. If an option is not set, a default value will be provided.
3694 * - showfullcalendarlink - bool - Whether to show the full calendar link or not. Defaults to false.
3696 * @return array The data for template and template name.
3698 function calendar_get_footer_options($calendar, array $options = []) {
3699 global $CFG, $USER, $PAGE;
3701 // Generate hash for iCal link.
3702 $authtoken = calendar_get_export_token($USER);
3704 $renderer = $PAGE->get_renderer('core_calendar');
3705 $footer = new \core_calendar\external\footer_options_exporter
($calendar, $USER->id
, $authtoken, $options);
3706 $data = $footer->export($renderer);
3707 $template = 'core_calendar/footer_options';
3709 return [$data, $template];
3713 * Get the list of potential calendar filter types as a type => name
3718 function calendar_get_filter_types() {
3728 return array_map(function($type) {
3730 'eventtype' => $type,
3731 'name' => get_string("eventtype{$type}", "calendar"),
3733 'key' => 'i/' . $type . 'event',
3734 'component' => 'core'
3740 * Check whether the specified event type is valid.
3742 * @param string $type
3745 function calendar_is_valid_eventtype($type) {
3753 return in_array($type, $validtypes);
3757 * Get event types the user can create event based on categories, courses and groups
3758 * the logged in user belongs to.
3760 * @param int|null $courseid The course id.
3761 * @return array The array of allowed types.
3763 function calendar_get_allowed_event_types(int $courseid = null) {
3764 global $DB, $CFG, $USER;
3774 if (!empty($courseid) && $courseid != SITEID
) {
3775 $context = \context_course
::instance($courseid);
3776 $types['user'] = has_capability('moodle/calendar:manageownentries', $context);
3777 calendar_internal_update_course_and_group_permission($courseid, $context, $types);
3780 if (has_capability('moodle/calendar:manageentries', \context_course
::instance(SITEID
))) {
3781 $types['site'] = true;
3784 if (has_capability('moodle/calendar:manageownentries', \context_system
::instance())) {
3785 $types['user'] = true;
3787 if (core_course_category
::has_manage_capability_on_any()) {
3788 $types['category'] = true;
3791 // We still don't know if the user can create group and course events, so iterate over the courses to find out
3792 // if the user has capabilities in one of the courses.
3793 if ($types['course'] == false ||
$types['group'] == false) {
3794 if ($CFG->calendar_adminseesall
&& has_capability('moodle/calendar:manageentries', context_system
::instance())) {
3795 $sql = "SELECT c.id, " . context_helper
::get_preload_record_columns_sql('ctx') . "
3797 JOIN {context} ctx ON ctx.contextlevel = ? AND ctx.instanceid = c.id
3799 SELECT DISTINCT courseid FROM {groups}
3801 $courseswithgroups = $DB->get_recordset_sql($sql, [CONTEXT_COURSE
]);
3802 foreach ($courseswithgroups as $course) {
3803 context_helper
::preload_from_record($course);
3804 $context = context_course
::instance($course->id
);
3806 if (has_capability('moodle/calendar:manageentries', $context)) {
3807 if (has_any_capability(['moodle/site:accessallgroups', 'moodle/calendar:managegroupentries'], $context)) {
3808 // The user can manage group entries or access any group.
3809 $types['group'] = true;
3810 $types['course'] = true;
3815 $courseswithgroups->close();
3817 if (false === $types['course']) {
3818 // Course is still not confirmed. There may have been no courses with a group in them.
3819 $ctxfields = context_helper
::get_preload_record_columns_sql('ctx');
3821 c.id, c.visible, {$ctxfields}
3823 JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
3825 'contextlevel' => CONTEXT_COURSE
,
3827 $courses = $DB->get_recordset_sql($sql, $params);
3828 foreach ($courses as $course) {
3829 context_helper
::preload_from_record($course);
3830 $context = context_course
::instance($course->id
);
3831 if (has_capability('moodle/calendar:manageentries', $context)) {
3832 $types['course'] = true;
3840 $courses = calendar_get_default_courses(null, 'id');
3841 if (empty($courses)) {
3845 $courseids = array_map(function($c) {
3849 // Check whether the user has access to create events within courses which have groups.
3850 list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED
);
3851 $sql = "SELECT c.id, " . context_helper
::get_preload_record_columns_sql('ctx') . "
3853 JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3855 AND c.id IN (SELECT DISTINCT courseid FROM {groups})";
3856 $params['contextlevel'] = CONTEXT_COURSE
;
3857 $courseswithgroups = $DB->get_recordset_sql($sql, $params);
3858 foreach ($courseswithgroups as $coursewithgroup) {
3859 context_helper
::preload_from_record($coursewithgroup);
3860 $context = context_course
::instance($coursewithgroup->id
);
3862 calendar_internal_update_course_and_group_permission($coursewithgroup->id
, $context, $types);
3864 // Okay, course and group event types are allowed, no need to keep the loop iteration.
3865 if ($types['course'] == true && $types['group'] == true) {
3869 $courseswithgroups->close();
3871 if (false === $types['course']) {
3872 list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED
);
3873 $contextsql = "SELECT c.id, " . context_helper
::get_preload_record_columns_sql('ctx') . "
3875 JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3877 $params['contextlevel'] = CONTEXT_COURSE
;
3878 $contextrecords = $DB->get_recordset_sql($contextsql, $params);
3879 foreach ($contextrecords as $course) {
3880 context_helper
::preload_from_record($course);
3881 $coursecontext = context_course
::instance($course->id
);
3882 if (has_capability('moodle/calendar:manageentries', $coursecontext)
3883 && ($courseid == $course->id ||
empty($courseid))) {
3884 $types['course'] = true;
3888 $contextrecords->close();
3898 * Given a course id, and context, updates the permission types array to add the 'course' or 'group'
3899 * permission if it is relevant for that course.
3901 * For efficiency, if they already have 'course' or 'group' then it skips checks.
3903 * Do not call this function directly, it is only for use by calendar_get_allowed_event_types().
3905 * @param int $courseid Course id
3906 * @param context $context Context for that course
3907 * @param array $types Current permissions
3909 function calendar_internal_update_course_and_group_permission(int $courseid, context
$context, array &$types) {
3910 if (!$types['course']) {
3911 // If they have manageentries permission on the course, then they can update this course.
3912 if (has_capability('moodle/calendar:manageentries', $context)) {
3913 $types['course'] = true;
3916 // To update group events they must have EITHER manageentries OR managegroupentries.
3917 if (!$types['group'] && (has_capability('moodle/calendar:manageentries', $context) ||
3918 has_capability('moodle/calendar:managegroupentries', $context))) {
3919 // And they also need for a group to exist on the course.
3920 $groups = groups_get_all_groups($courseid);
3921 if (!empty($groups)) {
3922 // And either accessallgroups, or belong to one of the groups.
3923 if (has_capability('moodle/site:accessallgroups', $context)) {
3924 $types['group'] = true;
3926 foreach ($groups as $group) {
3927 if (groups_is_member($group->id
)) {
3928 $types['group'] = true;
3938 * Get the auth token for exporting the given user calendar.
3939 * @param stdClass $user The user to export the calendar for
3941 * @return string The export token.
3943 function calendar_get_export_token(stdClass
$user): string {
3946 return sha1($user->id
. $DB->get_field('user', 'password', ['id' => $user->id
]) . $CFG->calendar_exportsalt
);
3950 * Get the list of URL parameters for calendar expport and import links.
3954 function calendar_get_export_import_link_params(): array {
3958 if ($courseid = $PAGE->url
->get_param('course')) {
3959 $params['course'] = $courseid;
3961 if ($categoryid = $PAGE->url
->get_param('category')) {
3962 $params['category'] = $categoryid;
3969 * Implements the inplace editable feature.
3971 * @param string $itemtype Type of the inplace editable element
3972 * @param int $itemid Id of the item to edit
3973 * @param int $newvalue New value of the item
3974 * @return \core\output\inplace_editable
3976 function calendar_inplace_editable(string $itemtype, int $itemid, int $newvalue): \core\output\inplace_editable
{
3979 if ($itemtype === 'refreshinterval') {
3981 $subscription = calendar_get_subscription($itemid);
3982 $context = calendar_get_calendar_context($subscription);
3983 \external_api
::validate_context($context);
3985 $updateresult = \core_calendar\output\refreshintervalcollection
::update($itemid, $newvalue);
3987 $refreshresults = calendar_update_subscription_events($itemid);
3988 \core\notification
::add($OUTPUT->render_from_template(
3989 'core_calendar/subscription_update_result',
3990 array_merge($refreshresults, [
3991 'subscriptionname' => s($subscription->name
),
3993 ), \core\notification
::INFO
);
3995 return $updateresult;
3998 \external_api
::validate_context(context_system
::instance());