2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * @package core_calendar
21 * @copyright 2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 if (!defined('MOODLE_INTERNAL')) {
27 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
31 * These are read by the administration component to provide default values
35 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
37 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
40 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
42 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
45 * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
47 define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
49 // This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
50 // Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
53 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
55 define('CALENDAR_DEFAULT_WEEKEND', 65);
58 * CALENDAR_URL - path to calendar's folder
60 define('CALENDAR_URL', $CFG->wwwroot
.'/calendar/');
63 * CALENDAR_TF_24 - Calendar time in 24 hours format
65 define('CALENDAR_TF_24', '%H:%M');
68 * CALENDAR_TF_12 - Calendar time in 12 hours format
70 define('CALENDAR_TF_12', '%I:%M %p');
73 * CALENDAR_EVENT_GLOBAL - Site calendar event types
74 * @deprecated since 3.8
76 define('CALENDAR_EVENT_GLOBAL', 1);
79 * CALENDAR_EVENT_SITE - Site calendar event types
81 define('CALENDAR_EVENT_SITE', 1);
84 * CALENDAR_EVENT_COURSE - Course calendar event types
86 define('CALENDAR_EVENT_COURSE', 2);
89 * CALENDAR_EVENT_GROUP - group calendar event types
91 define('CALENDAR_EVENT_GROUP', 4);
94 * CALENDAR_EVENT_USER - user calendar event types
96 define('CALENDAR_EVENT_USER', 8);
99 * CALENDAR_EVENT_COURSECAT - Course category calendar event types
101 define('CALENDAR_EVENT_COURSECAT', 16);
104 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
106 define('CALENDAR_IMPORT_FROM_FILE', 0);
109 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
111 define('CALENDAR_IMPORT_FROM_URL', 1);
114 * CALENDAR_IMPORT_EVENT_UPDATED_SKIPPED - imported event was skipped
116 define('CALENDAR_IMPORT_EVENT_SKIPPED', -1);
119 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
121 define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
124 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
126 define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
129 * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
131 define('CALENDAR_SUBSCRIPTION_UPDATE', 1);
134 * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
136 define('CALENDAR_SUBSCRIPTION_REMOVE', 2);
139 * CALENDAR_EVENT_USER_OVERRIDE_PRIORITY - Constant for the user override priority.
141 define('CALENDAR_EVENT_USER_OVERRIDE_PRIORITY', 0);
144 * CALENDAR_EVENT_TYPE_STANDARD - Standard events.
146 define('CALENDAR_EVENT_TYPE_STANDARD', 0);
149 * CALENDAR_EVENT_TYPE_ACTION - Action events.
151 define('CALENDAR_EVENT_TYPE_ACTION', 1);
154 * Manage calendar events.
156 * This class provides the required functionality in order to manage calendar events.
157 * It was introduced as part of Moodle 2.0 and was created in order to provide a
158 * better framework for dealing with calendar events in particular regard to file
159 * handling through the new file API.
161 * @package core_calendar
163 * @copyright 2009 Sam Hemelryk
164 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
166 * @property int $id The id within the event table
167 * @property string $name The name of the event
168 * @property string $description The description of the event
169 * @property int $format The format of the description FORMAT_?
170 * @property int $courseid The course the event is associated with (0 if none)
171 * @property int $groupid The group the event is associated with (0 if none)
172 * @property int $userid The user the event is associated with (0 if none)
173 * @property int $repeatid If this is a repeated event this will be set to the
175 * @property string $component If created by a plugin/component (other than module), the full frankenstyle name of a component
176 * @property string $modulename If added by a module this will be the module name
177 * @property int $instance If added by a module this will be the module instance
178 * @property string $eventtype The event type
179 * @property int $timestart The start time as a timestamp
180 * @property int $timeduration The duration of the event in seconds
181 * @property int $visible 1 if the event is visible
182 * @property int $uuid ?
183 * @property int $sequence ?
184 * @property int $timemodified The time last modified as a timestamp
186 class calendar_event
{
188 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
189 protected $properties = null;
191 /** @var string The converted event discription with file paths resolved.
192 * This gets populated when someone requests description for the first time */
193 protected $_description = null;
195 /** @var array The options to use with this description editor */
196 protected $editoroptions = array(
198 'forcehttps' => false,
201 'trusttext' => false);
203 /** @var object The context to use with the description editor */
204 protected $editorcontext = null;
207 * Instantiates a new event and optionally populates its properties with the data provided.
209 * @param \stdClass $data Optional. An object containing the properties to for
212 public function __construct($data = null) {
215 // First convert to object if it is not already (should either be object or assoc array).
216 if (!is_object($data)) {
217 $data = (object) $data;
220 $this->editoroptions
['maxbytes'] = $CFG->maxbytes
;
222 $data->eventrepeats
= 0;
224 if (empty($data->id
)) {
228 if (!empty($data->subscriptionid
)) {
229 $data->subscription
= calendar_get_subscription($data->subscriptionid
);
232 // Default to a user event.
233 if (empty($data->eventtype
)) {
234 $data->eventtype
= 'user';
237 // Default to the current user.
238 if (empty($data->userid
)) {
239 $data->userid
= $USER->id
;
242 if (!empty($data->timeduration
) && is_array($data->timeduration
)) {
243 $data->timeduration
= make_timestamp(
244 $data->timeduration
['year'], $data->timeduration
['month'], $data->timeduration
['day'],
245 $data->timeduration
['hour'], $data->timeduration
['minute']) - $data->timestart
;
248 if (!empty($data->description
) && is_array($data->description
)) {
249 $data->format
= $data->description
['format'];
250 $data->description
= $data->description
['text'];
251 } else if (empty($data->description
)) {
252 $data->description
= '';
253 $data->format
= editors_get_preferred_format();
256 // Ensure form is defaulted correctly.
257 if (empty($data->format
)) {
258 $data->format
= editors_get_preferred_format();
261 if (empty($data->component
)) {
262 $data->component
= null;
265 $this->properties
= $data;
271 * Attempts to call a set_$key method if one exists otherwise falls back
272 * to simply set the property.
274 * @param string $key property name
275 * @param mixed $value value of the property
277 public function __set($key, $value) {
278 if (method_exists($this, 'set_'.$key)) {
279 $this->{'set_'.$key}($value);
281 $this->properties
->{$key} = $value;
287 * Attempts to call a get_$key method to return the property and ralls over
288 * to return the raw property.
290 * @param string $key property name
291 * @return mixed property value
292 * @throws \coding_exception
294 public function __get($key) {
295 if (method_exists($this, 'get_'.$key)) {
296 return $this->{'get_'.$key}();
298 if (!property_exists($this->properties
, $key)) {
299 throw new \
coding_exception('Undefined property requested');
301 return $this->properties
->{$key};
305 * Magic isset method.
307 * PHP needs an isset magic method if you use the get magic method and
308 * still want empty calls to work.
310 * @param string $key $key property name
311 * @return bool|mixed property value, false if property is not exist
313 public function __isset($key) {
314 return !empty($this->properties
->{$key});
318 * Calculate the context value needed for an event.
320 * Event's type can be determine by the available value store in $data
321 * It is important to check for the existence of course/courseid to determine
323 * Default value is set to CONTEXT_USER
325 * @return \stdClass The context object.
327 protected function calculate_context() {
331 if (isset($this->properties
->categoryid
) && $this->properties
->categoryid
> 0) {
332 $context = \context_coursecat
::instance($this->properties
->categoryid
);
333 } else if (isset($this->properties
->courseid
) && $this->properties
->courseid
> 0) {
334 $context = \context_course
::instance($this->properties
->courseid
);
335 } else if (isset($this->properties
->course
) && $this->properties
->course
> 0) {
336 $context = \context_course
::instance($this->properties
->course
);
337 } else if (isset($this->properties
->groupid
) && $this->properties
->groupid
> 0) {
338 $group = $DB->get_record('groups', array('id' => $this->properties
->groupid
));
339 $context = \context_course
::instance($group->courseid
);
340 } else if (isset($this->properties
->userid
) && $this->properties
->userid
> 0
341 && $this->properties
->userid
== $USER->id
) {
342 $context = \context_user
::instance($this->properties
->userid
);
343 } else if (isset($this->properties
->userid
) && $this->properties
->userid
> 0
344 && $this->properties
->userid
!= $USER->id
&&
345 !empty($this->properties
->modulename
) &&
346 isset($this->properties
->instance
) && $this->properties
->instance
> 0) {
347 $cm = get_coursemodule_from_instance($this->properties
->modulename
, $this->properties
->instance
, 0,
349 $context = \context_course
::instance($cm->course
);
351 $context = \context_user
::instance($this->properties
->userid
);
358 * Returns the context for this event. The context is calculated
359 * the first time is is requested and then stored in a member
360 * variable to be returned each subsequent time.
362 * This is a magical getter function that will be called when
363 * ever the context property is accessed, e.g. $event->context.
367 protected function get_context() {
368 if (!isset($this->properties
->context
)) {
369 $this->properties
->context
= $this->calculate_context();
372 return $this->properties
->context
;
376 * Returns an array of editoroptions for this event.
378 * @return array event editor options
380 protected function get_editoroptions() {
381 return $this->editoroptions
;
385 * Returns an event description: Called by __get
386 * Please use $blah = $event->description;
388 * @return string event description
390 protected function get_description() {
393 require_once($CFG->libdir
. '/filelib.php');
395 if ($this->_description
=== null) {
396 // Check if we have already resolved the context for this event.
397 if ($this->editorcontext
=== null) {
398 // Switch on the event type to decide upon the appropriate context to use for this event.
399 $this->editorcontext
= $this->get_context();
400 if (!calendar_is_valid_eventtype($this->properties
->eventtype
)) {
401 return clean_text($this->properties
->description
, $this->properties
->format
);
405 // Work out the item id for the editor, if this is a repeated event
406 // then the files will be associated with the original.
407 if (!empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
408 $itemid = $this->properties
->repeatid
;
410 $itemid = $this->properties
->id
;
413 // Convert file paths in the description so that things display correctly.
414 $this->_description
= file_rewrite_pluginfile_urls($this->properties
->description
, 'pluginfile.php',
415 $this->editorcontext
->id
, 'calendar', 'event_description', $itemid);
416 // Clean the text so no nasties get through.
417 $this->_description
= clean_text($this->_description
, $this->properties
->format
);
420 // Finally return the description.
421 return $this->_description
;
425 * Return the number of repeat events there are in this events series.
427 * @return int number of event repeated
429 public function count_repeats() {
431 if (!empty($this->properties
->repeatid
)) {
432 $this->properties
->eventrepeats
= $DB->count_records('event',
433 array('repeatid' => $this->properties
->repeatid
));
434 // We don't want to count ourselves.
435 $this->properties
->eventrepeats
--;
437 return $this->properties
->eventrepeats
;
441 * Update or create an event within the database
443 * Pass in a object containing the event properties and this function will
444 * insert it into the database and deal with any associated files
446 * Capability checking should be performed if the user is directly manipulating the event
447 * and no other capability has been tested. However if the event is not being manipulated
448 * directly by the user and another capability has been checked for them to do this then
449 * capabilites should not be checked.
451 * For example if a user is editing an event in the calendar the check should be true,
452 * but if you are updating an event in an activities settings are changed then the calendar
453 * capabilites should not be checked.
455 * @see self::create()
456 * @see self::update()
458 * @param \stdClass $data object of event
459 * @param bool $checkcapability If Moodle should check the user can manage the calendar events for this call or not.
460 * @return bool event updated
462 public function update($data, $checkcapability=true) {
465 foreach ($data as $key => $value) {
466 $this->properties
->$key = $value;
469 $this->properties
->timemodified
= time();
470 $usingeditor = (!empty($this->properties
->description
) && is_array($this->properties
->description
));
472 // Prepare event data.
474 'context' => $this->get_context(),
475 'objectid' => $this->properties
->id
,
477 'repeatid' => empty($this->properties
->repeatid
) ?
0 : $this->properties
->repeatid
,
478 'timestart' => $this->properties
->timestart
,
479 'name' => $this->properties
->name
483 if (empty($this->properties
->id
) ||
$this->properties
->id
< 1) {
484 if ($checkcapability) {
485 if (!calendar_add_event_allowed($this->properties
)) {
486 print_error('nopermissiontoupdatecalendar');
491 switch ($this->properties
->eventtype
) {
493 $this->properties
->courseid
= 0;
494 $this->properties
->course
= 0;
495 $this->properties
->groupid
= 0;
496 $this->properties
->userid
= $USER->id
;
499 $this->properties
->courseid
= SITEID
;
500 $this->properties
->course
= SITEID
;
501 $this->properties
->groupid
= 0;
502 $this->properties
->userid
= $USER->id
;
505 $this->properties
->groupid
= 0;
506 $this->properties
->userid
= $USER->id
;
509 $this->properties
->groupid
= 0;
510 $this->properties
->category
= 0;
511 $this->properties
->userid
= $USER->id
;
514 $this->properties
->userid
= $USER->id
;
517 // We should NEVER get here, but just incase we do lets fail gracefully.
518 $usingeditor = false;
522 // If we are actually using the editor, we recalculate the context because some default values
523 // were set when calculate_context() was called from the constructor.
525 $this->properties
->context
= $this->calculate_context();
526 $this->editorcontext
= $this->get_context();
529 $editor = $this->properties
->description
;
530 $this->properties
->format
= $this->properties
->description
['format'];
531 $this->properties
->description
= $this->properties
->description
['text'];
534 // Insert the event into the database.
535 $this->properties
->id
= $DB->insert_record('event', $this->properties
);
538 $this->properties
->description
= file_save_draft_area_files(
540 $this->editorcontext
->id
,
543 $this->properties
->id
,
544 $this->editoroptions
,
546 $this->editoroptions
['forcehttps']);
547 $DB->set_field('event', 'description', $this->properties
->description
,
548 array('id' => $this->properties
->id
));
551 // Log the event entry.
552 $eventargs['objectid'] = $this->properties
->id
;
553 $eventargs['context'] = $this->get_context();
554 $event = \core\event\calendar_event_created
::create($eventargs);
557 $repeatedids = array();
559 if (!empty($this->properties
->repeat
)) {
560 $this->properties
->repeatid
= $this->properties
->id
;
561 $DB->set_field('event', 'repeatid', $this->properties
->repeatid
, array('id' => $this->properties
->id
));
563 $eventcopy = clone($this->properties
);
564 unset($eventcopy->id
);
566 $timestart = new \
DateTime('@' . $eventcopy->timestart
);
567 $timestart->setTimezone(\core_date
::get_user_timezone_object());
569 for ($i = 1; $i < $eventcopy->repeats
; $i++
) {
571 $timestart->add(new \
DateInterval('P7D'));
572 $eventcopy->timestart
= $timestart->getTimestamp();
574 // Get the event id for the log record.
575 $eventcopyid = $DB->insert_record('event', $eventcopy);
577 // If the context has been set delete all associated files.
579 $fs = get_file_storage();
580 $files = $fs->get_area_files($this->editorcontext
->id
, 'calendar', 'event_description',
581 $this->properties
->id
);
582 foreach ($files as $file) {
583 $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
587 $repeatedids[] = $eventcopyid;
590 $eventargs['objectid'] = $eventcopyid;
591 $eventargs['other']['timestart'] = $eventcopy->timestart
;
592 $event = \core\event\calendar_event_created
::create($eventargs);
600 if ($checkcapability) {
601 if (!calendar_edit_event_allowed($this->properties
)) {
602 print_error('nopermissiontoupdatecalendar');
607 if ($this->editorcontext
!== null) {
608 $this->properties
->description
= file_save_draft_area_files(
609 $this->properties
->description
['itemid'],
610 $this->editorcontext
->id
,
613 $this->properties
->id
,
614 $this->editoroptions
,
615 $this->properties
->description
['text'],
616 $this->editoroptions
['forcehttps']);
618 $this->properties
->format
= $this->properties
->description
['format'];
619 $this->properties
->description
= $this->properties
->description
['text'];
623 $event = $DB->get_record('event', array('id' => $this->properties
->id
));
625 $updaterepeated = (!empty($this->properties
->repeatid
) && !empty($this->properties
->repeateditall
));
627 if ($updaterepeated) {
636 // Note: Group and course id may not be set. If not, keep their current values.
638 $this->properties
->name
,
639 $this->properties
->description
,
640 $this->properties
->timeduration
,
642 isset($this->properties
->groupid
) ?
$this->properties
->groupid
: $event->groupid
,
643 isset($this->properties
->courseid
) ?
$this->properties
->courseid
: $event->courseid
,
646 // Note: Only update start date, if it was changed by the user.
647 if ($this->properties
->timestart
!= $event->timestart
) {
648 $timestartoffset = $this->properties
->timestart
- $event->timestart
;
649 $sqlset .= ', timestart = timestart + ?';
650 $params[] = $timestartoffset;
653 // Note: Only update location, if it was changed by the user.
654 $updatelocation = (!empty($this->properties
->location
) && $this->properties
->location
!== $event->location
);
655 if ($updatelocation) {
656 $sqlset .= ', location = ?';
657 $params[] = $this->properties
->location
;
661 $sql = "UPDATE {event}
665 $params[] = $event->repeatid
;
666 $DB->execute($sql, $params);
668 // Trigger an update event for each of the calendar event.
669 $events = $DB->get_records('event', array('repeatid' => $event->repeatid
), '', '*');
670 foreach ($events as $calendarevent) {
671 $eventargs['objectid'] = $calendarevent->id
;
672 $eventargs['other']['timestart'] = $calendarevent->timestart
;
673 $event = \core\event\calendar_event_updated
::create($eventargs);
674 $event->add_record_snapshot('event', $calendarevent);
678 $DB->update_record('event', $this->properties
);
679 $event = self
::load($this->properties
->id
);
680 $this->properties
= $event->properties();
682 // Trigger an update event.
683 $event = \core\event\calendar_event_updated
::create($eventargs);
684 $event->add_record_snapshot('event', $this->properties
);
693 * Deletes an event and if selected an repeated events in the same series
695 * This function deletes an event, any associated events if $deleterepeated=true,
696 * and cleans up any files associated with the events.
698 * @see self::delete()
700 * @param bool $deleterepeated delete event repeatedly
701 * @return bool succession of deleting event
703 public function delete($deleterepeated = false) {
706 // If $this->properties->id is not set then something is wrong.
707 if (empty($this->properties
->id
)) {
708 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER
);
711 $calevent = $DB->get_record('event', array('id' => $this->properties
->id
), '*', MUST_EXIST
);
713 $DB->delete_records('event', array('id' => $this->properties
->id
));
715 // Trigger an event for the delete action.
717 'context' => $this->get_context(),
718 'objectid' => $this->properties
->id
,
720 'repeatid' => empty($this->properties
->repeatid
) ?
0 : $this->properties
->repeatid
,
721 'timestart' => $this->properties
->timestart
,
722 'name' => $this->properties
->name
724 $event = \core\event\calendar_event_deleted
::create($eventargs);
725 $event->add_record_snapshot('event', $calevent);
728 // If we are deleting parent of a repeated event series, promote the next event in the series as parent.
729 if (($this->properties
->id
== $this->properties
->repeatid
) && !$deleterepeated) {
730 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC",
731 array($this->properties
->id
), IGNORE_MULTIPLE
);
732 if (!empty($newparent)) {
733 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?",
734 array($newparent, $this->properties
->id
));
735 // Get all records where the repeatid is the same as the event being removed.
736 $events = $DB->get_records('event', array('repeatid' => $newparent));
737 // For each of the returned events trigger an update event.
738 foreach ($events as $calendarevent) {
739 // Trigger an event for the update.
740 $eventargs['objectid'] = $calendarevent->id
;
741 $eventargs['other']['timestart'] = $calendarevent->timestart
;
742 $event = \core\event\calendar_event_updated
::create($eventargs);
743 $event->add_record_snapshot('event', $calendarevent);
749 // If the editor context hasn't already been set then set it now.
750 if ($this->editorcontext
=== null) {
751 $this->editorcontext
= $this->get_context();
754 // If the context has been set delete all associated files.
755 if ($this->editorcontext
!== null) {
756 $fs = get_file_storage();
757 $files = $fs->get_area_files($this->editorcontext
->id
, 'calendar', 'event_description', $this->properties
->id
);
758 foreach ($files as $file) {
763 // If we need to delete repeated events then we will fetch them all and delete one by one.
764 if ($deleterepeated && !empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
765 // Get all records where the repeatid is the same as the event being removed.
766 $events = $DB->get_records('event', array('repeatid' => $this->properties
->repeatid
));
767 // For each of the returned events populate an event object and call delete.
768 // make sure the arg passed is false as we are already deleting all repeats.
769 foreach ($events as $event) {
770 $event = new calendar_event($event);
771 $event->delete(false);
779 * Fetch all event properties.
781 * This function returns all of the events properties as an object and optionally
782 * can prepare an editor for the description field at the same time. This is
783 * designed to work when the properties are going to be used to set the default
784 * values of a moodle forms form.
786 * @param bool $prepareeditor If set to true a editor is prepared for use with
787 * the mforms editor element. (for description)
788 * @return \stdClass Object containing event properties
790 public function properties($prepareeditor = false) {
793 // First take a copy of the properties. We don't want to actually change the
794 // properties or we'd forever be converting back and forwards between an
795 // editor formatted description and not.
796 $properties = clone($this->properties
);
797 // Clean the description here.
798 $properties->description
= clean_text($properties->description
, $properties->format
);
800 // If set to true we need to prepare the properties for use with an editor
801 // and prepare the file area.
802 if ($prepareeditor) {
804 // We may or may not have a property id. If we do then we need to work
805 // out the context so we can copy the existing files to the draft area.
806 if (!empty($properties->id
)) {
808 if ($properties->eventtype
=== 'site') {
810 $this->editorcontext
= $this->get_context();
811 } else if ($properties->eventtype
=== 'user') {
813 $this->editorcontext
= $this->get_context();
814 } else if ($properties->eventtype
=== 'group' ||
$properties->eventtype
=== 'course') {
815 // First check the course is valid.
816 $course = $DB->get_record('course', array('id' => $properties->courseid
));
818 print_error('invalidcourse');
821 $this->editorcontext
= $this->get_context();
822 // We have a course and are within the course context so we had
823 // better use the courses max bytes value.
824 $this->editoroptions
['maxbytes'] = $course->maxbytes
;
825 } else if ($properties->eventtype
=== 'category') {
826 // First check the course is valid.
827 \core_course_category
::get($properties->categoryid
, MUST_EXIST
, true);
829 $this->editorcontext
= $this->get_context();
831 // If we get here we have a custom event type as used by some
832 // modules. In this case the event will have been added by
833 // code and we won't need the editor.
834 $this->editoroptions
['maxbytes'] = 0;
835 $this->editoroptions
['maxfiles'] = 0;
838 if (empty($this->editorcontext
) ||
empty($this->editorcontext
->id
)) {
841 // Get the context id that is what we really want.
842 $contextid = $this->editorcontext
->id
;
846 // If we get here then this is a new event in which case we don't need a
847 // context as there is no existing files to copy to the draft area.
851 // If the contextid === false we don't support files so no preparing
853 if ($contextid !== false) {
854 // Just encase it has already been submitted.
855 $draftiddescription = file_get_submitted_draft_itemid('description');
856 // Prepare the draft area, this copies existing files to the draft area as well.
857 $properties->description
= file_prepare_draft_area($draftiddescription, $contextid, 'calendar',
858 'event_description', $properties->id
, $this->editoroptions
, $properties->description
);
860 $draftiddescription = 0;
863 // Structure the description field as the editor requires.
864 $properties->description
= array('text' => $properties->description
, 'format' => $properties->format
,
865 'itemid' => $draftiddescription);
868 // Finally return the properties.
873 * Toggles the visibility of an event
875 * @param null|bool $force If it is left null the events visibility is flipped,
876 * If it is false the event is made hidden, if it is true it
878 * @return bool if event is successfully updated, toggle will be visible
880 public function toggle_visibility($force = null) {
883 // Set visible to the default if it is not already set.
884 if (empty($this->properties
->visible
)) {
885 $this->properties
->visible
= 1;
888 if ($force === true ||
($force !== false && $this->properties
->visible
== 0)) {
889 // Make this event visible.
890 $this->properties
->visible
= 1;
892 // Make this event hidden.
893 $this->properties
->visible
= 0;
896 // Update the database to reflect this change.
897 $success = $DB->set_field('event', 'visible', $this->properties
->visible
, array('id' => $this->properties
->id
));
898 $calendarevent = $DB->get_record('event', array('id' => $this->properties
->id
), '*', MUST_EXIST
);
900 // Prepare event data.
902 'context' => $this->get_context(),
903 'objectid' => $this->properties
->id
,
905 'repeatid' => empty($this->properties
->repeatid
) ?
0 : $this->properties
->repeatid
,
906 'timestart' => $this->properties
->timestart
,
907 'name' => $this->properties
->name
910 $event = \core\event\calendar_event_updated
::create($eventargs);
911 $event->add_record_snapshot('event', $calendarevent);
918 * Returns an event object when provided with an event id.
920 * This function makes use of MUST_EXIST, if the event id passed in is invalid
921 * it will result in an exception being thrown.
923 * @param int|object $param event object or event id
924 * @return calendar_event
926 public static function load($param) {
928 if (is_object($param)) {
929 $event = new calendar_event($param);
931 $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST
);
932 $event = new calendar_event($event);
938 * Creates a new event and returns an event object.
940 * Capability checking should be performed if the user is directly creating the event
941 * and no other capability has been tested. However if the event is not being created
942 * directly by the user and another capability has been checked for them to do this then
943 * capabilites should not be checked.
945 * For example if a user is creating an event in the calendar the check should be true,
946 * but if you are creating an event in an activity when it is created then the calendar
947 * capabilites should not be checked.
949 * @param \stdClass|array $properties An object containing event properties
950 * @param bool $checkcapability If Moodle should check the user can manage the calendar events for this call or not.
951 * @throws \coding_exception
953 * @return calendar_event|bool The event object or false if it failed
955 public static function create($properties, $checkcapability = true) {
956 if (is_array($properties)) {
957 $properties = (object)$properties;
959 if (!is_object($properties)) {
960 throw new \
coding_exception('When creating an event properties should be either an object or an assoc array');
962 $event = new calendar_event($properties);
963 if ($event->update($properties, $checkcapability)) {
971 * Format the text using the external API.
973 * This function should we used when text formatting is required in external functions.
975 * @return array an array containing the text formatted and the text format
977 public function format_external_text() {
979 if ($this->editorcontext
=== null) {
980 // Switch on the event type to decide upon the appropriate context to use for this event.
981 $this->editorcontext
= $this->get_context();
983 if (!calendar_is_valid_eventtype($this->properties
->eventtype
)) {
984 // We don't have a context here, do a normal format_text.
985 return external_format_text($this->properties
->description
, $this->properties
->format
, $this->editorcontext
->id
);
989 // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
990 if (!empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
991 $itemid = $this->properties
->repeatid
;
993 $itemid = $this->properties
->id
;
996 return external_format_text($this->properties
->description
, $this->properties
->format
, $this->editorcontext
->id
,
997 'calendar', 'event_description', $itemid);
1002 * Calendar information class
1004 * This class is used simply to organise the information pertaining to a calendar
1005 * and is used primarily to make information easily available.
1007 * @package core_calendar
1008 * @category calendar
1009 * @copyright 2010 Sam Hemelryk
1010 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1012 class calendar_information
{
1015 * @var int The timestamp
1017 * Rather than setting the day, month and year we will set a timestamp which will be able
1018 * to be used by multiple calendars.
1022 /** @var int A course id */
1023 public $courseid = null;
1025 /** @var array An array of categories */
1026 public $categories = array();
1028 /** @var int The current category */
1029 public $categoryid = null;
1031 /** @var array An array of courses */
1032 public $courses = array();
1034 /** @var array An array of groups */
1035 public $groups = array();
1037 /** @var array An array of users */
1038 public $users = array();
1040 /** @var context The anticipated context that the calendar is viewed in */
1041 public $context = null;
1044 * Creates a new instance
1046 * @param int $day the number of the day
1047 * @param int $month the number of the month
1048 * @param int $year the number of the year
1049 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
1050 * and $calyear to support multiple calendars
1052 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
1053 // If a day, month and year were passed then convert it to a timestamp. If these were passed
1054 // then we can assume the day, month and year are passed as Gregorian, as no where in core
1055 // should we be passing these values rather than the time. This is done for BC.
1056 if (!empty($day) ||
!empty($month) ||
!empty($year)) {
1057 $date = usergetdate(time());
1059 $day = $date['mday'];
1061 if (empty($month)) {
1062 $month = $date['mon'];
1065 $year = $date['year'];
1067 if (checkdate($month, $day, $year)) {
1068 $time = make_timestamp($year, $month, $day);
1074 $this->set_time($time);
1078 * Creates and set up a instance.
1080 * @param int $time the unixtimestamp representing the date we want to view.
1081 * @param int $courseid The ID of the course the user wishes to view.
1082 * @param int $categoryid The ID of the category the user wishes to view
1083 * If a courseid is specified, this value is ignored.
1084 * @return calendar_information
1086 public static function create($time, int $courseid, int $categoryid = null) : calendar_information
{
1087 $calendar = new static(0, 0, 0, $time);
1088 if ($courseid != SITEID
&& !empty($courseid)) {
1089 // Course ID must be valid and existing.
1090 $course = get_course($courseid);
1091 $calendar->context
= context_course
::instance($course->id
);
1093 if (!$course->visible
&& !is_role_switched($course->id
)) {
1094 require_capability('moodle/course:viewhiddencourses', $calendar->context
);
1097 $courses = [$course->id
=> $course];
1098 $category = (\core_course_category
::get($course->category
, MUST_EXIST
, true))->get_db_record();
1099 } else if (!empty($categoryid)) {
1100 $course = get_site();
1101 $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1103 // Filter available courses to those within this category or it's children.
1104 $ids = [$categoryid];
1105 $category = \core_course_category
::get($categoryid);
1106 $ids = array_merge($ids, array_keys($category->get_children()));
1107 $courses = array_filter($courses, function($course) use ($ids) {
1108 return array_search($course->category
, $ids) !== false;
1110 $category = $category->get_db_record();
1112 $calendar->context
= context_coursecat
::instance($categoryid);
1114 $course = get_site();
1115 $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1118 $calendar->context
= context_system
::instance();
1121 $calendar->set_sources($course, $courses, $category);
1127 * Set the time period of this instance.
1129 * @param int $time the unixtimestamp representing the date we want to view.
1132 public function set_time($time = null) {
1134 $this->time
= time();
1136 $this->time
= $time;
1143 * Initialize calendar information
1146 * @param stdClass $course object
1147 * @param array $coursestoload An array of courses [$course->id => $course]
1148 * @param bool $ignorefilters options to use filter
1150 public function prepare_for_view(stdClass
$course, array $coursestoload, $ignorefilters = false) {
1151 debugging('The prepare_for_view() function has been deprecated. Please update your code to use set_sources()',
1153 $this->set_sources($course, $coursestoload);
1157 * Set the sources for events within the calendar.
1159 * If no category is provided, then the category path for the current
1160 * course will be used.
1162 * @param stdClass $course The current course being viewed.
1163 * @param stdClass[] $courses The list of all courses currently accessible.
1164 * @param stdClass $category The current category to show.
1166 public function set_sources(stdClass
$course, array $courses, stdClass
$category = null) {
1169 // A cousre must always be specified.
1170 $this->course
= $course;
1171 $this->courseid
= $course->id
;
1173 list($courseids, $group, $user) = calendar_set_filters($courses);
1174 $this->courses
= $courseids;
1175 $this->groups
= $group;
1176 $this->users
= $user;
1178 // Do not show category events by default.
1179 $this->categoryid
= null;
1180 $this->categories
= null;
1182 // Determine the correct category information to show.
1183 // When called with a course, the category of that course is usually included too.
1184 // When a category was specifically requested, it should be requested with the site id.
1185 if (SITEID
!== $this->courseid
) {
1186 // A specific course was requested.
1187 // Fetch the category that this course is in, along with all parents.
1188 // Do not include child categories of this category, as the user many not have enrolments in those siblings or children.
1189 $category = \core_course_category
::get($course->category
, MUST_EXIST
, true);
1190 $this->categoryid
= $category->id
;
1192 $this->categories
= $category->get_parents();
1193 $this->categories
[] = $category->id
;
1194 } else if (null !== $category && $category->id
> 0) {
1195 // A specific category was requested.
1196 // Fetch all parents of this category, along with all children too.
1197 $category = \core_course_category
::get($category->id
);
1198 $this->categoryid
= $category->id
;
1200 // Build the category list.
1201 // This includes the current category.
1202 $this->categories
= $category->get_parents();
1203 $this->categories
[] = $category->id
;
1204 $this->categories
= array_merge($this->categories
, $category->get_all_children_ids());
1205 } else if (SITEID
=== $this->courseid
) {
1206 // The site was requested.
1207 // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
1209 // Grab the list of categories that this user has courses in.
1210 $coursecategories = array_flip(array_map(function($course) {
1211 return $course->category
;
1214 $calcatcache = cache
::make('core', 'calendar_categories');
1215 $this->categories
= $calcatcache->get('site');
1216 if ($this->categories
=== false) {
1217 // Use the category id as the key in the following array. That way we do not have to remove duplicates.
1219 foreach (\core_course_category
::get_all() as $category) {
1220 if (isset($coursecategories[$category->id
]) ||
1221 has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
1222 // If the user has access to a course in this category or can manage the category,
1223 // then they can see all parent categories too.
1224 $categories[$category->id
] = true;
1225 foreach ($category->get_parents() as $catid) {
1226 $categories[$catid] = true;
1230 $this->categories
= array_keys($categories);
1231 $calcatcache->set('site', $this->categories
);
1237 * Ensures the date for the calendar is correct and either sets it to now
1238 * or throws a moodle_exception if not
1240 * @param bool $defaultonow use current time
1241 * @throws moodle_exception
1242 * @return bool validation of checkdate
1244 public function checkdate($defaultonow = true) {
1245 if (!checkdate($this->month
, $this->day
, $this->year
)) {
1247 $now = usergetdate(time());
1248 $this->day
= intval($now['mday']);
1249 $this->month
= intval($now['mon']);
1250 $this->year
= intval($now['year']);
1253 throw new moodle_exception('invaliddate');
1260 * Gets todays timestamp for the calendar
1262 * @return int today timestamp
1264 public function timestamp_today() {
1268 * Gets tomorrows timestamp for the calendar
1270 * @return int tomorrow timestamp
1272 public function timestamp_tomorrow() {
1273 return strtotime('+1 day', $this->time
);
1276 * Adds the pretend blocks for the calendar
1278 * @param core_calendar_renderer $renderer
1279 * @param bool $showfilters display filters, false is set as default
1280 * @param string|null $view preference view options (eg: day, month, upcoming)
1282 public function add_sidecalendar_blocks(core_calendar_renderer
$renderer, $showfilters=false, $view=null) {
1284 $filters = new block_contents();
1285 $filters->content
= $renderer->event_filter();
1286 $filters->footer
= '';
1287 $filters->title
= get_string('eventskey', 'calendar');
1288 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT
);
1290 $block = new block_contents
;
1291 $block->content
= $renderer->fake_block_threemonths($this);
1292 $block->footer
= '';
1293 $block->title
= get_string('monthlyview', 'calendar');
1294 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT
);
1299 * Get calendar events.
1301 * @param int $tstart Start time of time range for events
1302 * @param int $tend End time of time range for events
1303 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
1304 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
1305 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
1306 * @param boolean $withduration whether only events starting within time range selected
1307 * or events in progress/already started selected as well
1308 * @param boolean $ignorehidden whether to select only visible events or all events
1309 * @param array|int|boolean $categories array of categories, category id or boolean for all/no course events
1310 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
1312 function calendar_get_events($tstart, $tend, $users, $groups, $courses,
1313 $withduration = true, $ignorehidden = true, $categories = []) {
1319 if (empty($users) && empty($groups) && empty($courses) && empty($categories)) {
1323 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
1324 // Events from a number of users
1325 if(!empty($whereclause)) $whereclause .= ' OR';
1326 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED
);
1327 $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)";
1328 $params = array_merge($params, $inparamsusers);
1329 } else if($users === true) {
1330 // Events from ALL users
1331 if(!empty($whereclause)) $whereclause .= ' OR';
1332 $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)';
1333 } else if($users === false) {
1334 // No user at all, do nothing
1337 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
1338 // Events from a number of groups
1339 if(!empty($whereclause)) $whereclause .= ' OR';
1340 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED
);
1341 $whereclause .= " e.groupid $insqlgroups ";
1342 $params = array_merge($params, $inparamsgroups);
1343 } else if($groups === true) {
1344 // Events from ALL groups
1345 if(!empty($whereclause)) $whereclause .= ' OR ';
1346 $whereclause .= ' e.groupid != 0';
1348 // boolean false (no groups at all): we don't need to do anything
1350 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
1351 if(!empty($whereclause)) $whereclause .= ' OR';
1352 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED
);
1353 $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
1354 $params = array_merge($params, $inparamscourses);
1355 } else if ($courses === true) {
1356 // Events from ALL courses
1357 if(!empty($whereclause)) $whereclause .= ' OR';
1358 $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
1361 if ((is_array($categories) && !empty($categories)) ||
is_numeric($categories)) {
1362 if (!empty($whereclause)) {
1363 $whereclause .= ' OR';
1365 list($insqlcategories, $inparamscategories) = $DB->get_in_or_equal($categories, SQL_PARAMS_NAMED
);
1366 $whereclause .= " (e.groupid = 0 AND e.courseid = 0 AND e.categoryid $insqlcategories)";
1367 $params = array_merge($params, $inparamscategories);
1368 } else if ($categories === true) {
1369 // Events from ALL categories.
1370 if (!empty($whereclause)) {
1371 $whereclause .= ' OR';
1373 $whereclause .= ' (e.groupid = 0 AND e.courseid = 0 AND e.categoryid != 0)';
1376 // Security check: if, by now, we have NOTHING in $whereclause, then it means
1377 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
1378 // events no matter what. Allowing the code to proceed might return a completely
1379 // valid query with only time constraints, thus selecting ALL events in that time frame!
1380 if(empty($whereclause)) {
1385 $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1388 $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1390 if(!empty($whereclause)) {
1391 // We have additional constraints
1392 $whereclause = $timeclause.' AND ('.$whereclause.')';
1395 // Just basic time filtering
1396 $whereclause = $timeclause;
1399 if ($ignorehidden) {
1400 $whereclause .= ' AND e.visible = 1';
1405 LEFT JOIN {modules} m ON e.modulename = m.name
1406 -- Non visible modules will have a value of 0.
1407 WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
1408 ORDER BY e.timestart";
1409 $events = $DB->get_records_sql($sql, $params);
1411 if ($events === false) {
1418 * Return the days of the week.
1420 * @return array array of days
1422 function calendar_get_days() {
1423 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1424 return $calendartype->get_weekdays();
1428 * Get the subscription from a given id.
1431 * @param int $id id of the subscription
1432 * @return stdClass Subscription record from DB
1433 * @throws moodle_exception for an invalid id
1435 function calendar_get_subscription($id) {
1438 $cache = \cache
::make('core', 'calendar_subscriptions');
1439 $subscription = $cache->get($id);
1440 if (empty($subscription)) {
1441 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST
);
1442 $cache->set($id, $subscription);
1445 return $subscription;
1449 * Gets the first day of the week.
1451 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
1455 function calendar_get_starting_weekday() {
1456 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1457 return $calendartype->get_starting_weekday();
1461 * Get a HTML link to a course.
1463 * @param int|stdClass $course the course id or course object
1464 * @return string a link to the course (as HTML); empty if the course id is invalid
1466 function calendar_get_courselink($course) {
1471 if (!is_object($course)) {
1472 $course = calendar_get_course_cached($coursecache, $course);
1474 $context = \context_course
::instance($course->id
);
1475 $fullname = format_string($course->fullname
, true, array('context' => $context));
1476 $url = new \
moodle_url('/course/view.php', array('id' => $course->id
));
1477 $link = \html_writer
::link($url, $fullname);
1483 * Get current module cache.
1485 * Only use this method if you do not know courseid. Otherwise use:
1486 * get_fast_modinfo($courseid)->instances[$modulename][$instance]
1488 * @param array $modulecache in memory module cache
1489 * @param string $modulename name of the module
1490 * @param int $instance module instance number
1491 * @return stdClass|bool $module information
1493 function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
1494 if (!isset($modulecache[$modulename . '_' . $instance])) {
1495 $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
1498 return $modulecache[$modulename . '_' . $instance];
1502 * Get current course cache.
1504 * @param array $coursecache list of course cache
1505 * @param int $courseid id of the course
1506 * @return stdClass $coursecache[$courseid] return the specific course cache
1508 function calendar_get_course_cached(&$coursecache, $courseid) {
1509 if (!isset($coursecache[$courseid])) {
1510 $coursecache[$courseid] = get_course($courseid);
1512 return $coursecache[$courseid];
1516 * Get group from groupid for calendar display
1518 * @param int $groupid
1519 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1521 function calendar_get_group_cached($groupid) {
1522 static $groupscache = array();
1523 if (!isset($groupscache[$groupid])) {
1524 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1526 return $groupscache[$groupid];
1530 * Add calendar event metadata
1532 * @deprecated since 3.9
1534 * @param stdClass $event event info
1535 * @return stdClass $event metadata
1537 function calendar_add_event_metadata($event) {
1538 debugging('This function is no longer used', DEBUG_DEVELOPER
);
1539 global $CFG, $OUTPUT;
1541 // Support multilang in event->name.
1542 $event->name
= format_string($event->name
, true);
1544 if (!empty($event->modulename
)) { // Activity event.
1545 // The module name is set. I will assume that it has to be displayed, and
1546 // also that it is an automatically-generated event. And of course that the
1547 // instace id and modulename are set correctly.
1548 $instances = get_fast_modinfo($event->courseid
)->get_instances_of($event->modulename
);
1549 if (!array_key_exists($event->instance
, $instances)) {
1552 $module = $instances[$event->instance
];
1554 $modulename = $module->get_module_type_name(false);
1555 if (get_string_manager()->string_exists($event->eventtype
, $event->modulename
)) {
1556 // Will be used as alt text if the event icon.
1557 $eventtype = get_string($event->eventtype
, $event->modulename
);
1562 $event->icon
= '<img src="' . s($module->get_icon_url()) . '" alt="' . s($eventtype) .
1563 '" title="' . s($modulename) . '" class="icon" />';
1564 $event->referer
= html_writer
::link($module->url
, $event->name
);
1565 $event->courselink
= calendar_get_courselink($module->get_course());
1566 $event->cmid
= $module->id
;
1567 } else if ($event->courseid
== SITEID
) { // Site event.
1568 $event->icon
= '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
1569 get_string('siteevent', 'calendar') . '" class="icon" />';
1570 $event->cssclass
= 'calendar_event_site';
1571 } else if ($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) { // Course event.
1572 $event->icon
= '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
1573 get_string('courseevent', 'calendar') . '" class="icon" />';
1574 $event->courselink
= calendar_get_courselink($event->courseid
);
1575 $event->cssclass
= 'calendar_event_course';
1576 } else if ($event->groupid
) { // Group event.
1577 if ($group = calendar_get_group_cached($event->groupid
)) {
1578 $groupname = format_string($group->name
, true, \context_course
::instance($group->courseid
));
1582 $event->icon
= \html_writer
::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
1583 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
1584 $event->courselink
= calendar_get_courselink($event->courseid
) . ', ' . $groupname;
1585 $event->cssclass
= 'calendar_event_group';
1586 } else if ($event->userid
) { // User event.
1587 $event->icon
= '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
1588 get_string('userevent', 'calendar') . '" class="icon" />';
1589 $event->cssclass
= 'calendar_event_user';
1596 * Get calendar events by id.
1599 * @param array $eventids list of event ids
1600 * @return array Array of event entries, empty array if nothing found
1602 function calendar_get_events_by_id($eventids) {
1605 if (!is_array($eventids) ||
empty($eventids)) {
1609 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
1610 $wheresql = "id $wheresql";
1612 return $DB->get_records_select('event', $wheresql, $params);
1616 * Get control options for calendar.
1618 * @param string $type of calendar
1619 * @param array $data calendar information
1620 * @return string $content return available control for the calender in html
1622 function calendar_top_controls($type, $data) {
1623 global $PAGE, $OUTPUT;
1625 // Get the calendar type we are using.
1626 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1630 // Ensure course id passed if relevant.
1632 if (!empty($data['id'])) {
1633 $courseid = '&course=' . $data['id'];
1636 // If we are passing a month and year then we need to convert this to a timestamp to
1637 // support multiple calendars. No where in core should these be passed, this logic
1638 // here is for third party plugins that may use this function.
1639 if (!empty($data['m']) && !empty($date['y'])) {
1640 if (!isset($data['d'])) {
1643 if (!checkdate($data['m'], $data['d'], $data['y'])) {
1646 $time = make_timestamp($data['y'], $data['m'], $data['d']);
1648 } else if (!empty($data['time'])) {
1649 $time = $data['time'];
1654 // Get the date for the calendar type.
1655 $date = $calendartype->timestamp_to_date_array($time);
1657 $urlbase = $PAGE->url
;
1659 // We need to get the previous and next months in certain cases.
1660 if ($type == 'frontpage' ||
$type == 'course' ||
$type == 'month') {
1661 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1662 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
1663 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
1664 $prevmonthtime['hour'], $prevmonthtime['minute']);
1666 $nextmonth = calendar_add_month($date['mon'], $date['year']);
1667 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
1668 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
1669 $nextmonthtime['hour'], $nextmonthtime['minute']);
1674 $prevlink = calendar_get_link_previous(get_string('monthprev', 'calendar'), $urlbase, false, false, false,
1675 true, $prevmonthtime);
1676 $nextlink = calendar_get_link_next(get_string('monthnext', 'calendar'), $urlbase, false, false, false, true,
1678 $calendarlink = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', array('view' => 'month')),
1679 false, false, false, $time);
1681 if (!empty($data['id'])) {
1682 $calendarlink->param('course', $data['id']);
1687 $content .= \html_writer
::start_tag('div', array('class' => 'calendar-controls'));
1688 $content .= $prevlink . '<span class="hide"> | </span>';
1689 $content .= \html_writer
::tag('span', \html_writer
::link($calendarlink,
1690 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1691 ), array('class' => 'current'));
1692 $content .= '<span class="hide"> | </span>' . $right;
1693 $content .= "<span class=\"clearer\"><!-- --></span>\n";
1694 $content .= \html_writer
::end_tag('div');
1698 $prevlink = calendar_get_link_previous(get_string('monthprev', 'calendar'), $urlbase, false, false, false,
1699 true, $prevmonthtime);
1700 $nextlink = calendar_get_link_next(get_string('monthnext', 'calendar'), $urlbase, false, false, false,
1701 true, $nextmonthtime);
1702 $calendarlink = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', array('view' => 'month')),
1703 false, false, false, $time);
1705 if (!empty($data['id'])) {
1706 $calendarlink->param('course', $data['id']);
1709 $content .= \html_writer
::start_tag('div', array('class' => 'calendar-controls'));
1710 $content .= $prevlink . '<span class="hide"> | </span>';
1711 $content .= \html_writer
::tag('span', \html_writer
::link($calendarlink,
1712 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1713 ), array('class' => 'current'));
1714 $content .= '<span class="hide"> | </span>' . $nextlink;
1715 $content .= "<span class=\"clearer\"><!-- --></span>";
1716 $content .= \html_writer
::end_tag('div');
1719 $calendarlink = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', array('view' => 'upcoming')),
1720 false, false, false, $time);
1721 if (!empty($data['id'])) {
1722 $calendarlink->param('course', $data['id']);
1724 $calendarlink = \html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1725 $content .= \html_writer
::tag('div', $calendarlink, array('class' => 'centered'));
1728 $calendarlink = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', array('view' => 'month')),
1729 false, false, false, $time);
1730 if (!empty($data['id'])) {
1731 $calendarlink->param('course', $data['id']);
1733 $calendarlink = \html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1734 $content .= \html_writer
::tag('h3', $calendarlink);
1737 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1738 'view.php?view=month' . $courseid . '&', false, false, false, false, $prevmonthtime);
1739 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1740 'view.php?view=month' . $courseid . '&', false, false, false, false, $nextmonthtime);
1742 $content .= \html_writer
::start_tag('div', array('class' => 'calendar-controls'));
1743 $content .= $prevlink . '<span class="hide"> | </span>';
1744 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1745 $content .= '<span class="hide"> | </span>' . $nextlink;
1746 $content .= '<span class="clearer"><!-- --></span>';
1747 $content .= \html_writer
::end_tag('div')."\n";
1750 $days = calendar_get_days();
1752 $prevtimestamp = strtotime('-1 day', $time);
1753 $nexttimestamp = strtotime('+1 day', $time);
1755 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1756 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1758 $prevname = $days[$prevdate['wday']]['fullname'];
1759 $nextname = $days[$nextdate['wday']]['fullname'];
1760 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&', false, false,
1761 false, false, $prevtimestamp);
1762 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&', false, false, false,
1763 false, $nexttimestamp);
1765 $content .= \html_writer
::start_tag('div', array('class' => 'calendar-controls'));
1766 $content .= $prevlink;
1767 $content .= '<span class="hide"> | </span><span class="current">' .userdate($time,
1768 get_string('strftimedaydate')) . '</span>';
1769 $content .= '<span class="hide"> | </span>' . $nextlink;
1770 $content .= "<span class=\"clearer\"><!-- --></span>";
1771 $content .= \html_writer
::end_tag('div') . "\n";
1780 * Return the representation day.
1782 * @param int $tstamp Timestamp in GMT
1783 * @param int|bool $now current Unix timestamp
1784 * @param bool $usecommonwords
1785 * @return string the formatted date/time
1787 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1788 static $shortformat;
1790 if (empty($shortformat)) {
1791 $shortformat = get_string('strftimedayshort');
1794 if ($now === false) {
1798 // To have it in one place, if a change is needed.
1799 $formal = userdate($tstamp, $shortformat);
1801 $datestamp = usergetdate($tstamp);
1802 $datenow = usergetdate($now);
1804 if ($usecommonwords == false) {
1805 // We don't want words, just a date.
1807 } else if ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1808 return get_string('today', 'calendar');
1809 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1810 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12
1811 && $datenow['yday'] == 1)) {
1812 return get_string('yesterday', 'calendar');
1813 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] +
1 ) ||
1814 ($datestamp['year'] == $datenow['year'] +
1 && $datenow['mday'] == 31 && $datenow['mon'] == 12
1815 && $datestamp['yday'] == 1)) {
1816 return get_string('tomorrow', 'calendar');
1823 * return the formatted representation time.
1826 * @param int $time the timestamp in UTC, as obtained from the database
1827 * @return string the formatted date/time
1829 function calendar_time_representation($time) {
1830 static $langtimeformat = null;
1832 if ($langtimeformat === null) {
1833 $langtimeformat = get_string('strftimetime');
1836 $timeformat = get_user_preferences('calendar_timeformat');
1837 if (empty($timeformat)) {
1838 $timeformat = get_config(null, 'calendar_site_timeformat');
1841 // Allow language customization of selected time format.
1842 if ($timeformat === CALENDAR_TF_12
) {
1843 $timeformat = get_string('strftimetime12', 'langconfig');
1844 } else if ($timeformat === CALENDAR_TF_24
) {
1845 $timeformat = get_string('strftimetime24', 'langconfig');
1848 return userdate($time, empty($timeformat) ?
$langtimeformat : $timeformat);
1852 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1854 * @param string|moodle_url $linkbase
1855 * @param int $d The number of the day.
1856 * @param int $m The number of the month.
1857 * @param int $y The number of the year.
1858 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1859 * $m and $y are kept for backwards compatibility.
1860 * @return moodle_url|null $linkbase
1862 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1863 if (empty($linkbase)) {
1867 if (!($linkbase instanceof \moodle_url
)) {
1868 $linkbase = new \
moodle_url($linkbase);
1871 $linkbase->param('time', calendar_get_timestamp($d, $m, $y, $time));
1877 * Build and return a previous month HTML link, with an arrow.
1879 * @param string $text The text label.
1880 * @param string|moodle_url $linkbase The URL stub.
1881 * @param int $d The number of the date.
1882 * @param int $m The number of the month.
1883 * @param int $y year The number of the year.
1884 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1885 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1886 * $m and $y are kept for backwards compatibility.
1887 * @return string HTML string.
1889 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1890 $href = calendar_get_link_href(new \
moodle_url($linkbase), $d, $m, $y, $time);
1897 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1898 'data-drop-zone' => 'nav-link',
1901 return link_arrow_left($text, $href->out(false), $accesshide, 'previous', $attrs);
1905 * Build and return a next month HTML link, with an arrow.
1907 * @param string $text The text label.
1908 * @param string|moodle_url $linkbase The URL stub.
1909 * @param int $d the number of the Day
1910 * @param int $m The number of the month.
1911 * @param int $y The number of the year.
1912 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1913 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1914 * $m and $y are kept for backwards compatibility.
1915 * @return string HTML string.
1917 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1918 $href = calendar_get_link_href(new \
moodle_url($linkbase), $d, $m, $y, $time);
1925 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1926 'data-drop-zone' => 'nav-link',
1929 return link_arrow_right($text, $href->out(false), $accesshide, 'next', $attrs);
1933 * Return the number of days in month.
1935 * @param int $month the number of the month.
1936 * @param int $year the number of the year
1939 function calendar_days_in_month($month, $year) {
1940 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1941 return $calendartype->get_num_days_in_month($year, $month);
1945 * Get the next following month.
1947 * @param int $month the number of the month.
1948 * @param int $year the number of the year.
1949 * @return array the following month
1951 function calendar_add_month($month, $year) {
1952 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1953 return $calendartype->get_next_month($year, $month);
1957 * Get the previous month.
1959 * @param int $month the number of the month.
1960 * @param int $year the number of the year.
1961 * @return array previous month
1963 function calendar_sub_month($month, $year) {
1964 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1965 return $calendartype->get_prev_month($year, $month);
1969 * Get per-day basis events
1971 * @param array $events list of events
1972 * @param int $month the number of the month
1973 * @param int $year the number of the year
1974 * @param array $eventsbyday event on specific day
1975 * @param array $durationbyday duration of the event in days
1976 * @param array $typesbyday event type (eg: site, course, user, or group)
1977 * @param array $courses list of courses
1980 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1981 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1983 $eventsbyday = array();
1984 $typesbyday = array();
1985 $durationbyday = array();
1987 if ($events === false) {
1991 foreach ($events as $event) {
1992 $startdate = $calendartype->timestamp_to_date_array($event->timestart
);
1993 if ($event->timeduration
) {
1994 $enddate = $calendartype->timestamp_to_date_array($event->timestart +
$event->timeduration
- 1);
1996 $enddate = $startdate;
1999 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair.
2000 if (!($startdate['year'] * 13 +
$startdate['mon'] <= $year * 13 +
$month) &&
2001 ($enddate['year'] * 13 +
$enddate['mon'] >= $year * 13 +
$month)) {
2005 $eventdaystart = intval($startdate['mday']);
2007 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2008 // Give the event to its day.
2009 $eventsbyday[$eventdaystart][] = $event->id
;
2011 // Mark the day as having such an event.
2012 if ($event->courseid
== SITEID
&& $event->groupid
== 0) {
2013 $typesbyday[$eventdaystart]['startsite'] = true;
2014 // Set event class for site event.
2015 $events[$event->id
]->class = 'calendar_event_site';
2016 } else if ($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) {
2017 $typesbyday[$eventdaystart]['startcourse'] = true;
2018 // Set event class for course event.
2019 $events[$event->id
]->class = 'calendar_event_course';
2020 } else if ($event->groupid
) {
2021 $typesbyday[$eventdaystart]['startgroup'] = true;
2022 // Set event class for group event.
2023 $events[$event->id
]->class = 'calendar_event_group';
2024 } else if ($event->userid
) {
2025 $typesbyday[$eventdaystart]['startuser'] = true;
2026 // Set event class for user event.
2027 $events[$event->id
]->class = 'calendar_event_user';
2031 if ($event->timeduration
== 0) {
2032 // Proceed with the next.
2036 // The event starts on $month $year or before.
2037 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2038 $lowerbound = intval($startdate['mday']);
2043 // Also, it ends on $month $year or later.
2044 if ($enddate['mon'] == $month && $enddate['year'] == $year) {
2045 $upperbound = intval($enddate['mday']);
2047 $upperbound = calendar_days_in_month($month, $year);
2050 // Mark all days between $lowerbound and $upperbound (inclusive) as duration.
2051 for ($i = $lowerbound +
1; $i <= $upperbound; ++
$i) {
2052 $durationbyday[$i][] = $event->id
;
2053 if ($event->courseid
== SITEID
&& $event->groupid
== 0) {
2054 $typesbyday[$i]['durationsite'] = true;
2055 } else if ($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) {
2056 $typesbyday[$i]['durationcourse'] = true;
2057 } else if ($event->groupid
) {
2058 $typesbyday[$i]['durationgroup'] = true;
2059 } else if ($event->userid
) {
2060 $typesbyday[$i]['durationuser'] = true;
2069 * Returns the courses to load events for.
2071 * @param array $courseeventsfrom An array of courses to load calendar events for
2072 * @param bool $ignorefilters specify the use of filters, false is set as default
2073 * @param stdClass $user The user object. This defaults to the global $USER object.
2074 * @return array An array of courses, groups, and user to load calendar events for based upon filters
2076 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false, stdClass
$user = null) {
2079 if (is_null($user)) {
2087 // Get the capabilities that allow seeing group events from all groups.
2088 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
2090 $isvaliduser = !empty($user->id
);
2092 if ($ignorefilters ||
calendar_show_event_type(CALENDAR_EVENT_COURSE
, $user)) {
2093 $courses = array_keys($courseeventsfrom);
2095 if ($ignorefilters ||
calendar_show_event_type(CALENDAR_EVENT_SITE
, $user)) {
2096 $courses[] = SITEID
;
2098 $courses = array_unique($courses);
2101 if (!empty($courses) && in_array(SITEID
, $courses)) {
2102 // Sort courses for consistent colour highlighting.
2103 // Effectively ignoring SITEID as setting as last course id.
2104 $key = array_search(SITEID
, $courses);
2105 unset($courses[$key]);
2106 $courses[] = SITEID
;
2109 if ($ignorefilters ||
($isvaliduser && calendar_show_event_type(CALENDAR_EVENT_USER
, $user))) {
2110 $userid = $user->id
;
2113 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP
, $user) ||
$ignorefilters)) {
2115 if (count($courseeventsfrom) == 1) {
2116 $course = reset($courseeventsfrom);
2117 if (has_any_capability($allgroupscaps, \context_course
::instance($course->id
))) {
2118 $coursegroups = groups_get_all_groups($course->id
, 0, 0, 'g.id');
2119 $group = array_keys($coursegroups);
2122 if ($group === false) {
2123 if (!empty($CFG->calendar_adminseesall
) && has_any_capability($allgroupscaps, \context_system
::instance())) {
2125 } else if ($isvaliduser) {
2126 $groupids = array();
2127 foreach ($courseeventsfrom as $courseid => $course) {
2128 // If the user is an editing teacher in there.
2129 if (!empty($user->groupmember
[$course->id
])) {
2130 // We've already cached the users groups for this course so we can just use that.
2131 $groupids = array_merge($groupids, $user->groupmember
[$course->id
]);
2132 } else if ($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
2133 // If this course has groups, show events from all of those related to the current user.
2134 $coursegroups = groups_get_user_groups($course->id
, $user->id
);
2135 $groupids = array_merge($groupids, $coursegroups['0']);
2138 if (!empty($groupids)) {
2144 if (empty($courses)) {
2148 return array($courses, $group, $userid);
2152 * Return the capability for viewing a calendar event.
2154 * @param calendar_event $event event object
2157 function calendar_view_event_allowed(calendar_event
$event) {
2160 // Anyone can see site events.
2161 if ($event->courseid
&& $event->courseid
== SITEID
) {
2165 // If a user can manage events at the site level they can see any event.
2166 $sitecontext = \context_system
::instance();
2167 // If user has manageentries at site level, return true.
2168 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2172 if (!empty($event->groupid
)) {
2173 // If it is a group event we need to be able to manage events in the course, or be in the group.
2174 if (has_capability('moodle/calendar:manageentries', $event->context
) ||
2175 has_capability('moodle/calendar:managegroupentries', $event->context
)) {
2179 $mycourses = enrol_get_my_courses('id');
2180 return isset($mycourses[$event->courseid
]) && groups_is_member($event->groupid
);
2181 } else if ($event->modulename
) {
2182 // If this is a module event we need to be able to see the module.
2183 $coursemodules = [];
2185 // Override events do not have the courseid set.
2186 if ($event->courseid
) {
2187 $courseid = $event->courseid
;
2188 $coursemodules = get_fast_modinfo($event->courseid
)->instances
;
2190 $cmraw = get_coursemodule_from_instance($event->modulename
, $event->instance
, 0, false, MUST_EXIST
);
2191 $courseid = $cmraw->course
;
2192 $coursemodules = get_fast_modinfo($cmraw->course
)->instances
;
2194 $hasmodule = isset($coursemodules[$event->modulename
]);
2195 $hasinstance = isset($coursemodules[$event->modulename
][$event->instance
]);
2197 // If modinfo doesn't know about the module, return false to be safe.
2198 if (!$hasmodule ||
!$hasinstance) {
2202 // Must be able to see the course and the module - MDL-59304.
2203 $cm = $coursemodules[$event->modulename
][$event->instance
];
2204 if (!$cm->uservisible
) {
2207 $mycourses = enrol_get_my_courses('id');
2208 return isset($mycourses[$courseid]);
2209 } else if ($event->categoryid
) {
2210 // If this is a category we need to be able to see the category.
2211 $cat = \core_course_category
::get($event->categoryid
, IGNORE_MISSING
);
2216 } else if (!empty($event->courseid
)) {
2217 // If it is a course event we need to be able to manage events in the course, or be in the course.
2218 if (has_capability('moodle/calendar:manageentries', $event->context
)) {
2222 return can_access_course(get_course($event->courseid
));
2223 } else if ($event->userid
) {
2224 if ($event->userid
!= $USER->id
) {
2225 // No-one can ever see another users events.
2230 throw new moodle_exception('unknown event type');
2237 * Return the capability for editing calendar event.
2239 * @param calendar_event $event event object
2240 * @param bool $manualedit is the event being edited manually by the user
2241 * @return bool capability to edit event
2243 function calendar_edit_event_allowed($event, $manualedit = false) {
2246 // Must be logged in.
2247 if (!isloggedin()) {
2251 // Can not be using guest account.
2252 if (isguestuser()) {
2256 if ($manualedit && !empty($event->modulename
)) {
2257 $hascallback = component_callback_exists(
2258 'mod_' . $event->modulename
,
2259 'core_calendar_event_timestart_updated'
2262 if (!$hascallback) {
2263 // If the activity hasn't implemented the correct callback
2264 // to handle changes to it's events then don't allow any
2265 // manual changes to them.
2269 $coursemodules = get_fast_modinfo($event->courseid
)->instances
;
2270 $hasmodule = isset($coursemodules[$event->modulename
]);
2271 $hasinstance = isset($coursemodules[$event->modulename
][$event->instance
]);
2273 // If modinfo doesn't know about the module, return false to be safe.
2274 if (!$hasmodule ||
!$hasinstance) {
2278 $coursemodule = $coursemodules[$event->modulename
][$event->instance
];
2279 $context = context_module
::instance($coursemodule->id
);
2280 // This is the capability that allows a user to modify the activity
2281 // settings. Since the activity generated this event we need to check
2282 // that the current user has the same capability before allowing them
2283 // to update the event because the changes to the event will be
2284 // reflected within the activity.
2285 return has_capability('moodle/course:manageactivities', $context);
2288 if ($manualedit && !empty($event->component
)) {
2289 // TODO possibly we can later add a callback similar to core_calendar_event_timestart_updated in the modules.
2293 // You cannot edit URL based calendar subscription events presently.
2294 if (!empty($event->subscriptionid
)) {
2295 if (!empty($event->subscription
->url
)) {
2296 // This event can be updated externally, so it cannot be edited.
2301 $sitecontext = \context_system
::instance();
2303 // If user has manageentries at site level, return true.
2304 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2308 // If groupid is set, it's definitely a group event.
2309 if (!empty($event->groupid
)) {
2310 // Allow users to add/edit group events if -
2311 // 1) They have manageentries for the course OR
2312 // 2) They have managegroupentries AND are in the group.
2313 $group = $DB->get_record('groups', array('id' => $event->groupid
));
2315 has_capability('moodle/calendar:manageentries', $event->context
) ||
2316 (has_capability('moodle/calendar:managegroupentries', $event->context
)
2317 && groups_is_member($event->groupid
)));
2318 } else if (!empty($event->courseid
)) {
2319 // If groupid is not set, but course is set, it's definitely a course event.
2320 return has_capability('moodle/calendar:manageentries', $event->context
);
2321 } else if (!empty($event->categoryid
)) {
2322 // If groupid is not set, but category is set, it's definitely a category event.
2323 return has_capability('moodle/calendar:manageentries', $event->context
);
2324 } else if (!empty($event->userid
) && $event->userid
== $USER->id
) {
2325 // If course is not set, but userid id set, it's a user event.
2326 return (has_capability('moodle/calendar:manageownentries', $event->context
));
2327 } else if (!empty($event->userid
)) {
2328 return (has_capability('moodle/calendar:manageentries', $event->context
));
2335 * Return the capability for deleting a calendar event.
2337 * @param calendar_event $event The event object
2338 * @return bool Whether the user has permission to delete the event or not.
2340 function calendar_delete_event_allowed($event) {
2341 // Only allow delete if you have capabilities and it is not an module or component event.
2342 return (calendar_edit_event_allowed($event) && empty($event->modulename
) && empty($event->component
));
2346 * Returns the default courses to display on the calendar when there isn't a specific
2347 * course to display.
2349 * @param int $courseid (optional) If passed, an additional course can be returned for admins (the current course).
2350 * @param string $fields Comma separated list of course fields to return.
2351 * @param bool $canmanage If true, this will return the list of courses the user can create events in, rather
2352 * than the list of courses they see events from (an admin can always add events in a course
2353 * calendar, even if they are not enrolled in the course).
2354 * @param int $userid (optional) The user which this function returns the default courses for.
2355 * By default the current user.
2356 * @return array $courses Array of courses to display
2358 function calendar_get_default_courses($courseid = null, $fields = '*', $canmanage = false, int $userid = null) {
2362 if (!isloggedin()) {
2365 $userid = $USER->id
;
2368 if ((!empty($CFG->calendar_adminseesall
) ||
$canmanage) &&
2369 has_capability('moodle/calendar:manageentries', context_system
::instance(), $userid)) {
2371 // Add a c. prefix to every field as expected by get_courses function.
2372 $fieldlist = explode(',', $fields);
2374 $prefixedfields = array_map(function($value) {
2375 return 'c.' . trim(strtolower($value));
2377 if (!in_array('c.visible', $prefixedfields) && !in_array('c.*', $prefixedfields)) {
2378 $prefixedfields[] = 'c.visible';
2380 $courses = get_courses('all', 'c.shortname', implode(',', $prefixedfields));
2382 $courses = enrol_get_users_courses($userid, true, $fields);
2385 if ($courseid && $courseid != SITEID
) {
2386 if (empty($courses[$courseid]) && has_capability('moodle/calendar:manageentries', context_system
::instance(), $userid)) {
2387 // Allow a site admin to see calendars from courses he is not enrolled in.
2388 // This will come from $COURSE.
2389 $courses[$courseid] = get_course($courseid);
2397 * Get event format time.
2399 * @param calendar_event $event event object
2400 * @param int $now current time in gmt
2401 * @param array $linkparams list of params for event link
2402 * @param bool $usecommonwords the words as formatted date/time.
2403 * @param int $showtime determine the show time GMT timestamp
2404 * @return string $eventtime link/string for event time
2406 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
2407 $starttime = $event->timestart
;
2408 $endtime = $event->timestart +
$event->timeduration
;
2410 if (empty($linkparams) ||
!is_array($linkparams)) {
2411 $linkparams = array();
2414 $linkparams['view'] = 'day';
2416 // OK, now to get a meaningful display.
2417 // Check if there is a duration for this event.
2418 if ($event->timeduration
) {
2419 // Get the midnight of the day the event will start.
2420 $usermidnightstart = usergetmidnight($starttime);
2421 // Get the midnight of the day the event will end.
2422 $usermidnightend = usergetmidnight($endtime);
2423 // Check if we will still be on the same day.
2424 if ($usermidnightstart == $usermidnightend) {
2425 // Check if we are running all day.
2426 if ($event->timeduration
== DAYSECS
) {
2427 $time = get_string('allday', 'calendar');
2428 } else { // Specify the time we will be running this from.
2429 $datestart = calendar_time_representation($starttime);
2430 $dateend = calendar_time_representation($endtime);
2431 $time = $datestart . ' <strong>»</strong> ' . $dateend;
2434 // Set printable representation.
2436 $day = calendar_day_representation($event->timestart
, $now, $usecommonwords);
2437 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $endtime);
2438 $eventtime = \html_writer
::link($url, $day) . ', ' . $time;
2442 } else { // It must spans two or more days.
2443 $daystart = calendar_day_representation($event->timestart
, $now, $usecommonwords) . ', ';
2444 if ($showtime == $usermidnightstart) {
2447 $timestart = calendar_time_representation($event->timestart
);
2448 $dayend = calendar_day_representation($event->timestart +
$event->timeduration
, $now, $usecommonwords) . ', ';
2449 if ($showtime == $usermidnightend) {
2452 $timeend = calendar_time_representation($event->timestart +
$event->timeduration
);
2454 // Set printable representation.
2455 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2456 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $endtime);
2457 $eventtime = $timestart . ' <strong>»</strong> ' . \html_writer
::link($url, $dayend) . $timeend;
2459 // The event is in the future, print start and end links.
2460 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $starttime);
2461 $eventtime = \html_writer
::link($url, $daystart) . $timestart . ' <strong>»</strong> ';
2463 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $endtime);
2464 $eventtime .= \html_writer
::link($url, $dayend) . $timeend;
2467 } else { // There is no time duration.
2468 $time = calendar_time_representation($event->timestart
);
2469 // Set printable representation.
2471 $day = calendar_day_representation($event->timestart
, $now, $usecommonwords);
2472 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $starttime);
2473 $eventtime = \html_writer
::link($url, $day) . ', ' . trim($time);
2479 // Check if It has expired.
2480 if ($event->timestart +
$event->timeduration
< $now) {
2481 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2488 * Checks to see if the requested type of event should be shown for the given user.
2490 * @param int $type The type to check the display for (default is to display all)
2491 * @param stdClass|int|null $user The user to check for - by default the current user
2492 * @return bool True if the tyep should be displayed false otherwise
2494 function calendar_show_event_type($type, $user = null) {
2495 $default = CALENDAR_EVENT_SITE + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER
;
2497 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2499 if (!isset($SESSION->calendarshoweventtype
)) {
2500 $SESSION->calendarshoweventtype
= $default;
2502 return $SESSION->calendarshoweventtype
& $type;
2504 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2509 * Sets the display of the event type given $display.
2511 * If $display = true the event type will be shown.
2512 * If $display = false the event type will NOT be shown.
2513 * If $display = null the current value will be toggled and saved.
2515 * @param int $type object of CALENDAR_EVENT_XXX
2516 * @param bool $display option to display event type
2517 * @param stdClass|int $user moodle user object or id, null means current user
2519 function calendar_set_event_type_display($type, $display = null, $user = null) {
2520 $persist = get_user_preferences('calendar_persistflt', 0, $user);
2521 $default = CALENDAR_EVENT_SITE + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP
2522 + CALENDAR_EVENT_USER + CALENDAR_EVENT_COURSECAT
;
2523 if ($persist === 0) {
2525 if (!isset($SESSION->calendarshoweventtype
)) {
2526 $SESSION->calendarshoweventtype
= $default;
2528 $preference = $SESSION->calendarshoweventtype
;
2530 $preference = get_user_preferences('calendar_savedflt', $default, $user);
2532 $current = $preference & $type;
2533 if ($display === null) {
2534 $display = !$current;
2536 if ($display && !$current) {
2537 $preference +
= $type;
2538 } else if (!$display && $current) {
2539 $preference -= $type;
2541 if ($persist === 0) {
2542 $SESSION->calendarshoweventtype
= $preference;
2544 if ($preference == $default) {
2545 unset_user_preference('calendar_savedflt', $user);
2547 set_user_preference('calendar_savedflt', $preference, $user);
2553 * Get calendar's allowed types.
2555 * @param stdClass $allowed list of allowed edit for event type
2556 * @param stdClass|int $course object of a course or course id
2557 * @param array $groups array of groups for the given course
2558 * @param stdClass|int $category object of a category
2560 function calendar_get_allowed_types(&$allowed, $course = null, $groups = null, $category = null) {
2563 $allowed = new \
stdClass();
2564 $allowed->user
= has_capability('moodle/calendar:manageownentries', \context_system
::instance());
2565 $allowed->groups
= false;
2566 $allowed->courses
= false;
2567 $allowed->categories
= false;
2568 $allowed->site
= has_capability('moodle/calendar:manageentries', \context_course
::instance(SITEID
));
2569 $getgroupsfunc = function($course, $context, $user) use ($groups) {
2570 if ($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
2571 if (has_capability('moodle/site:accessallgroups', $context)) {
2572 return is_null($groups) ?
groups_get_all_groups($course->id
) : $groups;
2574 if (is_null($groups)) {
2575 return groups_get_all_groups($course->id
, $user->id
);
2577 return array_filter($groups, function($group) use ($user) {
2578 return isset($group->members
[$user->id
]);
2587 if (!empty($course)) {
2588 if (!is_object($course)) {
2589 $course = $DB->get_record('course', array('id' => $course), 'id, groupmode, groupmodeforce', MUST_EXIST
);
2591 if ($course->id
!= SITEID
) {
2592 $coursecontext = \context_course
::instance($course->id
);
2593 $allowed->user
= has_capability('moodle/calendar:manageownentries', $coursecontext);
2595 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2596 $allowed->courses
= array($course->id
=> 1);
2597 $allowed->groups
= $getgroupsfunc($course, $coursecontext, $USER);
2598 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
2599 $allowed->groups
= $getgroupsfunc($course, $coursecontext, $USER);
2604 if (!empty($category)) {
2605 $catcontext = \context_coursecat
::instance($category->id
);
2606 if (has_capability('moodle/category:manage', $catcontext)) {
2607 $allowed->categories
= [$category->id
=> 1];
2613 * See if user can add calendar entries at all used to print the "New Event" button.
2615 * @param stdClass $course object of a course or course id
2616 * @return bool has the capability to add at least one event type
2618 function calendar_user_can_add_event($course) {
2619 if (!isloggedin() ||
isguestuser()) {
2623 calendar_get_allowed_types($allowed, $course);
2625 return (bool)($allowed->user ||
$allowed->groups ||
$allowed->courses ||
$allowed->categories ||
$allowed->site
);
2629 * Check wether the current user is permitted to add events.
2631 * @param stdClass $event object of event
2632 * @return bool has the capability to add event
2634 function calendar_add_event_allowed($event) {
2637 // Can not be using guest account.
2638 if (!isloggedin() or isguestuser()) {
2642 $sitecontext = \context_system
::instance();
2644 // If user has manageentries at site level, always return true.
2645 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2649 switch ($event->eventtype
) {
2651 return has_capability('moodle/category:manage', $event->context
);
2653 return has_capability('moodle/calendar:manageentries', $event->context
);
2655 // Allow users to add/edit group events if -
2656 // 1) They have manageentries (= entries for whole course).
2657 // 2) They have managegroupentries AND are in the group.
2658 $group = $DB->get_record('groups', array('id' => $event->groupid
));
2660 has_capability('moodle/calendar:manageentries', $event->context
) ||
2661 (has_capability('moodle/calendar:managegroupentries', $event->context
)
2662 && groups_is_member($event->groupid
)));
2664 if ($event->userid
== $USER->id
) {
2665 return (has_capability('moodle/calendar:manageownentries', $event->context
));
2667 // There is intentionally no 'break'.
2669 return has_capability('moodle/calendar:manageentries', $event->context
);
2671 return has_capability('moodle/calendar:manageentries', $event->context
);
2676 * Returns option list for the poll interval setting.
2678 * @return array An array of poll interval options. Interval => description.
2680 function calendar_get_pollinterval_choices() {
2682 '0' => new \
lang_string('never', 'calendar'),
2683 HOURSECS
=> new \
lang_string('hourly', 'calendar'),
2684 DAYSECS
=> new \
lang_string('daily', 'calendar'),
2685 WEEKSECS
=> new \
lang_string('weekly', 'calendar'),
2686 '2628000' => new \
lang_string('monthly', 'calendar'),
2687 YEARSECS
=> new \
lang_string('annually', 'calendar')
2692 * Returns option list of available options for the calendar event type, given the current user and course.
2694 * @param int $courseid The id of the course
2695 * @return array An array containing the event types the user can create.
2697 function calendar_get_eventtype_choices($courseid) {
2699 $allowed = new \stdClass
;
2700 calendar_get_allowed_types($allowed, $courseid);
2702 if ($allowed->user
) {
2703 $choices['user'] = get_string('userevents', 'calendar');
2705 if ($allowed->site
) {
2706 $choices['site'] = get_string('siteevents', 'calendar');
2708 if (!empty($allowed->courses
)) {
2709 $choices['course'] = get_string('courseevents', 'calendar');
2711 if (!empty($allowed->categories
)) {
2712 $choices['category'] = get_string('categoryevents', 'calendar');
2714 if (!empty($allowed->groups
) and is_array($allowed->groups
)) {
2715 $choices['group'] = get_string('group');
2718 return array($choices, $allowed->groups
);
2722 * Add an iCalendar subscription to the database.
2724 * @param stdClass $sub The subscription object (e.g. from the form)
2725 * @return int The insert ID, if any.
2727 function calendar_add_subscription($sub) {
2728 global $DB, $USER, $SITE;
2730 // Undo the form definition work around to allow us to have two different
2731 // course selectors present depending on which event type the user selects.
2732 if (!empty($sub->groupcourseid
)) {
2733 $sub->courseid
= $sub->groupcourseid
;
2734 unset($sub->groupcourseid
);
2737 // Default course id if none is set.
2738 if (empty($sub->courseid
)) {
2739 if ($sub->eventtype
=== 'site') {
2740 $sub->courseid
= SITEID
;
2746 if ($sub->eventtype
=== 'site') {
2747 $sub->courseid
= $SITE->id
;
2748 } else if ($sub->eventtype
=== 'group' ||
$sub->eventtype
=== 'course') {
2749 $sub->courseid
= $sub->courseid
;
2750 } else if ($sub->eventtype
=== 'category') {
2751 $sub->categoryid
= $sub->categoryid
;
2756 $sub->userid
= $USER->id
;
2758 // File subscriptions never update.
2759 if (empty($sub->url
)) {
2760 $sub->pollinterval
= 0;
2763 if (!empty($sub->name
)) {
2764 if (empty($sub->id
)) {
2765 $id = $DB->insert_record('event_subscriptions', $sub);
2766 // We cannot cache the data here because $sub is not complete.
2768 // Trigger event, calendar subscription added.
2769 $eventparams = array('objectid' => $sub->id
,
2770 'context' => calendar_get_calendar_context($sub),
2772 'eventtype' => $sub->eventtype
,
2775 switch ($sub->eventtype
) {
2777 $eventparams['other']['categoryid'] = $sub->categoryid
;
2780 $eventparams['other']['courseid'] = $sub->courseid
;
2783 $eventparams['other']['courseid'] = $sub->courseid
;
2784 $eventparams['other']['groupid'] = $sub->groupid
;
2787 $eventparams['other']['courseid'] = $sub->courseid
;
2790 $event = \core\event\calendar_subscription_created
::create($eventparams);
2794 // Why are we doing an update here?
2795 calendar_update_subscription($sub);
2799 print_error('errorbadsubscription', 'importcalendar');
2804 * Add an iCalendar event to the Moodle calendar.
2806 * @param stdClass $event The RFC-2445 iCalendar event
2807 * @param int $unused Deprecated
2808 * @param int $subscriptionid The iCalendar subscription ID
2809 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2810 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2811 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2813 function calendar_add_icalendar_event($event, $unused = null, $subscriptionid, $timezone='UTC') {
2816 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2817 if (empty($event->properties
['SUMMARY'])) {
2821 $name = $event->properties
['SUMMARY'][0]->value
;
2822 $name = str_replace('\n', '<br />', $name);
2823 $name = str_replace('\\', '', $name);
2824 $name = preg_replace('/\s+/u', ' ', $name);
2826 $eventrecord = new \stdClass
;
2827 $eventrecord->name
= clean_param($name, PARAM_NOTAGS
);
2829 if (empty($event->properties
['DESCRIPTION'][0]->value
)) {
2832 $description = $event->properties
['DESCRIPTION'][0]->value
;
2833 $description = clean_param($description, PARAM_NOTAGS
);
2834 $description = str_replace('\n', '<br />', $description);
2835 $description = str_replace('\\', '', $description);
2836 $description = preg_replace('/\s+/u', ' ', $description);
2838 $eventrecord->description
= $description;
2840 // Probably a repeating event with RRULE etc. TODO: skip for now.
2841 if (empty($event->properties
['DTSTART'][0]->value
)) {
2845 if (isset($event->properties
['DTSTART'][0]->parameters
['TZID'])) {
2846 $tz = $event->properties
['DTSTART'][0]->parameters
['TZID'];
2850 $tz = \core_date
::normalise_timezone($tz);
2851 $eventrecord->timestart
= strtotime($event->properties
['DTSTART'][0]->value
. ' ' . $tz);
2852 if (empty($event->properties
['DTEND'])) {
2853 $eventrecord->timeduration
= 0; // No duration if no end time specified.
2855 if (isset($event->properties
['DTEND'][0]->parameters
['TZID'])) {
2856 $endtz = $event->properties
['DTEND'][0]->parameters
['TZID'];
2860 $endtz = \core_date
::normalise_timezone($endtz);
2861 $eventrecord->timeduration
= strtotime($event->properties
['DTEND'][0]->value
. ' ' . $endtz) - $eventrecord->timestart
;
2864 // Check to see if it should be treated as an all day event.
2865 if ($eventrecord->timeduration
== DAYSECS
) {
2866 // Check to see if the event started at Midnight on the imported calendar.
2867 date_default_timezone_set($timezone);
2868 if (date('H:i:s', $eventrecord->timestart
) === "00:00:00") {
2869 // This event should be an all day event. This is not correct, we don't do anything differently for all day events.
2871 $eventrecord->timeduration
= 0;
2873 \core_date
::set_default_server_timezone();
2876 $eventrecord->location
= empty($event->properties
['LOCATION'][0]->value
) ?
'' :
2877 trim(str_replace('\\', '', $event->properties
['LOCATION'][0]->value
));
2878 $eventrecord->uuid
= $event->properties
['UID'][0]->value
;
2879 $eventrecord->timemodified
= time();
2881 // Add the iCal subscription details if required.
2882 // We should never do anything with an event without a subscription reference.
2883 $sub = calendar_get_subscription($subscriptionid);
2884 $eventrecord->subscriptionid
= $subscriptionid;
2885 $eventrecord->userid
= $sub->userid
;
2886 $eventrecord->groupid
= $sub->groupid
;
2887 $eventrecord->courseid
= $sub->courseid
;
2888 $eventrecord->categoryid
= $sub->categoryid
;
2889 $eventrecord->eventtype
= $sub->eventtype
;
2891 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid
,
2892 'subscriptionid' => $eventrecord->subscriptionid
))) {
2894 // Compare iCal event data against the moodle event to see if something has changed.
2895 $result = array_diff((array) $eventrecord, (array) $updaterecord);
2897 // Unset timemodified field because it's always going to be different.
2898 unset($result['timemodified']);
2900 if (count($result)) {
2901 $eventrecord->id
= $updaterecord->id
;
2902 $return = CALENDAR_IMPORT_EVENT_UPDATED
; // Update.
2904 return CALENDAR_IMPORT_EVENT_SKIPPED
;
2907 $return = CALENDAR_IMPORT_EVENT_INSERTED
; // Insert.
2910 if ($createdevent = \calendar_event
::create($eventrecord, false)) {
2911 if (!empty($event->properties
['RRULE'])) {
2912 // Repeating events.
2913 date_default_timezone_set($tz); // Change time zone to parse all events.
2914 $rrule = new \core_calendar\rrule_manager
($event->properties
['RRULE'][0]->value
);
2915 $rrule->parse_rrule();
2916 $rrule->create_events($createdevent);
2917 \core_date
::set_default_server_timezone(); // Change time zone back to what it was.
2926 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2928 * @param int $subscriptionid The ID of the subscription we are acting upon.
2929 * @param int $pollinterval The poll interval to use.
2930 * @param int $action The action to be performed. One of update or remove.
2931 * @throws dml_exception if invalid subscriptionid is provided
2932 * @return string A log of the import progress, including errors
2934 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2935 // Fetch the subscription from the database making sure it exists.
2936 $sub = calendar_get_subscription($subscriptionid);
2938 // Update or remove the subscription, based on action.
2940 case CALENDAR_SUBSCRIPTION_UPDATE
:
2941 // Skip updating file subscriptions.
2942 if (empty($sub->url
)) {
2945 $sub->pollinterval
= $pollinterval;
2946 calendar_update_subscription($sub);
2948 // Update the events.
2949 return "<p>" . get_string('subscriptionupdated', 'calendar', $sub->name
) . "</p>" .
2950 calendar_update_subscription_events($subscriptionid);
2951 case CALENDAR_SUBSCRIPTION_REMOVE
:
2952 calendar_delete_subscription($subscriptionid);
2953 return get_string('subscriptionremoved', 'calendar', $sub->name
);
2962 * Delete subscription and all related events.
2964 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
2966 function calendar_delete_subscription($subscription) {
2969 if (!is_object($subscription)) {
2970 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST
);
2973 // Delete subscription and related events.
2974 $DB->delete_records('event', array('subscriptionid' => $subscription->id
));
2975 $DB->delete_records('event_subscriptions', array('id' => $subscription->id
));
2976 \cache_helper
::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id
));
2978 // Trigger event, calendar subscription deleted.
2979 $eventparams = array('objectid' => $subscription->id
,
2980 'context' => calendar_get_calendar_context($subscription),
2982 'eventtype' => $subscription->eventtype
,
2985 switch ($subscription->eventtype
) {
2987 $eventparams['other']['categoryid'] = $subscription->categoryid
;
2990 $eventparams['other']['courseid'] = $subscription->courseid
;
2993 $eventparams['other']['courseid'] = $subscription->courseid
;
2994 $eventparams['other']['groupid'] = $subscription->groupid
;
2997 $eventparams['other']['courseid'] = $subscription->courseid
;
2999 $event = \core\event\calendar_subscription_deleted
::create($eventparams);
3004 * From a URL, fetch the calendar and return an iCalendar object.
3006 * @param string $url The iCalendar URL
3007 * @return iCalendar The iCalendar object
3009 function calendar_get_icalendar($url) {
3012 require_once($CFG->libdir
. '/filelib.php');
3014 $curl = new \
curl();
3015 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
3016 $calendar = $curl->get($url);
3018 // Http code validation should actually be the job of curl class.
3019 if (!$calendar ||
$curl->info
['http_code'] != 200 ||
!empty($curl->errorno
)) {
3020 throw new \
moodle_exception('errorinvalidicalurl', 'calendar');
3023 $ical = new \
iCalendar();
3024 $ical->unserialize($calendar);
3030 * Import events from an iCalendar object into a course calendar.
3032 * @param iCalendar $ical The iCalendar object.
3033 * @param int $unused Deprecated
3034 * @param int $subscriptionid The subscription ID.
3035 * @return string A log of the import progress, including errors.
3037 function calendar_import_icalendar_events($ical, $unused = null, $subscriptionid = null) {
3045 // Large calendars take a while...
3047 \core_php_time_limit
::raise(300);
3050 // Grab the timezone from the iCalendar file to be used later.
3051 if (isset($ical->properties
['X-WR-TIMEZONE'][0]->value
)) {
3052 $timezone = $ical->properties
['X-WR-TIMEZONE'][0]->value
;
3058 foreach ($ical->components
['VEVENT'] as $event) {
3059 $icaluuids[] = $event->properties
['UID'][0]->value
;
3060 $res = calendar_add_icalendar_event($event, null, $subscriptionid, $timezone);
3062 case CALENDAR_IMPORT_EVENT_UPDATED
:
3065 case CALENDAR_IMPORT_EVENT_INSERTED
:
3068 case CALENDAR_IMPORT_EVENT_SKIPPED
:
3072 $return .= '<p>' . get_string('erroraddingevent', 'calendar') . ': ';
3073 if (empty($event->properties
['SUMMARY'])) {
3074 $return .= '(' . get_string('notitle', 'calendar') . ')';
3076 $return .= $event->properties
['SUMMARY'][0]->value
;
3078 $return .= "</p>\n";
3083 $existing = $DB->get_field('event_subscriptions', 'lastupdated', ['id' => $subscriptionid]);
3084 if (!empty($existing)) {
3085 $eventsuuids = $DB->get_records_menu('event', ['subscriptionid' => $subscriptionid], '', 'id, uuid');
3087 $icaleventscount = count($icaluuids);
3089 if (count($eventsuuids) > $icaleventscount) {
3090 foreach ($eventsuuids as $eventid => $eventuuid) {
3091 if (!in_array($eventuuid, $icaluuids)) {
3092 $tobedeleted[] = $eventid;
3095 if (!empty($tobedeleted)) {
3096 $DB->delete_records_list('event', 'id', $tobedeleted);
3097 $return .= "<p> " . get_string('eventsdeleted', 'calendar') . ": " . count($tobedeleted) . "</p> ";
3102 $return .= "<p>" . get_string('eventsimported', 'calendar', $eventcount) . "</p> ";
3103 $return .= "<p>" . get_string('eventsskipped', 'calendar', $skippedcount) . "</p> ";
3104 $return .= "<p>" . get_string('eventsupdated', 'calendar', $updatecount) . "</p>";
3109 * Fetch a calendar subscription and update the events in the calendar.
3111 * @param int $subscriptionid The course ID for the calendar.
3112 * @return string A log of the import progress, including errors.
3114 function calendar_update_subscription_events($subscriptionid) {
3115 $sub = calendar_get_subscription($subscriptionid);
3117 // Don't update a file subscription.
3118 if (empty($sub->url
)) {
3119 return 'File subscription not updated.';
3122 $ical = calendar_get_icalendar($sub->url
);
3123 $return = calendar_import_icalendar_events($ical, null, $subscriptionid);
3124 $sub->lastupdated
= time();
3126 calendar_update_subscription($sub);
3132 * Update a calendar subscription. Also updates the associated cache.
3134 * @param stdClass|array $subscription Subscription record.
3135 * @throws coding_exception If something goes wrong
3138 function calendar_update_subscription($subscription) {
3141 if (is_array($subscription)) {
3142 $subscription = (object)$subscription;
3144 if (empty($subscription->id
) ||
!$DB->record_exists('event_subscriptions', array('id' => $subscription->id
))) {
3145 throw new \
coding_exception('Cannot update a subscription without a valid id');
3148 $DB->update_record('event_subscriptions', $subscription);
3151 $cache = \cache
::make('core', 'calendar_subscriptions');
3152 $cache->set($subscription->id
, $subscription);
3154 // Trigger event, calendar subscription updated.
3155 $eventparams = array('userid' => $subscription->userid
,
3156 'objectid' => $subscription->id
,
3157 'context' => calendar_get_calendar_context($subscription),
3159 'eventtype' => $subscription->eventtype
,
3162 switch ($subscription->eventtype
) {
3164 $eventparams['other']['categoryid'] = $subscription->categoryid
;
3167 $eventparams['other']['courseid'] = $subscription->courseid
;
3170 $eventparams['other']['courseid'] = $subscription->courseid
;
3171 $eventparams['other']['groupid'] = $subscription->groupid
;
3174 $eventparams['other']['courseid'] = $subscription->courseid
;
3176 $event = \core\event\calendar_subscription_updated
::create($eventparams);
3181 * Checks to see if the user can edit a given subscription feed.
3183 * @param mixed $subscriptionorid Subscription object or id
3184 * @return bool true if current user can edit the subscription else false
3186 function calendar_can_edit_subscription($subscriptionorid) {
3187 if (is_array($subscriptionorid)) {
3188 $subscription = (object)$subscriptionorid;
3189 } else if (is_object($subscriptionorid)) {
3190 $subscription = $subscriptionorid;
3192 $subscription = calendar_get_subscription($subscriptionorid);
3195 $allowed = new \stdClass
;
3196 $courseid = $subscription->courseid
;
3197 $categoryid = $subscription->categoryid
;
3198 $groupid = $subscription->groupid
;
3201 if (!empty($categoryid)) {
3202 $category = \core_course_category
::get($categoryid);
3204 calendar_get_allowed_types($allowed, $courseid, null, $category);
3205 switch ($subscription->eventtype
) {
3207 return $allowed->user
;
3209 if (isset($allowed->courses
[$courseid])) {
3210 return $allowed->courses
[$courseid];
3215 if (isset($allowed->categories
[$categoryid])) {
3216 return $allowed->categories
[$categoryid];
3221 return $allowed->site
;
3223 if (isset($allowed->groups
[$groupid])) {
3224 return $allowed->groups
[$groupid];
3234 * Helper function to determine the context of a calendar subscription.
3235 * Subscriptions can be created in two contexts COURSE, or USER.
3237 * @param stdClass $subscription
3238 * @return context instance
3240 function calendar_get_calendar_context($subscription) {
3241 // Determine context based on calendar type.
3242 if ($subscription->eventtype
=== 'site') {
3243 $context = \context_course
::instance(SITEID
);
3244 } else if ($subscription->eventtype
=== 'group' ||
$subscription->eventtype
=== 'course') {
3245 $context = \context_course
::instance($subscription->courseid
);
3247 $context = \context_user
::instance($subscription->userid
);
3253 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
3255 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3259 function core_calendar_user_preferences() {
3261 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS
, 'null' => NULL_NOT_ALLOWED
, 'default' => '0',
3262 'choices' => array('0', CALENDAR_TF_12
, CALENDAR_TF_24
)
3264 $preferences['calendar_startwday'] = array('type' => PARAM_INT
, 'null' => NULL_NOT_ALLOWED
, 'default' => 0,
3265 'choices' => array(0, 1, 2, 3, 4, 5, 6));
3266 $preferences['calendar_maxevents'] = array('type' => PARAM_INT
, 'choices' => range(1, 20));
3267 $preferences['calendar_lookahead'] = array('type' => PARAM_INT
, 'null' => NULL_NOT_ALLOWED
, 'default' => 365,
3268 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3269 $preferences['calendar_persistflt'] = array('type' => PARAM_INT
, 'null' => NULL_NOT_ALLOWED
, 'default' => 0,
3270 'choices' => array(0, 1));
3271 return $preferences;
3275 * Get legacy calendar events
3277 * @param int $tstart Start time of time range for events
3278 * @param int $tend End time of time range for events
3279 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3280 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3281 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3282 * @param boolean $withduration whether only events starting within time range selected
3283 * or events in progress/already started selected as well
3284 * @param boolean $ignorehidden whether to select only visible events or all events
3285 * @param array $categories array of category ids and/or objects.
3286 * @param int $limitnum Number of events to fetch or zero to fetch all.
3288 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3290 function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses,
3291 $withduration = true, $ignorehidden = true, $categories = [], $limitnum = 0) {
3292 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3293 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3294 // parameters, but with the new API method, only null and arrays are accepted.
3295 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3296 // If parameter is true, return null.
3297 if ($param === true) {
3301 // If parameter is false, return an empty array.
3302 if ($param === false) {
3306 // If the parameter is a scalar value, enclose it in an array.
3307 if (!is_array($param)) {
3311 // No normalisation required.
3313 }, [$users, $groups, $courses, $categories]);
3315 // If a single user is provided, we can use that for capability checks.
3316 // Otherwise current logged in user is used - See MDL-58768.
3317 if (is_array($userparam) && count($userparam) == 1) {
3318 \core_calendar\local\event\container
::set_requesting_user($userparam[0]);
3320 $mapper = \core_calendar\local\event\container
::get_event_mapper();
3321 $events = \core_calendar\local\api
::get_events(
3338 return array_reduce($events, function($carry, $event) use ($mapper) {
3339 return $carry +
[$event->get_id() => $mapper->from_event_to_stdclass($event)];
3345 * Get the calendar view output.
3347 * @param \calendar_information $calendar The calendar being represented
3348 * @param string $view The type of calendar to have displayed
3349 * @param bool $includenavigation Whether to include navigation
3350 * @param bool $skipevents Whether to load the events or not
3351 * @param int $lookahead Overwrites site and users's lookahead setting.
3352 * @return array[array, string]
3354 function calendar_get_view(\calendar_information
$calendar, $view, $includenavigation = true, bool $skipevents = false,
3355 ?
int $lookahead = null) {
3358 $renderer = $PAGE->get_renderer('core_calendar');
3359 $type = \core_calendar\type_factory
::get_calendar_instance();
3361 // Calculate the bounds of the month.
3362 $calendardate = $type->timestamp_to_date_array($calendar->time
);
3364 $date = new \
DateTime('now', core_date
::get_user_timezone_object(99));
3367 if ($view === 'day') {
3368 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday']);
3369 $date->setTimestamp($tstart);
3370 $date->modify('+1 day');
3371 } else if ($view === 'upcoming' ||
$view === 'upcoming_mini') {
3372 // Number of days in the future that will be used to fetch events.
3374 if (isset($CFG->calendar_lookahead
)) {
3375 $defaultlookahead = intval($CFG->calendar_lookahead
);
3377 $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD
;
3379 $lookahead = get_user_preferences('calendar_lookahead', $defaultlookahead);
3382 // Maximum number of events to be displayed on upcoming view.
3383 $defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS
;
3384 if (isset($CFG->calendar_maxevents
)) {
3385 $defaultmaxevents = intval($CFG->calendar_maxevents
);
3387 $eventlimit = get_user_preferences('calendar_maxevents', $defaultmaxevents);
3389 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday'],
3390 $calendardate['hours']);
3391 $date->setTimestamp($tstart);
3392 $date->modify('+' . $lookahead . ' days');
3394 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], 1);
3395 $monthdays = $type->get_num_days_in_month($calendardate['year'], $calendardate['mon']);
3396 $date->setTimestamp($tstart);
3397 $date->modify('+' . $monthdays . ' days');
3399 if ($view === 'mini' ||
$view === 'minithree') {
3400 $template = 'core_calendar/calendar_mini';
3402 $template = 'core_calendar/calendar_month';
3406 // We need to extract 1 second to ensure that we don't get into the next day.
3407 $date->modify('-1 second');
3408 $tend = $date->getTimestamp();
3410 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3411 // If parameter is true, return null.
3412 if ($param === true) {
3416 // If parameter is false, return an empty array.
3417 if ($param === false) {
3421 // If the parameter is a scalar value, enclose it in an array.
3422 if (!is_array($param)) {
3426 // No normalisation required.
3428 }, [$calendar->users
, $calendar->groups
, $calendar->courses
, $calendar->categories
]);
3433 $events = \core_calendar\local\api
::get_events(
3449 if ($proxy = $event->get_course_module()) {
3450 $cminfo = $proxy->get_proxied_instance();
3451 return $cminfo->uservisible
;
3454 if ($proxy = $event->get_category()) {
3455 $category = $proxy->get_proxied_instance();
3457 return $category->is_uservisible();
3466 'events' => $events,
3467 'cache' => new \core_calendar\external\
events_related_objects_cache($events),
3472 if ($view == "month" ||
$view == "mini" ||
$view == "minithree") {
3473 $month = new \core_calendar\external\
month_exporter($calendar, $type, $related);
3474 $month->set_includenavigation($includenavigation);
3475 $month->set_initialeventsloaded(!$skipevents);
3476 $month->set_showcoursefilter($view == "month");
3477 $data = $month->export($renderer);
3478 $data->viewingmonth
= true;
3479 } else if ($view == "day") {
3480 $day = new \core_calendar\external\
calendar_day_exporter($calendar, $related);
3481 $data = $day->export($renderer);
3482 $data->viewingday
= true;
3483 $template = 'core_calendar/calendar_day';
3484 } else if ($view == "upcoming" ||
$view == "upcoming_mini") {
3485 $upcoming = new \core_calendar\external\
calendar_upcoming_exporter($calendar, $related);
3486 $data = $upcoming->export($renderer);
3488 if ($view == "upcoming") {
3489 $template = 'core_calendar/calendar_upcoming';
3490 $data->viewingupcoming
= true;
3491 } else if ($view == "upcoming_mini") {
3492 $template = 'core_calendar/calendar_upcoming_mini';
3496 return [$data, $template];
3500 * Request and render event form fragment.
3502 * @param array $args The fragment arguments.
3503 * @return string The rendered mform fragment.
3505 function calendar_output_fragment_event_form($args) {
3506 global $CFG, $OUTPUT, $USER;
3507 require_once($CFG->libdir
. '/grouplib.php');
3510 $eventid = isset($args['eventid']) ?
clean_param($args['eventid'], PARAM_INT
) : null;
3511 $starttime = isset($args['starttime']) ?
clean_param($args['starttime'], PARAM_INT
) : null;
3512 $courseid = (isset($args['courseid']) && $args['courseid'] != SITEID
) ?
clean_param($args['courseid'], PARAM_INT
) : null;
3513 $categoryid = isset($args['categoryid']) ?
clean_param($args['categoryid'], PARAM_INT
) : null;
3515 $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
3516 $context = \context_user
::instance($USER->id
);
3517 $editoroptions = \core_calendar\local\event\forms\create
::build_editor_options($context);
3518 $formoptions = ['editoroptions' => $editoroptions, 'courseid' => $courseid];
3522 parse_str(clean_param($args['formdata'], PARAM_TEXT
), $data);
3523 if (isset($data['description']['itemid'])) {
3524 $draftitemid = $data['description']['itemid'];
3529 $formoptions['starttime'] = $starttime;
3531 // Let's check first which event types user can add.
3532 $eventtypes = calendar_get_allowed_event_types($courseid);
3533 $formoptions['eventtypes'] = $eventtypes;
3535 if (is_null($eventid)) {
3536 if (!empty($courseid)) {
3537 $groupcoursedata = groups_get_course_data($courseid);
3538 $formoptions['groups'] = [];
3539 foreach ($groupcoursedata->groups
as $groupid => $groupdata) {
3540 $formoptions['groups'][$groupid] = $groupdata->name
;
3544 $mform = new \core_calendar\local\event\forms\
create(
3554 // If the user is on course context and is allowed to add course events set the event type default to course.
3555 if (!empty($courseid) && !empty($eventtypes['course'])) {
3556 $data['eventtype'] = 'course';
3557 $data['courseid'] = $courseid;
3558 $data['groupcourseid'] = $courseid;
3559 } else if (!empty($categoryid) && !empty($eventtypes['category'])) {
3560 $data['eventtype'] = 'category';
3561 $data['categoryid'] = $categoryid;
3562 } else if (!empty($groupcoursedata) && !empty($eventtypes['group'])) {
3563 $data['groupcourseid'] = $courseid;
3564 $data['groups'] = $groupcoursedata->groups
;
3566 $mform->set_data($data);
3568 $event = calendar_event
::load($eventid);
3570 if (!calendar_edit_event_allowed($event)) {
3571 print_error('nopermissiontoupdatecalendar');
3574 $mapper = new \core_calendar\local\event\mappers\
create_update_form_mapper();
3575 $eventdata = $mapper->from_legacy_event_to_data($event);
3576 $data = array_merge((array) $eventdata, $data);
3577 $event->count_repeats();
3578 $formoptions['event'] = $event;
3580 if (!empty($event->courseid
)) {
3581 $groupcoursedata = groups_get_course_data($event->courseid
);
3582 $formoptions['groups'] = [];
3583 foreach ($groupcoursedata->groups
as $groupid => $groupdata) {
3584 $formoptions['groups'][$groupid] = $groupdata->name
;
3588 $data['description']['text'] = file_prepare_draft_area(
3590 $event->context
->id
,
3592 'event_description',
3595 $data['description']['text']
3597 $data['description']['itemid'] = $draftitemid;
3599 $mform = new \core_calendar\local\event\forms\
update(
3608 $mform->set_data($data);
3610 // Check to see if this event is part of a subscription or import.
3611 // If so display a warning on edit.
3612 if (isset($event->subscriptionid
) && ($event->subscriptionid
!= null)) {
3613 $renderable = new \core\output\notification
(
3614 get_string('eventsubscriptioneditwarning', 'calendar'),
3615 \core\output\notification
::NOTIFY_INFO
3618 $html .= $OUTPUT->render($renderable);
3623 $mform->is_validated();
3626 $html .= $mform->render();
3631 * Calculate the timestamp from the supplied Gregorian Year, Month, and Day.
3633 * @param int $d The day
3634 * @param int $m The month
3635 * @param int $y The year
3636 * @param int $time The timestamp to use instead of a separate y/m/d.
3637 * @return int The timestamp
3639 function calendar_get_timestamp($d, $m, $y, $time = 0) {
3640 // If a day, month and year were passed then convert it to a timestamp. If these were passed
3641 // then we can assume the day, month and year are passed as Gregorian, as no where in core
3642 // should we be passing these values rather than the time.
3643 if (!empty($d) && !empty($m) && !empty($y)) {
3644 if (checkdate($m, $d, $y)) {
3645 $time = make_timestamp($y, $m, $d);
3649 } else if (empty($time)) {
3657 * Get the calendar footer options.
3659 * @param calendar_information $calendar The calendar information object.
3660 * @return array The data for template and template name.
3662 function calendar_get_footer_options($calendar) {
3663 global $CFG, $USER, $DB, $PAGE;
3665 // Generate hash for iCal link.
3666 $rawhash = $USER->id
. $DB->get_field('user', 'password', ['id' => $USER->id
]) . $CFG->calendar_exportsalt
;
3667 $authtoken = sha1($rawhash);
3669 $renderer = $PAGE->get_renderer('core_calendar');
3670 $footer = new \core_calendar\external\footer_options_exporter
($calendar, $USER->id
, $authtoken);
3671 $data = $footer->export($renderer);
3672 $template = 'core_calendar/footer_options';
3674 return [$data, $template];
3678 * Get the list of potential calendar filter types as a type => name
3683 function calendar_get_filter_types() {
3693 return array_map(function($type) {
3695 'eventtype' => $type,
3696 'name' => get_string("eventtype{$type}", "calendar"),
3698 'key' => 'i/' . $type . 'event',
3699 'component' => 'core'
3705 * Check whether the specified event type is valid.
3707 * @param string $type
3710 function calendar_is_valid_eventtype($type) {
3718 return in_array($type, $validtypes);
3722 * Get event types the user can create event based on categories, courses and groups
3723 * the logged in user belongs to.
3725 * @param int|null $courseid The course id.
3726 * @return array The array of allowed types.
3728 function calendar_get_allowed_event_types(int $courseid = null) {
3729 global $DB, $CFG, $USER;
3739 if (!empty($courseid) && $courseid != SITEID
) {
3740 $context = \context_course
::instance($courseid);
3741 $types['user'] = has_capability('moodle/calendar:manageownentries', $context);
3742 calendar_internal_update_course_and_group_permission($courseid, $context, $types);
3745 if (has_capability('moodle/calendar:manageentries', \context_course
::instance(SITEID
))) {
3746 $types['site'] = true;
3749 if (has_capability('moodle/calendar:manageownentries', \context_system
::instance())) {
3750 $types['user'] = true;
3752 if (core_course_category
::has_manage_capability_on_any()) {
3753 $types['category'] = true;
3756 // We still don't know if the user can create group and course events, so iterate over the courses to find out
3757 // if the user has capabilities in one of the courses.
3758 if ($types['course'] == false ||
$types['group'] == false) {
3759 if ($CFG->calendar_adminseesall
&& has_capability('moodle/calendar:manageentries', context_system
::instance())) {
3760 $sql = "SELECT c.id, " . context_helper
::get_preload_record_columns_sql('ctx') . "
3762 JOIN {context} ctx ON ctx.contextlevel = ? AND ctx.instanceid = c.id
3764 SELECT DISTINCT courseid FROM {groups}
3766 $courseswithgroups = $DB->get_recordset_sql($sql, [CONTEXT_COURSE
]);
3767 foreach ($courseswithgroups as $course) {
3768 context_helper
::preload_from_record($course);
3769 $context = context_course
::instance($course->id
);
3771 if (has_capability('moodle/calendar:manageentries', $context)) {
3772 if (has_any_capability(['moodle/site:accessallgroups', 'moodle/calendar:managegroupentries'], $context)) {
3773 // The user can manage group entries or access any group.
3774 $types['group'] = true;
3775 $types['course'] = true;
3780 $courseswithgroups->close();
3782 if (false === $types['course']) {
3783 // Course is still not confirmed. There may have been no courses with a group in them.
3784 $ctxfields = context_helper
::get_preload_record_columns_sql('ctx');
3786 c.id, c.visible, {$ctxfields}
3788 JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
3790 'contextlevel' => CONTEXT_COURSE
,
3792 $courses = $DB->get_recordset_sql($sql, $params);
3793 foreach ($courses as $course) {
3794 context_helper
::preload_from_record($course);
3795 $context = context_course
::instance($course->id
);
3796 if (has_capability('moodle/calendar:manageentries', $context)) {
3797 $types['course'] = true;
3805 $courses = calendar_get_default_courses(null, 'id');
3806 if (empty($courses)) {
3810 $courseids = array_map(function($c) {
3814 // Check whether the user has access to create events within courses which have groups.
3815 list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED
);
3816 $sql = "SELECT c.id, " . context_helper
::get_preload_record_columns_sql('ctx') . "
3818 JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3820 AND c.id IN (SELECT DISTINCT courseid FROM {groups})";
3821 $params['contextlevel'] = CONTEXT_COURSE
;
3822 $courseswithgroups = $DB->get_recordset_sql($sql, $params);
3823 foreach ($courseswithgroups as $coursewithgroup) {
3824 context_helper
::preload_from_record($coursewithgroup);
3825 $context = context_course
::instance($coursewithgroup->id
);
3827 calendar_internal_update_course_and_group_permission($coursewithgroup->id
, $context, $types);
3829 // Okay, course and group event types are allowed, no need to keep the loop iteration.
3830 if ($types['course'] == true && $types['group'] == true) {
3834 $courseswithgroups->close();
3836 if (false === $types['course']) {
3837 list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED
);
3838 $contextsql = "SELECT c.id, " . context_helper
::get_preload_record_columns_sql('ctx') . "
3840 JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3842 $params['contextlevel'] = CONTEXT_COURSE
;
3843 $contextrecords = $DB->get_recordset_sql($contextsql, $params);
3844 foreach ($contextrecords as $course) {
3845 context_helper
::preload_from_record($course);
3846 $coursecontext = context_course
::instance($course->id
);
3847 if (has_capability('moodle/calendar:manageentries', $coursecontext)
3848 && ($courseid == $course->id ||
empty($courseid))) {
3849 $types['course'] = true;
3853 $contextrecords->close();
3863 * Given a course id, and context, updates the permission types array to add the 'course' or 'group'
3864 * permission if it is relevant for that course.
3866 * For efficiency, if they already have 'course' or 'group' then it skips checks.
3868 * Do not call this function directly, it is only for use by calendar_get_allowed_event_types().
3870 * @param int $courseid Course id
3871 * @param context $context Context for that course
3872 * @param array $types Current permissions
3874 function calendar_internal_update_course_and_group_permission(int $courseid, context
$context, array &$types) {
3875 if (!$types['course']) {
3876 // If they have manageentries permission on the course, then they can update this course.
3877 if (has_capability('moodle/calendar:manageentries', $context)) {
3878 $types['course'] = true;
3881 // To update group events they must have EITHER manageentries OR managegroupentries.
3882 if (!$types['group'] && (has_capability('moodle/calendar:manageentries', $context) ||
3883 has_capability('moodle/calendar:managegroupentries', $context))) {
3884 // And they also need for a group to exist on the course.
3885 $groups = groups_get_all_groups($courseid);
3886 if (!empty($groups)) {
3887 // And either accessallgroups, or belong to one of the groups.
3888 if (has_capability('moodle/site:accessallgroups', $context)) {
3889 $types['group'] = true;
3891 foreach ($groups as $group) {
3892 if (groups_is_member($group->id
)) {
3893 $types['group'] = true;