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 - Global calendar event types
75 define('CALENDAR_EVENT_GLOBAL', 1);
78 * CALENDAR_EVENT_COURSE - Course calendar event types
80 define('CALENDAR_EVENT_COURSE', 2);
83 * CALENDAR_EVENT_GROUP - group calendar event types
85 define('CALENDAR_EVENT_GROUP', 4);
88 * CALENDAR_EVENT_USER - user calendar event types
90 define('CALENDAR_EVENT_USER', 8);
93 * CALENDAR_EVENT_COURSECAT - Course category calendar event types
95 define('CALENDAR_EVENT_COURSECAT', 16);
98 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
100 define('CALENDAR_IMPORT_FROM_FILE', 0);
103 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
105 define('CALENDAR_IMPORT_FROM_URL', 1);
108 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
110 define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
113 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
115 define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
118 * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
120 define('CALENDAR_SUBSCRIPTION_UPDATE', 1);
123 * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
125 define('CALENDAR_SUBSCRIPTION_REMOVE', 2);
128 * CALENDAR_EVENT_USER_OVERRIDE_PRIORITY - Constant for the user override priority.
130 define('CALENDAR_EVENT_USER_OVERRIDE_PRIORITY', 0);
133 * CALENDAR_EVENT_TYPE_STANDARD - Standard events.
135 define('CALENDAR_EVENT_TYPE_STANDARD', 0);
138 * CALENDAR_EVENT_TYPE_ACTION - Action events.
140 define('CALENDAR_EVENT_TYPE_ACTION', 1);
143 * Manage calendar events.
145 * This class provides the required functionality in order to manage calendar events.
146 * It was introduced as part of Moodle 2.0 and was created in order to provide a
147 * better framework for dealing with calendar events in particular regard to file
148 * handling through the new file API.
150 * @package core_calendar
152 * @copyright 2009 Sam Hemelryk
153 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
155 * @property int $id The id within the event table
156 * @property string $name The name of the event
157 * @property string $description The description of the event
158 * @property int $format The format of the description FORMAT_?
159 * @property int $courseid The course the event is associated with (0 if none)
160 * @property int $groupid The group the event is associated with (0 if none)
161 * @property int $userid The user the event is associated with (0 if none)
162 * @property int $repeatid If this is a repeated event this will be set to the
164 * @property string $modulename If added by a module this will be the module name
165 * @property int $instance If added by a module this will be the module instance
166 * @property string $eventtype The event type
167 * @property int $timestart The start time as a timestamp
168 * @property int $timeduration The duration of the event in seconds
169 * @property int $visible 1 if the event is visible
170 * @property int $uuid ?
171 * @property int $sequence ?
172 * @property int $timemodified The time last modified as a timestamp
174 class calendar_event
{
176 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
177 protected $properties = null;
179 /** @var string The converted event discription with file paths resolved.
180 * This gets populated when someone requests description for the first time */
181 protected $_description = null;
183 /** @var array The options to use with this description editor */
184 protected $editoroptions = array(
186 'forcehttps' => false,
189 'trusttext' => false);
191 /** @var object The context to use with the description editor */
192 protected $editorcontext = null;
195 * Instantiates a new event and optionally populates its properties with the data provided.
197 * @param \stdClass $data Optional. An object containing the properties to for
200 public function __construct($data = null) {
203 // First convert to object if it is not already (should either be object or assoc array).
204 if (!is_object($data)) {
205 $data = (object) $data;
208 $this->editoroptions
['maxbytes'] = $CFG->maxbytes
;
210 $data->eventrepeats
= 0;
212 if (empty($data->id
)) {
216 if (!empty($data->subscriptionid
)) {
217 $data->subscription
= calendar_get_subscription($data->subscriptionid
);
220 // Default to a user event.
221 if (empty($data->eventtype
)) {
222 $data->eventtype
= 'user';
225 // Default to the current user.
226 if (empty($data->userid
)) {
227 $data->userid
= $USER->id
;
230 if (!empty($data->timeduration
) && is_array($data->timeduration
)) {
231 $data->timeduration
= make_timestamp(
232 $data->timeduration
['year'], $data->timeduration
['month'], $data->timeduration
['day'],
233 $data->timeduration
['hour'], $data->timeduration
['minute']) - $data->timestart
;
236 if (!empty($data->description
) && is_array($data->description
)) {
237 $data->format
= $data->description
['format'];
238 $data->description
= $data->description
['text'];
239 } else if (empty($data->description
)) {
240 $data->description
= '';
241 $data->format
= editors_get_preferred_format();
244 // Ensure form is defaulted correctly.
245 if (empty($data->format
)) {
246 $data->format
= editors_get_preferred_format();
249 $this->properties
= $data;
255 * Attempts to call a set_$key method if one exists otherwise falls back
256 * to simply set the property.
258 * @param string $key property name
259 * @param mixed $value value of the property
261 public function __set($key, $value) {
262 if (method_exists($this, 'set_'.$key)) {
263 $this->{'set_'.$key}($value);
265 $this->properties
->{$key} = $value;
271 * Attempts to call a get_$key method to return the property and ralls over
272 * to return the raw property.
274 * @param string $key property name
275 * @return mixed property value
276 * @throws \coding_exception
278 public function __get($key) {
279 if (method_exists($this, 'get_'.$key)) {
280 return $this->{'get_'.$key}();
282 if (!property_exists($this->properties
, $key)) {
283 throw new \
coding_exception('Undefined property requested');
285 return $this->properties
->{$key};
289 * Magic isset method.
291 * PHP needs an isset magic method if you use the get magic method and
292 * still want empty calls to work.
294 * @param string $key $key property name
295 * @return bool|mixed property value, false if property is not exist
297 public function __isset($key) {
298 return !empty($this->properties
->{$key});
302 * Calculate the context value needed for an event.
304 * Event's type can be determine by the available value store in $data
305 * It is important to check for the existence of course/courseid to determine
307 * Default value is set to CONTEXT_USER
309 * @return \stdClass The context object.
311 protected function calculate_context() {
315 if (isset($this->properties
->categoryid
) && $this->properties
->categoryid
> 0) {
316 $context = \context_coursecat
::instance($this->properties
->categoryid
);
317 } else if (isset($this->properties
->courseid
) && $this->properties
->courseid
> 0) {
318 $context = \context_course
::instance($this->properties
->courseid
);
319 } else if (isset($this->properties
->course
) && $this->properties
->course
> 0) {
320 $context = \context_course
::instance($this->properties
->course
);
321 } else if (isset($this->properties
->groupid
) && $this->properties
->groupid
> 0) {
322 $group = $DB->get_record('groups', array('id' => $this->properties
->groupid
));
323 $context = \context_course
::instance($group->courseid
);
324 } else if (isset($this->properties
->userid
) && $this->properties
->userid
> 0
325 && $this->properties
->userid
== $USER->id
) {
326 $context = \context_user
::instance($this->properties
->userid
);
327 } else if (isset($this->properties
->userid
) && $this->properties
->userid
> 0
328 && $this->properties
->userid
!= $USER->id
&&
329 isset($this->properties
->instance
) && $this->properties
->instance
> 0) {
330 $cm = get_coursemodule_from_instance($this->properties
->modulename
, $this->properties
->instance
, 0,
332 $context = \context_course
::instance($cm->course
);
334 $context = \context_user
::instance($this->properties
->userid
);
341 * Returns the context for this event. The context is calculated
342 * the first time is is requested and then stored in a member
343 * variable to be returned each subsequent time.
345 * This is a magical getter function that will be called when
346 * ever the context property is accessed, e.g. $event->context.
350 protected function get_context() {
351 if (!isset($this->properties
->context
)) {
352 $this->properties
->context
= $this->calculate_context();
355 return $this->properties
->context
;
359 * Returns an array of editoroptions for this event.
361 * @return array event editor options
363 protected function get_editoroptions() {
364 return $this->editoroptions
;
368 * Returns an event description: Called by __get
369 * Please use $blah = $event->description;
371 * @return string event description
373 protected function get_description() {
376 require_once($CFG->libdir
. '/filelib.php');
378 if ($this->_description
=== null) {
379 // Check if we have already resolved the context for this event.
380 if ($this->editorcontext
=== null) {
381 // Switch on the event type to decide upon the appropriate context to use for this event.
382 $this->editorcontext
= $this->get_context();
383 if (!calendar_is_valid_eventtype($this->properties
->eventtype
)) {
384 return clean_text($this->properties
->description
, $this->properties
->format
);
388 // Work out the item id for the editor, if this is a repeated event
389 // then the files will be associated with the original.
390 if (!empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
391 $itemid = $this->properties
->repeatid
;
393 $itemid = $this->properties
->id
;
396 // Convert file paths in the description so that things display correctly.
397 $this->_description
= file_rewrite_pluginfile_urls($this->properties
->description
, 'pluginfile.php',
398 $this->editorcontext
->id
, 'calendar', 'event_description', $itemid);
399 // Clean the text so no nasties get through.
400 $this->_description
= clean_text($this->_description
, $this->properties
->format
);
403 // Finally return the description.
404 return $this->_description
;
408 * Return the number of repeat events there are in this events series.
410 * @return int number of event repeated
412 public function count_repeats() {
414 if (!empty($this->properties
->repeatid
)) {
415 $this->properties
->eventrepeats
= $DB->count_records('event',
416 array('repeatid' => $this->properties
->repeatid
));
417 // We don't want to count ourselves.
418 $this->properties
->eventrepeats
--;
420 return $this->properties
->eventrepeats
;
424 * Update or create an event within the database
426 * Pass in a object containing the event properties and this function will
427 * insert it into the database and deal with any associated files
429 * Capability checking should be performed if the user is directly manipulating the event
430 * and no other capability has been tested. However if the event is not being manipulated
431 * directly by the user and another capability has been checked for them to do this then
432 * capabilites should not be checked.
434 * For example if a user is editing an event in the calendar the check should be true,
435 * but if you are updating an event in an activities settings are changed then the calendar
436 * capabilites should not be checked.
438 * @see self::create()
439 * @see self::update()
441 * @param \stdClass $data object of event
442 * @param bool $checkcapability If Moodle should check the user can manage the calendar events for this call or not.
443 * @return bool event updated
445 public function update($data, $checkcapability=true) {
448 foreach ($data as $key => $value) {
449 $this->properties
->$key = $value;
452 $this->properties
->timemodified
= time();
453 $usingeditor = (!empty($this->properties
->description
) && is_array($this->properties
->description
));
455 // Prepare event data.
457 'context' => $this->get_context(),
458 'objectid' => $this->properties
->id
,
460 'repeatid' => empty($this->properties
->repeatid
) ?
0 : $this->properties
->repeatid
,
461 'timestart' => $this->properties
->timestart
,
462 'name' => $this->properties
->name
466 if (empty($this->properties
->id
) ||
$this->properties
->id
< 1) {
467 if ($checkcapability) {
468 if (!calendar_add_event_allowed($this->properties
)) {
469 print_error('nopermissiontoupdatecalendar');
474 switch ($this->properties
->eventtype
) {
476 $this->properties
->courseid
= 0;
477 $this->properties
->course
= 0;
478 $this->properties
->groupid
= 0;
479 $this->properties
->userid
= $USER->id
;
482 $this->properties
->courseid
= SITEID
;
483 $this->properties
->course
= SITEID
;
484 $this->properties
->groupid
= 0;
485 $this->properties
->userid
= $USER->id
;
488 $this->properties
->groupid
= 0;
489 $this->properties
->userid
= $USER->id
;
492 $this->properties
->groupid
= 0;
493 $this->properties
->category
= 0;
494 $this->properties
->userid
= $USER->id
;
497 $this->properties
->userid
= $USER->id
;
500 // We should NEVER get here, but just incase we do lets fail gracefully.
501 $usingeditor = false;
505 // If we are actually using the editor, we recalculate the context because some default values
506 // were set when calculate_context() was called from the constructor.
508 $this->properties
->context
= $this->calculate_context();
509 $this->editorcontext
= $this->get_context();
512 $editor = $this->properties
->description
;
513 $this->properties
->format
= $this->properties
->description
['format'];
514 $this->properties
->description
= $this->properties
->description
['text'];
517 // Insert the event into the database.
518 $this->properties
->id
= $DB->insert_record('event', $this->properties
);
521 $this->properties
->description
= file_save_draft_area_files(
523 $this->editorcontext
->id
,
526 $this->properties
->id
,
527 $this->editoroptions
,
529 $this->editoroptions
['forcehttps']);
530 $DB->set_field('event', 'description', $this->properties
->description
,
531 array('id' => $this->properties
->id
));
534 // Log the event entry.
535 $eventargs['objectid'] = $this->properties
->id
;
536 $eventargs['context'] = $this->get_context();
537 $event = \core\event\calendar_event_created
::create($eventargs);
540 $repeatedids = array();
542 if (!empty($this->properties
->repeat
)) {
543 $this->properties
->repeatid
= $this->properties
->id
;
544 $DB->set_field('event', 'repeatid', $this->properties
->repeatid
, array('id' => $this->properties
->id
));
546 $eventcopy = clone($this->properties
);
547 unset($eventcopy->id
);
549 $timestart = new \
DateTime('@' . $eventcopy->timestart
);
550 $timestart->setTimezone(\core_date
::get_user_timezone_object());
552 for ($i = 1; $i < $eventcopy->repeats
; $i++
) {
554 $timestart->add(new \
DateInterval('P7D'));
555 $eventcopy->timestart
= $timestart->getTimestamp();
557 // Get the event id for the log record.
558 $eventcopyid = $DB->insert_record('event', $eventcopy);
560 // If the context has been set delete all associated files.
562 $fs = get_file_storage();
563 $files = $fs->get_area_files($this->editorcontext
->id
, 'calendar', 'event_description',
564 $this->properties
->id
);
565 foreach ($files as $file) {
566 $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
570 $repeatedids[] = $eventcopyid;
573 $eventargs['objectid'] = $eventcopyid;
574 $eventargs['other']['timestart'] = $eventcopy->timestart
;
575 $event = \core\event\calendar_event_created
::create($eventargs);
583 if ($checkcapability) {
584 if (!calendar_edit_event_allowed($this->properties
)) {
585 print_error('nopermissiontoupdatecalendar');
590 if ($this->editorcontext
!== null) {
591 $this->properties
->description
= file_save_draft_area_files(
592 $this->properties
->description
['itemid'],
593 $this->editorcontext
->id
,
596 $this->properties
->id
,
597 $this->editoroptions
,
598 $this->properties
->description
['text'],
599 $this->editoroptions
['forcehttps']);
601 $this->properties
->format
= $this->properties
->description
['format'];
602 $this->properties
->description
= $this->properties
->description
['text'];
606 $event = $DB->get_record('event', array('id' => $this->properties
->id
));
608 $updaterepeated = (!empty($this->properties
->repeatid
) && !empty($this->properties
->repeateditall
));
610 if ($updaterepeated) {
612 if ($this->properties
->timestart
!= $event->timestart
) {
613 $timestartoffset = $this->properties
->timestart
- $event->timestart
;
614 $sql = "UPDATE {event}
617 timestart = timestart + ?,
623 // Note: Group and course id may not be set. If not, keep their current values.
625 $this->properties
->name
,
626 $this->properties
->description
,
628 $this->properties
->timeduration
,
630 isset($this->properties
->groupid
) ?
$this->properties
->groupid
: $event->groupid
,
631 isset($this->properties
->courseid
) ?
$this->properties
->courseid
: $event->courseid
,
635 $sql = "UPDATE {event}
643 // Note: Group and course id may not be set. If not, keep their current values.
645 $this->properties
->name
,
646 $this->properties
->description
,
647 $this->properties
->timeduration
,
649 isset($this->properties
->groupid
) ?
$this->properties
->groupid
: $event->groupid
,
650 isset($this->properties
->courseid
) ?
$this->properties
->courseid
: $event->courseid
,
654 $DB->execute($sql, $params);
656 // Trigger an update event for each of the calendar event.
657 $events = $DB->get_records('event', array('repeatid' => $event->repeatid
), '', '*');
658 foreach ($events as $calendarevent) {
659 $eventargs['objectid'] = $calendarevent->id
;
660 $eventargs['other']['timestart'] = $calendarevent->timestart
;
661 $event = \core\event\calendar_event_updated
::create($eventargs);
662 $event->add_record_snapshot('event', $calendarevent);
666 $DB->update_record('event', $this->properties
);
667 $event = self
::load($this->properties
->id
);
668 $this->properties
= $event->properties();
670 // Trigger an update event.
671 $event = \core\event\calendar_event_updated
::create($eventargs);
672 $event->add_record_snapshot('event', $this->properties
);
681 * Deletes an event and if selected an repeated events in the same series
683 * This function deletes an event, any associated events if $deleterepeated=true,
684 * and cleans up any files associated with the events.
686 * @see self::delete()
688 * @param bool $deleterepeated delete event repeatedly
689 * @return bool succession of deleting event
691 public function delete($deleterepeated = false) {
694 // If $this->properties->id is not set then something is wrong.
695 if (empty($this->properties
->id
)) {
696 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER
);
699 $calevent = $DB->get_record('event', array('id' => $this->properties
->id
), '*', MUST_EXIST
);
701 $DB->delete_records('event', array('id' => $this->properties
->id
));
703 // Trigger an event for the delete action.
705 'context' => $this->get_context(),
706 'objectid' => $this->properties
->id
,
708 'repeatid' => empty($this->properties
->repeatid
) ?
0 : $this->properties
->repeatid
,
709 'timestart' => $this->properties
->timestart
,
710 'name' => $this->properties
->name
712 $event = \core\event\calendar_event_deleted
::create($eventargs);
713 $event->add_record_snapshot('event', $calevent);
716 // If we are deleting parent of a repeated event series, promote the next event in the series as parent.
717 if (($this->properties
->id
== $this->properties
->repeatid
) && !$deleterepeated) {
718 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC",
719 array($this->properties
->id
), IGNORE_MULTIPLE
);
720 if (!empty($newparent)) {
721 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?",
722 array($newparent, $this->properties
->id
));
723 // Get all records where the repeatid is the same as the event being removed.
724 $events = $DB->get_records('event', array('repeatid' => $newparent));
725 // For each of the returned events trigger an update event.
726 foreach ($events as $calendarevent) {
727 // Trigger an event for the update.
728 $eventargs['objectid'] = $calendarevent->id
;
729 $eventargs['other']['timestart'] = $calendarevent->timestart
;
730 $event = \core\event\calendar_event_updated
::create($eventargs);
731 $event->add_record_snapshot('event', $calendarevent);
737 // If the editor context hasn't already been set then set it now.
738 if ($this->editorcontext
=== null) {
739 $this->editorcontext
= $this->get_context();
742 // If the context has been set delete all associated files.
743 if ($this->editorcontext
!== null) {
744 $fs = get_file_storage();
745 $files = $fs->get_area_files($this->editorcontext
->id
, 'calendar', 'event_description', $this->properties
->id
);
746 foreach ($files as $file) {
751 // If we need to delete repeated events then we will fetch them all and delete one by one.
752 if ($deleterepeated && !empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
753 // Get all records where the repeatid is the same as the event being removed.
754 $events = $DB->get_records('event', array('repeatid' => $this->properties
->repeatid
));
755 // For each of the returned events populate an event object and call delete.
756 // make sure the arg passed is false as we are already deleting all repeats.
757 foreach ($events as $event) {
758 $event = new calendar_event($event);
759 $event->delete(false);
767 * Fetch all event properties.
769 * This function returns all of the events properties as an object and optionally
770 * can prepare an editor for the description field at the same time. This is
771 * designed to work when the properties are going to be used to set the default
772 * values of a moodle forms form.
774 * @param bool $prepareeditor If set to true a editor is prepared for use with
775 * the mforms editor element. (for description)
776 * @return \stdClass Object containing event properties
778 public function properties($prepareeditor = false) {
781 // First take a copy of the properties. We don't want to actually change the
782 // properties or we'd forever be converting back and forwards between an
783 // editor formatted description and not.
784 $properties = clone($this->properties
);
785 // Clean the description here.
786 $properties->description
= clean_text($properties->description
, $properties->format
);
788 // If set to true we need to prepare the properties for use with an editor
789 // and prepare the file area.
790 if ($prepareeditor) {
792 // We may or may not have a property id. If we do then we need to work
793 // out the context so we can copy the existing files to the draft area.
794 if (!empty($properties->id
)) {
796 if ($properties->eventtype
=== 'site') {
798 $this->editorcontext
= $this->get_context();
799 } else if ($properties->eventtype
=== 'user') {
801 $this->editorcontext
= $this->get_context();
802 } else if ($properties->eventtype
=== 'group' ||
$properties->eventtype
=== 'course') {
803 // First check the course is valid.
804 $course = $DB->get_record('course', array('id' => $properties->courseid
));
806 print_error('invalidcourse');
809 $this->editorcontext
= $this->get_context();
810 // We have a course and are within the course context so we had
811 // better use the courses max bytes value.
812 $this->editoroptions
['maxbytes'] = $course->maxbytes
;
813 } else if ($properties->eventtype
=== 'category') {
814 // First check the course is valid.
815 \core_course_category
::get($properties->categoryid
, MUST_EXIST
, true);
817 $this->editorcontext
= $this->get_context();
819 // If we get here we have a custom event type as used by some
820 // modules. In this case the event will have been added by
821 // code and we won't need the editor.
822 $this->editoroptions
['maxbytes'] = 0;
823 $this->editoroptions
['maxfiles'] = 0;
826 if (empty($this->editorcontext
) ||
empty($this->editorcontext
->id
)) {
829 // Get the context id that is what we really want.
830 $contextid = $this->editorcontext
->id
;
834 // If we get here then this is a new event in which case we don't need a
835 // context as there is no existing files to copy to the draft area.
839 // If the contextid === false we don't support files so no preparing
841 if ($contextid !== false) {
842 // Just encase it has already been submitted.
843 $draftiddescription = file_get_submitted_draft_itemid('description');
844 // Prepare the draft area, this copies existing files to the draft area as well.
845 $properties->description
= file_prepare_draft_area($draftiddescription, $contextid, 'calendar',
846 'event_description', $properties->id
, $this->editoroptions
, $properties->description
);
848 $draftiddescription = 0;
851 // Structure the description field as the editor requires.
852 $properties->description
= array('text' => $properties->description
, 'format' => $properties->format
,
853 'itemid' => $draftiddescription);
856 // Finally return the properties.
861 * Toggles the visibility of an event
863 * @param null|bool $force If it is left null the events visibility is flipped,
864 * If it is false the event is made hidden, if it is true it
866 * @return bool if event is successfully updated, toggle will be visible
868 public function toggle_visibility($force = null) {
871 // Set visible to the default if it is not already set.
872 if (empty($this->properties
->visible
)) {
873 $this->properties
->visible
= 1;
876 if ($force === true ||
($force !== false && $this->properties
->visible
== 0)) {
877 // Make this event visible.
878 $this->properties
->visible
= 1;
880 // Make this event hidden.
881 $this->properties
->visible
= 0;
884 // Update the database to reflect this change.
885 $success = $DB->set_field('event', 'visible', $this->properties
->visible
, array('id' => $this->properties
->id
));
886 $calendarevent = $DB->get_record('event', array('id' => $this->properties
->id
), '*', MUST_EXIST
);
888 // Prepare event data.
890 'context' => $this->get_context(),
891 'objectid' => $this->properties
->id
,
893 'repeatid' => empty($this->properties
->repeatid
) ?
0 : $this->properties
->repeatid
,
894 'timestart' => $this->properties
->timestart
,
895 'name' => $this->properties
->name
898 $event = \core\event\calendar_event_updated
::create($eventargs);
899 $event->add_record_snapshot('event', $calendarevent);
906 * Returns an event object when provided with an event id.
908 * This function makes use of MUST_EXIST, if the event id passed in is invalid
909 * it will result in an exception being thrown.
911 * @param int|object $param event object or event id
912 * @return calendar_event
914 public static function load($param) {
916 if (is_object($param)) {
917 $event = new calendar_event($param);
919 $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST
);
920 $event = new calendar_event($event);
926 * Creates a new event and returns an event object.
928 * Capability checking should be performed if the user is directly creating the event
929 * and no other capability has been tested. However if the event is not being created
930 * directly by the user and another capability has been checked for them to do this then
931 * capabilites should not be checked.
933 * For example if a user is creating an event in the calendar the check should be true,
934 * but if you are creating an event in an activity when it is created then the calendar
935 * capabilites should not be checked.
937 * @param \stdClass|array $properties An object containing event properties
938 * @param bool $checkcapability If Moodle should check the user can manage the calendar events for this call or not.
939 * @throws \coding_exception
941 * @return calendar_event|bool The event object or false if it failed
943 public static function create($properties, $checkcapability = true) {
944 if (is_array($properties)) {
945 $properties = (object)$properties;
947 if (!is_object($properties)) {
948 throw new \
coding_exception('When creating an event properties should be either an object or an assoc array');
950 $event = new calendar_event($properties);
951 if ($event->update($properties, $checkcapability)) {
959 * Format the text using the external API.
961 * This function should we used when text formatting is required in external functions.
963 * @return array an array containing the text formatted and the text format
965 public function format_external_text() {
967 if ($this->editorcontext
=== null) {
968 // Switch on the event type to decide upon the appropriate context to use for this event.
969 $this->editorcontext
= $this->get_context();
971 if (!calendar_is_valid_eventtype($this->properties
->eventtype
)) {
972 // We don't have a context here, do a normal format_text.
973 return external_format_text($this->properties
->description
, $this->properties
->format
, $this->editorcontext
->id
);
977 // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
978 if (!empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
979 $itemid = $this->properties
->repeatid
;
981 $itemid = $this->properties
->id
;
984 return external_format_text($this->properties
->description
, $this->properties
->format
, $this->editorcontext
->id
,
985 'calendar', 'event_description', $itemid);
990 * Calendar information class
992 * This class is used simply to organise the information pertaining to a calendar
993 * and is used primarily to make information easily available.
995 * @package core_calendar
997 * @copyright 2010 Sam Hemelryk
998 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1000 class calendar_information
{
1003 * @var int The timestamp
1005 * Rather than setting the day, month and year we will set a timestamp which will be able
1006 * to be used by multiple calendars.
1010 /** @var int A course id */
1011 public $courseid = null;
1013 /** @var array An array of categories */
1014 public $categories = array();
1016 /** @var int The current category */
1017 public $categoryid = null;
1019 /** @var array An array of courses */
1020 public $courses = array();
1022 /** @var array An array of groups */
1023 public $groups = array();
1025 /** @var array An array of users */
1026 public $users = array();
1028 /** @var context The anticipated context that the calendar is viewed in */
1029 public $context = null;
1032 * Creates a new instance
1034 * @param int $day the number of the day
1035 * @param int $month the number of the month
1036 * @param int $year the number of the year
1037 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
1038 * and $calyear to support multiple calendars
1040 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
1041 // If a day, month and year were passed then convert it to a timestamp. If these were passed
1042 // then we can assume the day, month and year are passed as Gregorian, as no where in core
1043 // should we be passing these values rather than the time. This is done for BC.
1044 if (!empty($day) ||
!empty($month) ||
!empty($year)) {
1045 $date = usergetdate(time());
1047 $day = $date['mday'];
1049 if (empty($month)) {
1050 $month = $date['mon'];
1053 $year = $date['year'];
1055 if (checkdate($month, $day, $year)) {
1056 $time = make_timestamp($year, $month, $day);
1062 $this->set_time($time);
1066 * Creates and set up a instance.
1068 * @param int $time the unixtimestamp representing the date we want to view.
1069 * @param int $courseid The ID of the course the user wishes to view.
1070 * @param int $categoryid The ID of the category the user wishes to view
1071 * If a courseid is specified, this value is ignored.
1072 * @return calendar_information
1074 public static function create($time, int $courseid, int $categoryid = null) : calendar_information
{
1075 $calendar = new static(0, 0, 0, $time);
1076 if ($courseid != SITEID
&& !empty($courseid)) {
1077 // Course ID must be valid and existing.
1078 $course = get_course($courseid);
1079 $calendar->context
= context_course
::instance($course->id
);
1081 if (!$course->visible
&& !is_role_switched($course->id
)) {
1082 require_capability('moodle/course:viewhiddencourses', $calendar->context
);
1085 $courses = [$course->id
=> $course];
1086 $category = (\core_course_category
::get($course->category
, MUST_EXIST
, true))->get_db_record();
1087 } else if (!empty($categoryid)) {
1088 $course = get_site();
1089 $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1091 // Filter available courses to those within this category or it's children.
1092 $ids = [$categoryid];
1093 $category = \core_course_category
::get($categoryid);
1094 $ids = array_merge($ids, array_keys($category->get_children()));
1095 $courses = array_filter($courses, function($course) use ($ids) {
1096 return array_search($course->category
, $ids) !== false;
1098 $category = $category->get_db_record();
1100 $calendar->context
= context_coursecat
::instance($categoryid);
1102 $course = get_site();
1103 $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1106 $calendar->context
= context_system
::instance();
1109 $calendar->set_sources($course, $courses, $category);
1115 * Set the time period of this instance.
1117 * @param int $time the unixtimestamp representing the date we want to view.
1120 public function set_time($time = null) {
1122 $this->time
= time();
1124 $this->time
= $time;
1131 * Initialize calendar information
1134 * @param stdClass $course object
1135 * @param array $coursestoload An array of courses [$course->id => $course]
1136 * @param bool $ignorefilters options to use filter
1138 public function prepare_for_view(stdClass
$course, array $coursestoload, $ignorefilters = false) {
1139 debugging('The prepare_for_view() function has been deprecated. Please update your code to use set_sources()',
1141 $this->set_sources($course, $coursestoload);
1145 * Set the sources for events within the calendar.
1147 * If no category is provided, then the category path for the current
1148 * course will be used.
1150 * @param stdClass $course The current course being viewed.
1151 * @param stdClass[] $courses The list of all courses currently accessible.
1152 * @param stdClass $category The current category to show.
1154 public function set_sources(stdClass
$course, array $courses, stdClass
$category = null) {
1157 // A cousre must always be specified.
1158 $this->course
= $course;
1159 $this->courseid
= $course->id
;
1161 list($courseids, $group, $user) = calendar_set_filters($courses);
1162 $this->courses
= $courseids;
1163 $this->groups
= $group;
1164 $this->users
= $user;
1166 // Do not show category events by default.
1167 $this->categoryid
= null;
1168 $this->categories
= null;
1170 // Determine the correct category information to show.
1171 // When called with a course, the category of that course is usually included too.
1172 // When a category was specifically requested, it should be requested with the site id.
1173 if (SITEID
!== $this->courseid
) {
1174 // A specific course was requested.
1175 // Fetch the category that this course is in, along with all parents.
1176 // Do not include child categories of this category, as the user many not have enrolments in those siblings or children.
1177 $category = \core_course_category
::get($course->category
, MUST_EXIST
, true);
1178 $this->categoryid
= $category->id
;
1180 $this->categories
= $category->get_parents();
1181 $this->categories
[] = $category->id
;
1182 } else if (null !== $category && $category->id
> 0) {
1183 // A specific category was requested.
1184 // Fetch all parents of this category, along with all children too.
1185 $category = \core_course_category
::get($category->id
);
1186 $this->categoryid
= $category->id
;
1188 // Build the category list.
1189 // This includes the current category.
1190 $this->categories
= $category->get_parents();
1191 $this->categories
[] = $category->id
;
1192 $this->categories
= array_merge($this->categories
, $category->get_all_children_ids());
1193 } else if (SITEID
=== $this->courseid
) {
1194 // The site was requested.
1195 // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
1197 // Grab the list of categories that this user has courses in.
1198 $coursecategories = array_flip(array_map(function($course) {
1199 return $course->category
;
1202 $calcatcache = cache
::make('core', 'calendar_categories');
1203 $this->categories
= $calcatcache->get('site');
1204 if ($this->categories
=== false) {
1205 // Use the category id as the key in the following array. That way we do not have to remove duplicates.
1207 foreach (\core_course_category
::get_all() as $category) {
1208 if (isset($coursecategories[$category->id
]) ||
1209 has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
1210 // If the user has access to a course in this category or can manage the category,
1211 // then they can see all parent categories too.
1212 $categories[$category->id
] = true;
1213 foreach ($category->get_parents() as $catid) {
1214 $categories[$catid] = true;
1218 $this->categories
= array_keys($categories);
1219 $calcatcache->set('site', $this->categories
);
1225 * Ensures the date for the calendar is correct and either sets it to now
1226 * or throws a moodle_exception if not
1228 * @param bool $defaultonow use current time
1229 * @throws moodle_exception
1230 * @return bool validation of checkdate
1232 public function checkdate($defaultonow = true) {
1233 if (!checkdate($this->month
, $this->day
, $this->year
)) {
1235 $now = usergetdate(time());
1236 $this->day
= intval($now['mday']);
1237 $this->month
= intval($now['mon']);
1238 $this->year
= intval($now['year']);
1241 throw new moodle_exception('invaliddate');
1248 * Gets todays timestamp for the calendar
1250 * @return int today timestamp
1252 public function timestamp_today() {
1256 * Gets tomorrows timestamp for the calendar
1258 * @return int tomorrow timestamp
1260 public function timestamp_tomorrow() {
1261 return strtotime('+1 day', $this->time
);
1264 * Adds the pretend blocks for the calendar
1266 * @param core_calendar_renderer $renderer
1267 * @param bool $showfilters display filters, false is set as default
1268 * @param string|null $view preference view options (eg: day, month, upcoming)
1270 public function add_sidecalendar_blocks(core_calendar_renderer
$renderer, $showfilters=false, $view=null) {
1272 $filters = new block_contents();
1273 $filters->content
= $renderer->event_filter();
1274 $filters->footer
= '';
1275 $filters->title
= get_string('eventskey', 'calendar');
1276 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT
);
1278 $block = new block_contents
;
1279 $block->content
= $renderer->fake_block_threemonths($this);
1280 $block->footer
= '';
1281 $block->title
= get_string('monthlyview', 'calendar');
1282 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT
);
1287 * Get calendar events.
1289 * @param int $tstart Start time of time range for events
1290 * @param int $tend End time of time range for events
1291 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
1292 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
1293 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
1294 * @param boolean $withduration whether only events starting within time range selected
1295 * or events in progress/already started selected as well
1296 * @param boolean $ignorehidden whether to select only visible events or all events
1297 * @param array|int|boolean $categories array of categories, category id or boolean for all/no course events
1298 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
1300 function calendar_get_events($tstart, $tend, $users, $groups, $courses,
1301 $withduration = true, $ignorehidden = true, $categories = []) {
1307 if (empty($users) && empty($groups) && empty($courses) && empty($categories)) {
1311 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
1312 // Events from a number of users
1313 if(!empty($whereclause)) $whereclause .= ' OR';
1314 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED
);
1315 $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)";
1316 $params = array_merge($params, $inparamsusers);
1317 } else if($users === true) {
1318 // Events from ALL users
1319 if(!empty($whereclause)) $whereclause .= ' OR';
1320 $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)';
1321 } else if($users === false) {
1322 // No user at all, do nothing
1325 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
1326 // Events from a number of groups
1327 if(!empty($whereclause)) $whereclause .= ' OR';
1328 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED
);
1329 $whereclause .= " e.groupid $insqlgroups ";
1330 $params = array_merge($params, $inparamsgroups);
1331 } else if($groups === true) {
1332 // Events from ALL groups
1333 if(!empty($whereclause)) $whereclause .= ' OR ';
1334 $whereclause .= ' e.groupid != 0';
1336 // boolean false (no groups at all): we don't need to do anything
1338 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
1339 if(!empty($whereclause)) $whereclause .= ' OR';
1340 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED
);
1341 $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
1342 $params = array_merge($params, $inparamscourses);
1343 } else if ($courses === true) {
1344 // Events from ALL courses
1345 if(!empty($whereclause)) $whereclause .= ' OR';
1346 $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
1349 if ((is_array($categories) && !empty($categories)) ||
is_numeric($categories)) {
1350 if (!empty($whereclause)) {
1351 $whereclause .= ' OR';
1353 list($insqlcategories, $inparamscategories) = $DB->get_in_or_equal($categories, SQL_PARAMS_NAMED
);
1354 $whereclause .= " (e.groupid = 0 AND e.courseid = 0 AND e.categoryid $insqlcategories)";
1355 $params = array_merge($params, $inparamscategories);
1356 } else if ($categories === true) {
1357 // Events from ALL categories.
1358 if (!empty($whereclause)) {
1359 $whereclause .= ' OR';
1361 $whereclause .= ' (e.groupid = 0 AND e.courseid = 0 AND e.categoryid != 0)';
1364 // Security check: if, by now, we have NOTHING in $whereclause, then it means
1365 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
1366 // events no matter what. Allowing the code to proceed might return a completely
1367 // valid query with only time constraints, thus selecting ALL events in that time frame!
1368 if(empty($whereclause)) {
1373 $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1376 $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1378 if(!empty($whereclause)) {
1379 // We have additional constraints
1380 $whereclause = $timeclause.' AND ('.$whereclause.')';
1383 // Just basic time filtering
1384 $whereclause = $timeclause;
1387 if ($ignorehidden) {
1388 $whereclause .= ' AND e.visible = 1';
1393 LEFT JOIN {modules} m ON e.modulename = m.name
1394 -- Non visible modules will have a value of 0.
1395 WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
1396 ORDER BY e.timestart";
1397 $events = $DB->get_records_sql($sql, $params);
1399 if ($events === false) {
1406 * Return the days of the week.
1408 * @return array array of days
1410 function calendar_get_days() {
1411 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1412 return $calendartype->get_weekdays();
1416 * Get the subscription from a given id.
1419 * @param int $id id of the subscription
1420 * @return stdClass Subscription record from DB
1421 * @throws moodle_exception for an invalid id
1423 function calendar_get_subscription($id) {
1426 $cache = \cache
::make('core', 'calendar_subscriptions');
1427 $subscription = $cache->get($id);
1428 if (empty($subscription)) {
1429 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST
);
1430 $cache->set($id, $subscription);
1433 return $subscription;
1437 * Gets the first day of the week.
1439 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
1443 function calendar_get_starting_weekday() {
1444 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1445 return $calendartype->get_starting_weekday();
1449 * Get a HTML link to a course.
1451 * @param int|stdClass $course the course id or course object
1452 * @return string a link to the course (as HTML); empty if the course id is invalid
1454 function calendar_get_courselink($course) {
1459 if (!is_object($course)) {
1460 $course = calendar_get_course_cached($coursecache, $course);
1462 $context = \context_course
::instance($course->id
);
1463 $fullname = format_string($course->fullname
, true, array('context' => $context));
1464 $url = new \
moodle_url('/course/view.php', array('id' => $course->id
));
1465 $link = \html_writer
::link($url, $fullname);
1471 * Get current module cache.
1473 * Only use this method if you do not know courseid. Otherwise use:
1474 * get_fast_modinfo($courseid)->instances[$modulename][$instance]
1476 * @param array $modulecache in memory module cache
1477 * @param string $modulename name of the module
1478 * @param int $instance module instance number
1479 * @return stdClass|bool $module information
1481 function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
1482 if (!isset($modulecache[$modulename . '_' . $instance])) {
1483 $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
1486 return $modulecache[$modulename . '_' . $instance];
1490 * Get current course cache.
1492 * @param array $coursecache list of course cache
1493 * @param int $courseid id of the course
1494 * @return stdClass $coursecache[$courseid] return the specific course cache
1496 function calendar_get_course_cached(&$coursecache, $courseid) {
1497 if (!isset($coursecache[$courseid])) {
1498 $coursecache[$courseid] = get_course($courseid);
1500 return $coursecache[$courseid];
1504 * Get group from groupid for calendar display
1506 * @param int $groupid
1507 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1509 function calendar_get_group_cached($groupid) {
1510 static $groupscache = array();
1511 if (!isset($groupscache[$groupid])) {
1512 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1514 return $groupscache[$groupid];
1518 * Add calendar event metadata
1520 * @param stdClass $event event info
1521 * @return stdClass $event metadata
1523 function calendar_add_event_metadata($event) {
1524 global $CFG, $OUTPUT;
1526 // Support multilang in event->name.
1527 $event->name
= format_string($event->name
, true);
1529 if (!empty($event->modulename
)) { // Activity event.
1530 // The module name is set. I will assume that it has to be displayed, and
1531 // also that it is an automatically-generated event. And of course that the
1532 // instace id and modulename are set correctly.
1533 $instances = get_fast_modinfo($event->courseid
)->get_instances_of($event->modulename
);
1534 if (!array_key_exists($event->instance
, $instances)) {
1537 $module = $instances[$event->instance
];
1539 $modulename = $module->get_module_type_name(false);
1540 if (get_string_manager()->string_exists($event->eventtype
, $event->modulename
)) {
1541 // Will be used as alt text if the event icon.
1542 $eventtype = get_string($event->eventtype
, $event->modulename
);
1547 $event->icon
= '<img src="' . s($module->get_icon_url()) . '" alt="' . s($eventtype) .
1548 '" title="' . s($modulename) . '" class="icon" />';
1549 $event->referer
= html_writer
::link($module->url
, $event->name
);
1550 $event->courselink
= calendar_get_courselink($module->get_course());
1551 $event->cmid
= $module->id
;
1552 } else if ($event->courseid
== SITEID
) { // Site event.
1553 $event->icon
= '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
1554 get_string('globalevent', 'calendar') . '" class="icon" />';
1555 $event->cssclass
= 'calendar_event_global';
1556 } else if ($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) { // Course event.
1557 $event->icon
= '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
1558 get_string('courseevent', 'calendar') . '" class="icon" />';
1559 $event->courselink
= calendar_get_courselink($event->courseid
);
1560 $event->cssclass
= 'calendar_event_course';
1561 } else if ($event->groupid
) { // Group event.
1562 if ($group = calendar_get_group_cached($event->groupid
)) {
1563 $groupname = format_string($group->name
, true, \context_course
::instance($group->courseid
));
1567 $event->icon
= \html_writer
::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
1568 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
1569 $event->courselink
= calendar_get_courselink($event->courseid
) . ', ' . $groupname;
1570 $event->cssclass
= 'calendar_event_group';
1571 } else if ($event->userid
) { // User event.
1572 $event->icon
= '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
1573 get_string('userevent', 'calendar') . '" class="icon" />';
1574 $event->cssclass
= 'calendar_event_user';
1581 * Get calendar events by id.
1584 * @param array $eventids list of event ids
1585 * @return array Array of event entries, empty array if nothing found
1587 function calendar_get_events_by_id($eventids) {
1590 if (!is_array($eventids) ||
empty($eventids)) {
1594 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
1595 $wheresql = "id $wheresql";
1597 return $DB->get_records_select('event', $wheresql, $params);
1601 * Get control options for calendar.
1603 * @param string $type of calendar
1604 * @param array $data calendar information
1605 * @return string $content return available control for the calender in html
1607 function calendar_top_controls($type, $data) {
1608 global $PAGE, $OUTPUT;
1610 // Get the calendar type we are using.
1611 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1615 // Ensure course id passed if relevant.
1617 if (!empty($data['id'])) {
1618 $courseid = '&course=' . $data['id'];
1621 // If we are passing a month and year then we need to convert this to a timestamp to
1622 // support multiple calendars. No where in core should these be passed, this logic
1623 // here is for third party plugins that may use this function.
1624 if (!empty($data['m']) && !empty($date['y'])) {
1625 if (!isset($data['d'])) {
1628 if (!checkdate($data['m'], $data['d'], $data['y'])) {
1631 $time = make_timestamp($data['y'], $data['m'], $data['d']);
1633 } else if (!empty($data['time'])) {
1634 $time = $data['time'];
1639 // Get the date for the calendar type.
1640 $date = $calendartype->timestamp_to_date_array($time);
1642 $urlbase = $PAGE->url
;
1644 // We need to get the previous and next months in certain cases.
1645 if ($type == 'frontpage' ||
$type == 'course' ||
$type == 'month') {
1646 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1647 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
1648 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
1649 $prevmonthtime['hour'], $prevmonthtime['minute']);
1651 $nextmonth = calendar_add_month($date['mon'], $date['year']);
1652 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
1653 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
1654 $nextmonthtime['hour'], $nextmonthtime['minute']);
1659 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1660 true, $prevmonthtime);
1661 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true,
1663 $calendarlink = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', array('view' => 'month')),
1664 false, false, false, $time);
1666 if (!empty($data['id'])) {
1667 $calendarlink->param('course', $data['id']);
1672 $content .= \html_writer
::start_tag('div', array('class' => 'calendar-controls'));
1673 $content .= $prevlink . '<span class="hide"> | </span>';
1674 $content .= \html_writer
::tag('span', \html_writer
::link($calendarlink,
1675 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1676 ), array('class' => 'current'));
1677 $content .= '<span class="hide"> | </span>' . $right;
1678 $content .= "<span class=\"clearer\"><!-- --></span>\n";
1679 $content .= \html_writer
::end_tag('div');
1683 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1684 true, $prevmonthtime);
1685 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false,
1686 true, $nextmonthtime);
1687 $calendarlink = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', array('view' => 'month')),
1688 false, false, false, $time);
1690 if (!empty($data['id'])) {
1691 $calendarlink->param('course', $data['id']);
1694 $content .= \html_writer
::start_tag('div', array('class' => 'calendar-controls'));
1695 $content .= $prevlink . '<span class="hide"> | </span>';
1696 $content .= \html_writer
::tag('span', \html_writer
::link($calendarlink,
1697 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1698 ), array('class' => 'current'));
1699 $content .= '<span class="hide"> | </span>' . $nextlink;
1700 $content .= "<span class=\"clearer\"><!-- --></span>";
1701 $content .= \html_writer
::end_tag('div');
1704 $calendarlink = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', array('view' => 'upcoming')),
1705 false, false, false, $time);
1706 if (!empty($data['id'])) {
1707 $calendarlink->param('course', $data['id']);
1709 $calendarlink = \html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1710 $content .= \html_writer
::tag('div', $calendarlink, array('class' => 'centered'));
1713 $calendarlink = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', array('view' => 'month')),
1714 false, false, false, $time);
1715 if (!empty($data['id'])) {
1716 $calendarlink->param('course', $data['id']);
1718 $calendarlink = \html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1719 $content .= \html_writer
::tag('h3', $calendarlink);
1722 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1723 'view.php?view=month' . $courseid . '&', false, false, false, false, $prevmonthtime);
1724 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1725 'view.php?view=month' . $courseid . '&', false, false, false, false, $nextmonthtime);
1727 $content .= \html_writer
::start_tag('div', array('class' => 'calendar-controls'));
1728 $content .= $prevlink . '<span class="hide"> | </span>';
1729 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1730 $content .= '<span class="hide"> | </span>' . $nextlink;
1731 $content .= '<span class="clearer"><!-- --></span>';
1732 $content .= \html_writer
::end_tag('div')."\n";
1735 $days = calendar_get_days();
1737 $prevtimestamp = strtotime('-1 day', $time);
1738 $nexttimestamp = strtotime('+1 day', $time);
1740 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1741 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1743 $prevname = $days[$prevdate['wday']]['fullname'];
1744 $nextname = $days[$nextdate['wday']]['fullname'];
1745 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&', false, false,
1746 false, false, $prevtimestamp);
1747 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&', false, false, false,
1748 false, $nexttimestamp);
1750 $content .= \html_writer
::start_tag('div', array('class' => 'calendar-controls'));
1751 $content .= $prevlink;
1752 $content .= '<span class="hide"> | </span><span class="current">' .userdate($time,
1753 get_string('strftimedaydate')) . '</span>';
1754 $content .= '<span class="hide"> | </span>' . $nextlink;
1755 $content .= "<span class=\"clearer\"><!-- --></span>";
1756 $content .= \html_writer
::end_tag('div') . "\n";
1765 * Return the representation day.
1767 * @param int $tstamp Timestamp in GMT
1768 * @param int|bool $now current Unix timestamp
1769 * @param bool $usecommonwords
1770 * @return string the formatted date/time
1772 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1773 static $shortformat;
1775 if (empty($shortformat)) {
1776 $shortformat = get_string('strftimedayshort');
1779 if ($now === false) {
1783 // To have it in one place, if a change is needed.
1784 $formal = userdate($tstamp, $shortformat);
1786 $datestamp = usergetdate($tstamp);
1787 $datenow = usergetdate($now);
1789 if ($usecommonwords == false) {
1790 // We don't want words, just a date.
1792 } else if ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1793 return get_string('today', 'calendar');
1794 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1795 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12
1796 && $datenow['yday'] == 1)) {
1797 return get_string('yesterday', 'calendar');
1798 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] +
1 ) ||
1799 ($datestamp['year'] == $datenow['year'] +
1 && $datenow['mday'] == 31 && $datenow['mon'] == 12
1800 && $datestamp['yday'] == 1)) {
1801 return get_string('tomorrow', 'calendar');
1808 * return the formatted representation time.
1811 * @param int $time the timestamp in UTC, as obtained from the database
1812 * @return string the formatted date/time
1814 function calendar_time_representation($time) {
1815 static $langtimeformat = null;
1817 if ($langtimeformat === null) {
1818 $langtimeformat = get_string('strftimetime');
1821 $timeformat = get_user_preferences('calendar_timeformat');
1822 if (empty($timeformat)) {
1823 $timeformat = get_config(null, 'calendar_site_timeformat');
1826 // Allow language customization of selected time format.
1827 if ($timeformat === CALENDAR_TF_12
) {
1828 $timeformat = get_string('strftimetime12', 'langconfig');
1829 } else if ($timeformat === CALENDAR_TF_24
) {
1830 $timeformat = get_string('strftimetime24', 'langconfig');
1833 return userdate($time, empty($timeformat) ?
$langtimeformat : $timeformat);
1837 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1839 * @param string|moodle_url $linkbase
1840 * @param int $d The number of the day.
1841 * @param int $m The number of the month.
1842 * @param int $y The number of the year.
1843 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1844 * $m and $y are kept for backwards compatibility.
1845 * @return moodle_url|null $linkbase
1847 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1848 if (empty($linkbase)) {
1852 if (!($linkbase instanceof \moodle_url
)) {
1853 $linkbase = new \
moodle_url($linkbase);
1856 $linkbase->param('time', calendar_get_timestamp($d, $m, $y, $time));
1862 * Build and return a previous month HTML link, with an arrow.
1864 * @param string $text The text label.
1865 * @param string|moodle_url $linkbase The URL stub.
1866 * @param int $d The number of the date.
1867 * @param int $m The number of the month.
1868 * @param int $y year The number of the year.
1869 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1870 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1871 * $m and $y are kept for backwards compatibility.
1872 * @return string HTML string.
1874 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1875 $href = calendar_get_link_href(new \
moodle_url($linkbase), $d, $m, $y, $time);
1882 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1883 'data-drop-zone' => 'nav-link',
1886 return link_arrow_left($text, $href->out(false), $accesshide, 'previous', $attrs);
1890 * Build and return a next month HTML link, with an arrow.
1892 * @param string $text The text label.
1893 * @param string|moodle_url $linkbase The URL stub.
1894 * @param int $d the number of the Day
1895 * @param int $m The number of the month.
1896 * @param int $y The number of the year.
1897 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1898 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1899 * $m and $y are kept for backwards compatibility.
1900 * @return string HTML string.
1902 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1903 $href = calendar_get_link_href(new \
moodle_url($linkbase), $d, $m, $y, $time);
1910 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1911 'data-drop-zone' => 'nav-link',
1914 return link_arrow_right($text, $href->out(false), $accesshide, 'next', $attrs);
1918 * Return the number of days in month.
1920 * @param int $month the number of the month.
1921 * @param int $year the number of the year
1924 function calendar_days_in_month($month, $year) {
1925 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1926 return $calendartype->get_num_days_in_month($year, $month);
1930 * Get the next following month.
1932 * @param int $month the number of the month.
1933 * @param int $year the number of the year.
1934 * @return array the following month
1936 function calendar_add_month($month, $year) {
1937 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1938 return $calendartype->get_next_month($year, $month);
1942 * Get the previous month.
1944 * @param int $month the number of the month.
1945 * @param int $year the number of the year.
1946 * @return array previous month
1948 function calendar_sub_month($month, $year) {
1949 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1950 return $calendartype->get_prev_month($year, $month);
1954 * Get per-day basis events
1956 * @param array $events list of events
1957 * @param int $month the number of the month
1958 * @param int $year the number of the year
1959 * @param array $eventsbyday event on specific day
1960 * @param array $durationbyday duration of the event in days
1961 * @param array $typesbyday event type (eg: global, course, user, or group)
1962 * @param array $courses list of courses
1965 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1966 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1968 $eventsbyday = array();
1969 $typesbyday = array();
1970 $durationbyday = array();
1972 if ($events === false) {
1976 foreach ($events as $event) {
1977 $startdate = $calendartype->timestamp_to_date_array($event->timestart
);
1978 if ($event->timeduration
) {
1979 $enddate = $calendartype->timestamp_to_date_array($event->timestart +
$event->timeduration
- 1);
1981 $enddate = $startdate;
1984 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair.
1985 if (!($startdate['year'] * 13 +
$startdate['mon'] <= $year * 13 +
$month) &&
1986 ($enddate['year'] * 13 +
$enddate['mon'] >= $year * 13 +
$month)) {
1990 $eventdaystart = intval($startdate['mday']);
1992 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
1993 // Give the event to its day.
1994 $eventsbyday[$eventdaystart][] = $event->id
;
1996 // Mark the day as having such an event.
1997 if ($event->courseid
== SITEID
&& $event->groupid
== 0) {
1998 $typesbyday[$eventdaystart]['startglobal'] = true;
1999 // Set event class for global event.
2000 $events[$event->id
]->class = 'calendar_event_global';
2001 } else if ($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) {
2002 $typesbyday[$eventdaystart]['startcourse'] = true;
2003 // Set event class for course event.
2004 $events[$event->id
]->class = 'calendar_event_course';
2005 } else if ($event->groupid
) {
2006 $typesbyday[$eventdaystart]['startgroup'] = true;
2007 // Set event class for group event.
2008 $events[$event->id
]->class = 'calendar_event_group';
2009 } else if ($event->userid
) {
2010 $typesbyday[$eventdaystart]['startuser'] = true;
2011 // Set event class for user event.
2012 $events[$event->id
]->class = 'calendar_event_user';
2016 if ($event->timeduration
== 0) {
2017 // Proceed with the next.
2021 // The event starts on $month $year or before.
2022 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2023 $lowerbound = intval($startdate['mday']);
2028 // Also, it ends on $month $year or later.
2029 if ($enddate['mon'] == $month && $enddate['year'] == $year) {
2030 $upperbound = intval($enddate['mday']);
2032 $upperbound = calendar_days_in_month($month, $year);
2035 // Mark all days between $lowerbound and $upperbound (inclusive) as duration.
2036 for ($i = $lowerbound +
1; $i <= $upperbound; ++
$i) {
2037 $durationbyday[$i][] = $event->id
;
2038 if ($event->courseid
== SITEID
&& $event->groupid
== 0) {
2039 $typesbyday[$i]['durationglobal'] = true;
2040 } else if ($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) {
2041 $typesbyday[$i]['durationcourse'] = true;
2042 } else if ($event->groupid
) {
2043 $typesbyday[$i]['durationgroup'] = true;
2044 } else if ($event->userid
) {
2045 $typesbyday[$i]['durationuser'] = true;
2054 * Returns the courses to load events for.
2056 * @param array $courseeventsfrom An array of courses to load calendar events for
2057 * @param bool $ignorefilters specify the use of filters, false is set as default
2058 * @param stdClass $user The user object. This defaults to the global $USER object.
2059 * @return array An array of courses, groups, and user to load calendar events for based upon filters
2061 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false, stdClass
$user = null) {
2064 if (is_null($user)) {
2072 // Get the capabilities that allow seeing group events from all groups.
2073 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
2075 $isvaliduser = !empty($user->id
);
2077 if ($ignorefilters ||
calendar_show_event_type(CALENDAR_EVENT_COURSE
, $user)) {
2078 $courses = array_keys($courseeventsfrom);
2080 if ($ignorefilters ||
calendar_show_event_type(CALENDAR_EVENT_GLOBAL
, $user)) {
2081 $courses[] = SITEID
;
2083 $courses = array_unique($courses);
2086 if (!empty($courses) && in_array(SITEID
, $courses)) {
2087 // Sort courses for consistent colour highlighting.
2088 // Effectively ignoring SITEID as setting as last course id.
2089 $key = array_search(SITEID
, $courses);
2090 unset($courses[$key]);
2091 $courses[] = SITEID
;
2094 if ($ignorefilters ||
($isvaliduser && calendar_show_event_type(CALENDAR_EVENT_USER
, $user))) {
2095 $userid = $user->id
;
2098 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP
, $user) ||
$ignorefilters)) {
2100 if (count($courseeventsfrom) == 1) {
2101 $course = reset($courseeventsfrom);
2102 if (has_any_capability($allgroupscaps, \context_course
::instance($course->id
))) {
2103 $coursegroups = groups_get_all_groups($course->id
, 0, 0, 'g.id');
2104 $group = array_keys($coursegroups);
2107 if ($group === false) {
2108 if (!empty($CFG->calendar_adminseesall
) && has_any_capability($allgroupscaps, \context_system
::instance())) {
2110 } else if ($isvaliduser) {
2111 $groupids = array();
2112 foreach ($courseeventsfrom as $courseid => $course) {
2113 // If the user is an editing teacher in there.
2114 if (!empty($user->groupmember
[$course->id
])) {
2115 // We've already cached the users groups for this course so we can just use that.
2116 $groupids = array_merge($groupids, $user->groupmember
[$course->id
]);
2117 } else if ($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
2118 // If this course has groups, show events from all of those related to the current user.
2119 $coursegroups = groups_get_user_groups($course->id
, $user->id
);
2120 $groupids = array_merge($groupids, $coursegroups['0']);
2123 if (!empty($groupids)) {
2129 if (empty($courses)) {
2133 return array($courses, $group, $userid);
2137 * Return the capability for viewing a calendar event.
2139 * @param calendar_event $event event object
2142 function calendar_view_event_allowed(calendar_event
$event) {
2145 // Anyone can see site events.
2146 if ($event->courseid
&& $event->courseid
== SITEID
) {
2150 // If a user can manage events at the site level they can see any event.
2151 $sitecontext = \context_system
::instance();
2152 // If user has manageentries at site level, return true.
2153 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2157 if (!empty($event->groupid
)) {
2158 // If it is a group event we need to be able to manage events in the course, or be in the group.
2159 if (has_capability('moodle/calendar:manageentries', $event->context
) ||
2160 has_capability('moodle/calendar:managegroupentries', $event->context
)) {
2164 $mycourses = enrol_get_my_courses('id');
2165 return isset($mycourses[$event->courseid
]) && groups_is_member($event->groupid
);
2166 } else if ($event->modulename
) {
2167 // If this is a module event we need to be able to see the module.
2168 $coursemodules = [];
2170 // Override events do not have the courseid set.
2171 if ($event->courseid
) {
2172 $courseid = $event->courseid
;
2173 $coursemodules = get_fast_modinfo($event->courseid
)->instances
;
2175 $cmraw = get_coursemodule_from_instance($event->modulename
, $event->instance
, 0, false, MUST_EXIST
);
2176 $courseid = $cmraw->course
;
2177 $coursemodules = get_fast_modinfo($cmraw->course
)->instances
;
2179 $hasmodule = isset($coursemodules[$event->modulename
]);
2180 $hasinstance = isset($coursemodules[$event->modulename
][$event->instance
]);
2182 // If modinfo doesn't know about the module, return false to be safe.
2183 if (!$hasmodule ||
!$hasinstance) {
2187 // Must be able to see the course and the module - MDL-59304.
2188 $cm = $coursemodules[$event->modulename
][$event->instance
];
2189 if (!$cm->uservisible
) {
2192 $mycourses = enrol_get_my_courses('id');
2193 return isset($mycourses[$courseid]);
2194 } else if ($event->categoryid
) {
2195 // If this is a category we need to be able to see the category.
2196 $cat = \core_course_category
::get($event->categoryid
, IGNORE_MISSING
);
2201 } else if (!empty($event->courseid
)) {
2202 // If it is a course event we need to be able to manage events in the course, or be in the course.
2203 if (has_capability('moodle/calendar:manageentries', $event->context
)) {
2206 $mycourses = enrol_get_my_courses('id');
2207 return isset($mycourses[$event->courseid
]);
2208 } else if ($event->userid
) {
2209 if ($event->userid
!= $USER->id
) {
2210 // No-one can ever see another users events.
2215 throw new moodle_exception('unknown event type');
2222 * Return the capability for editing calendar event.
2224 * @param calendar_event $event event object
2225 * @param bool $manualedit is the event being edited manually by the user
2226 * @return bool capability to edit event
2228 function calendar_edit_event_allowed($event, $manualedit = false) {
2231 // Must be logged in.
2232 if (!isloggedin()) {
2236 // Can not be using guest account.
2237 if (isguestuser()) {
2241 if ($manualedit && !empty($event->modulename
)) {
2242 $hascallback = component_callback_exists(
2243 'mod_' . $event->modulename
,
2244 'core_calendar_event_timestart_updated'
2247 if (!$hascallback) {
2248 // If the activity hasn't implemented the correct callback
2249 // to handle changes to it's events then don't allow any
2250 // manual changes to them.
2254 $coursemodules = get_fast_modinfo($event->courseid
)->instances
;
2255 $hasmodule = isset($coursemodules[$event->modulename
]);
2256 $hasinstance = isset($coursemodules[$event->modulename
][$event->instance
]);
2258 // If modinfo doesn't know about the module, return false to be safe.
2259 if (!$hasmodule ||
!$hasinstance) {
2263 $coursemodule = $coursemodules[$event->modulename
][$event->instance
];
2264 $context = context_module
::instance($coursemodule->id
);
2265 // This is the capability that allows a user to modify the activity
2266 // settings. Since the activity generated this event we need to check
2267 // that the current user has the same capability before allowing them
2268 // to update the event because the changes to the event will be
2269 // reflected within the activity.
2270 return has_capability('moodle/course:manageactivities', $context);
2273 // You cannot edit URL based calendar subscription events presently.
2274 if (!empty($event->subscriptionid
)) {
2275 if (!empty($event->subscription
->url
)) {
2276 // This event can be updated externally, so it cannot be edited.
2281 $sitecontext = \context_system
::instance();
2283 // If user has manageentries at site level, return true.
2284 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2288 // If groupid is set, it's definitely a group event.
2289 if (!empty($event->groupid
)) {
2290 // Allow users to add/edit group events if -
2291 // 1) They have manageentries for the course OR
2292 // 2) They have managegroupentries AND are in the group.
2293 $group = $DB->get_record('groups', array('id' => $event->groupid
));
2295 has_capability('moodle/calendar:manageentries', $event->context
) ||
2296 (has_capability('moodle/calendar:managegroupentries', $event->context
)
2297 && groups_is_member($event->groupid
)));
2298 } else if (!empty($event->courseid
)) {
2299 // If groupid is not set, but course is set, it's definitely a course event.
2300 return has_capability('moodle/calendar:manageentries', $event->context
);
2301 } else if (!empty($event->categoryid
)) {
2302 // If groupid is not set, but category is set, it's definitely a category event.
2303 return has_capability('moodle/calendar:manageentries', $event->context
);
2304 } else if (!empty($event->userid
) && $event->userid
== $USER->id
) {
2305 // If course is not set, but userid id set, it's a user event.
2306 return (has_capability('moodle/calendar:manageownentries', $event->context
));
2307 } else if (!empty($event->userid
)) {
2308 return (has_capability('moodle/calendar:manageentries', $event->context
));
2315 * Return the capability for deleting a calendar event.
2317 * @param calendar_event $event The event object
2318 * @return bool Whether the user has permission to delete the event or not.
2320 function calendar_delete_event_allowed($event) {
2321 // Only allow delete if you have capabilities and it is not an module event.
2322 return (calendar_edit_event_allowed($event) && empty($event->modulename
));
2326 * Returns the default courses to display on the calendar when there isn't a specific
2327 * course to display.
2329 * @param int $courseid (optional) If passed, an additional course can be returned for admins (the current course).
2330 * @param string $fields Comma separated list of course fields to return.
2331 * @param bool $canmanage If true, this will return the list of courses the user can create events in, rather
2332 * than the list of courses they see events from (an admin can always add events in a course
2333 * calendar, even if they are not enrolled in the course).
2334 * @param int $userid (optional) The user which this function returns the default courses for.
2335 * By default the current user.
2336 * @return array $courses Array of courses to display
2338 function calendar_get_default_courses($courseid = null, $fields = '*', $canmanage = false, int $userid = null) {
2342 if (!isloggedin()) {
2345 $userid = $USER->id
;
2348 if ((!empty($CFG->calendar_adminseesall
) ||
$canmanage) &&
2349 has_capability('moodle/calendar:manageentries', context_system
::instance(), $userid)) {
2351 // Add a c. prefix to every field as expected by get_courses function.
2352 $fieldlist = explode(',', $fields);
2354 $prefixedfields = array_map(function($value) {
2355 return 'c.' . trim(strtolower($value));
2357 if (!in_array('c.visible', $prefixedfields) && !in_array('c.*', $prefixedfields)) {
2358 $prefixedfields[] = 'c.visible';
2360 $courses = get_courses('all', 'c.shortname', implode(',', $prefixedfields));
2362 $courses = enrol_get_users_courses($userid, true, $fields);
2365 if ($courseid && $courseid != SITEID
) {
2366 if (empty($courses[$courseid]) && has_capability('moodle/calendar:manageentries', context_system
::instance(), $userid)) {
2367 // Allow a site admin to see calendars from courses he is not enrolled in.
2368 // This will come from $COURSE.
2369 $courses[$courseid] = get_course($courseid);
2377 * Get event format time.
2379 * @param calendar_event $event event object
2380 * @param int $now current time in gmt
2381 * @param array $linkparams list of params for event link
2382 * @param bool $usecommonwords the words as formatted date/time.
2383 * @param int $showtime determine the show time GMT timestamp
2384 * @return string $eventtime link/string for event time
2386 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
2387 $starttime = $event->timestart
;
2388 $endtime = $event->timestart +
$event->timeduration
;
2390 if (empty($linkparams) ||
!is_array($linkparams)) {
2391 $linkparams = array();
2394 $linkparams['view'] = 'day';
2396 // OK, now to get a meaningful display.
2397 // Check if there is a duration for this event.
2398 if ($event->timeduration
) {
2399 // Get the midnight of the day the event will start.
2400 $usermidnightstart = usergetmidnight($starttime);
2401 // Get the midnight of the day the event will end.
2402 $usermidnightend = usergetmidnight($endtime);
2403 // Check if we will still be on the same day.
2404 if ($usermidnightstart == $usermidnightend) {
2405 // Check if we are running all day.
2406 if ($event->timeduration
== DAYSECS
) {
2407 $time = get_string('allday', 'calendar');
2408 } else { // Specify the time we will be running this from.
2409 $datestart = calendar_time_representation($starttime);
2410 $dateend = calendar_time_representation($endtime);
2411 $time = $datestart . ' <strong>»</strong> ' . $dateend;
2414 // Set printable representation.
2416 $day = calendar_day_representation($event->timestart
, $now, $usecommonwords);
2417 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $endtime);
2418 $eventtime = \html_writer
::link($url, $day) . ', ' . $time;
2422 } else { // It must spans two or more days.
2423 $daystart = calendar_day_representation($event->timestart
, $now, $usecommonwords) . ', ';
2424 if ($showtime == $usermidnightstart) {
2427 $timestart = calendar_time_representation($event->timestart
);
2428 $dayend = calendar_day_representation($event->timestart +
$event->timeduration
, $now, $usecommonwords) . ', ';
2429 if ($showtime == $usermidnightend) {
2432 $timeend = calendar_time_representation($event->timestart +
$event->timeduration
);
2434 // Set printable representation.
2435 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2436 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $endtime);
2437 $eventtime = $timestart . ' <strong>»</strong> ' . \html_writer
::link($url, $dayend) . $timeend;
2439 // The event is in the future, print start and end links.
2440 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $starttime);
2441 $eventtime = \html_writer
::link($url, $daystart) . $timestart . ' <strong>»</strong> ';
2443 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $endtime);
2444 $eventtime .= \html_writer
::link($url, $dayend) . $timeend;
2447 } else { // There is no time duration.
2448 $time = calendar_time_representation($event->timestart
);
2449 // Set printable representation.
2451 $day = calendar_day_representation($event->timestart
, $now, $usecommonwords);
2452 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $starttime);
2453 $eventtime = \html_writer
::link($url, $day) . ', ' . trim($time);
2459 // Check if It has expired.
2460 if ($event->timestart +
$event->timeduration
< $now) {
2461 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2468 * Checks to see if the requested type of event should be shown for the given user.
2470 * @param int $type The type to check the display for (default is to display all)
2471 * @param stdClass|int|null $user The user to check for - by default the current user
2472 * @return bool True if the tyep should be displayed false otherwise
2474 function calendar_show_event_type($type, $user = null) {
2475 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER
;
2477 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2479 if (!isset($SESSION->calendarshoweventtype
)) {
2480 $SESSION->calendarshoweventtype
= $default;
2482 return $SESSION->calendarshoweventtype
& $type;
2484 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2489 * Sets the display of the event type given $display.
2491 * If $display = true the event type will be shown.
2492 * If $display = false the event type will NOT be shown.
2493 * If $display = null the current value will be toggled and saved.
2495 * @param int $type object of CALENDAR_EVENT_XXX
2496 * @param bool $display option to display event type
2497 * @param stdClass|int $user moodle user object or id, null means current user
2499 function calendar_set_event_type_display($type, $display = null, $user = null) {
2500 $persist = get_user_preferences('calendar_persistflt', 0, $user);
2501 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP
2502 + CALENDAR_EVENT_USER + CALENDAR_EVENT_COURSECAT
;
2503 if ($persist === 0) {
2505 if (!isset($SESSION->calendarshoweventtype
)) {
2506 $SESSION->calendarshoweventtype
= $default;
2508 $preference = $SESSION->calendarshoweventtype
;
2510 $preference = get_user_preferences('calendar_savedflt', $default, $user);
2512 $current = $preference & $type;
2513 if ($display === null) {
2514 $display = !$current;
2516 if ($display && !$current) {
2517 $preference +
= $type;
2518 } else if (!$display && $current) {
2519 $preference -= $type;
2521 if ($persist === 0) {
2522 $SESSION->calendarshoweventtype
= $preference;
2524 if ($preference == $default) {
2525 unset_user_preference('calendar_savedflt', $user);
2527 set_user_preference('calendar_savedflt', $preference, $user);
2533 * Get calendar's allowed types.
2535 * @param stdClass $allowed list of allowed edit for event type
2536 * @param stdClass|int $course object of a course or course id
2537 * @param array $groups array of groups for the given course
2538 * @param stdClass|int $category object of a category
2540 function calendar_get_allowed_types(&$allowed, $course = null, $groups = null, $category = null) {
2543 $allowed = new \
stdClass();
2544 $allowed->user
= has_capability('moodle/calendar:manageownentries', \context_system
::instance());
2545 $allowed->groups
= false;
2546 $allowed->courses
= false;
2547 $allowed->categories
= false;
2548 $allowed->site
= has_capability('moodle/calendar:manageentries', \context_course
::instance(SITEID
));
2549 $getgroupsfunc = function($course, $context, $user) use ($groups) {
2550 if ($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
2551 if (has_capability('moodle/site:accessallgroups', $context)) {
2552 return is_null($groups) ?
groups_get_all_groups($course->id
) : $groups;
2554 if (is_null($groups)) {
2555 return groups_get_all_groups($course->id
, $user->id
);
2557 return array_filter($groups, function($group) use ($user) {
2558 return isset($group->members
[$user->id
]);
2567 if (!empty($course)) {
2568 if (!is_object($course)) {
2569 $course = $DB->get_record('course', array('id' => $course), 'id, groupmode, groupmodeforce', MUST_EXIST
);
2571 if ($course->id
!= SITEID
) {
2572 $coursecontext = \context_course
::instance($course->id
);
2573 $allowed->user
= has_capability('moodle/calendar:manageownentries', $coursecontext);
2575 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2576 $allowed->courses
= array($course->id
=> 1);
2577 $allowed->groups
= $getgroupsfunc($course, $coursecontext, $USER);
2578 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
2579 $allowed->groups
= $getgroupsfunc($course, $coursecontext, $USER);
2584 if (!empty($category)) {
2585 $catcontext = \context_coursecat
::instance($category->id
);
2586 if (has_capability('moodle/category:manage', $catcontext)) {
2587 $allowed->categories
= [$category->id
=> 1];
2593 * See if user can add calendar entries at all used to print the "New Event" button.
2595 * @param stdClass $course object of a course or course id
2596 * @return bool has the capability to add at least one event type
2598 function calendar_user_can_add_event($course) {
2599 if (!isloggedin() ||
isguestuser()) {
2603 calendar_get_allowed_types($allowed, $course);
2605 return (bool)($allowed->user ||
$allowed->groups ||
$allowed->courses ||
$allowed->categories ||
$allowed->site
);
2609 * Check wether the current user is permitted to add events.
2611 * @param stdClass $event object of event
2612 * @return bool has the capability to add event
2614 function calendar_add_event_allowed($event) {
2617 // Can not be using guest account.
2618 if (!isloggedin() or isguestuser()) {
2622 $sitecontext = \context_system
::instance();
2624 // If user has manageentries at site level, always return true.
2625 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2629 switch ($event->eventtype
) {
2631 return has_capability('moodle/category:manage', $event->context
);
2633 return has_capability('moodle/calendar:manageentries', $event->context
);
2635 // Allow users to add/edit group events if -
2636 // 1) They have manageentries (= entries for whole course).
2637 // 2) They have managegroupentries AND are in the group.
2638 $group = $DB->get_record('groups', array('id' => $event->groupid
));
2640 has_capability('moodle/calendar:manageentries', $event->context
) ||
2641 (has_capability('moodle/calendar:managegroupentries', $event->context
)
2642 && groups_is_member($event->groupid
)));
2644 if ($event->userid
== $USER->id
) {
2645 return (has_capability('moodle/calendar:manageownentries', $event->context
));
2647 // There is intentionally no 'break'.
2649 return has_capability('moodle/calendar:manageentries', $event->context
);
2651 return has_capability('moodle/calendar:manageentries', $event->context
);
2656 * Returns option list for the poll interval setting.
2658 * @return array An array of poll interval options. Interval => description.
2660 function calendar_get_pollinterval_choices() {
2662 '0' => new \
lang_string('never', 'calendar'),
2663 HOURSECS
=> new \
lang_string('hourly', 'calendar'),
2664 DAYSECS
=> new \
lang_string('daily', 'calendar'),
2665 WEEKSECS
=> new \
lang_string('weekly', 'calendar'),
2666 '2628000' => new \
lang_string('monthly', 'calendar'),
2667 YEARSECS
=> new \
lang_string('annually', 'calendar')
2672 * Returns option list of available options for the calendar event type, given the current user and course.
2674 * @param int $courseid The id of the course
2675 * @return array An array containing the event types the user can create.
2677 function calendar_get_eventtype_choices($courseid) {
2679 $allowed = new \stdClass
;
2680 calendar_get_allowed_types($allowed, $courseid);
2682 if ($allowed->user
) {
2683 $choices['user'] = get_string('userevents', 'calendar');
2685 if ($allowed->site
) {
2686 $choices['site'] = get_string('siteevents', 'calendar');
2688 if (!empty($allowed->courses
)) {
2689 $choices['course'] = get_string('courseevents', 'calendar');
2691 if (!empty($allowed->categories
)) {
2692 $choices['category'] = get_string('categoryevents', 'calendar');
2694 if (!empty($allowed->groups
) and is_array($allowed->groups
)) {
2695 $choices['group'] = get_string('group');
2698 return array($choices, $allowed->groups
);
2702 * Add an iCalendar subscription to the database.
2704 * @param stdClass $sub The subscription object (e.g. from the form)
2705 * @return int The insert ID, if any.
2707 function calendar_add_subscription($sub) {
2708 global $DB, $USER, $SITE;
2710 // Undo the form definition work around to allow us to have two different
2711 // course selectors present depending on which event type the user selects.
2712 if (!empty($sub->groupcourseid
)) {
2713 $sub->courseid
= $sub->groupcourseid
;
2714 unset($sub->groupcourseid
);
2717 // Default course id if none is set.
2718 if (empty($sub->courseid
)) {
2719 if ($sub->eventtype
=== 'site') {
2720 $sub->courseid
= SITEID
;
2726 if ($sub->eventtype
=== 'site') {
2727 $sub->courseid
= $SITE->id
;
2728 } else if ($sub->eventtype
=== 'group' ||
$sub->eventtype
=== 'course') {
2729 $sub->courseid
= $sub->courseid
;
2730 } else if ($sub->eventtype
=== 'category') {
2731 $sub->categoryid
= $sub->categoryid
;
2736 $sub->userid
= $USER->id
;
2738 // File subscriptions never update.
2739 if (empty($sub->url
)) {
2740 $sub->pollinterval
= 0;
2743 if (!empty($sub->name
)) {
2744 if (empty($sub->id
)) {
2745 $id = $DB->insert_record('event_subscriptions', $sub);
2746 // We cannot cache the data here because $sub is not complete.
2748 // Trigger event, calendar subscription added.
2749 $eventparams = array('objectid' => $sub->id
,
2750 'context' => calendar_get_calendar_context($sub),
2752 'eventtype' => $sub->eventtype
,
2755 switch ($sub->eventtype
) {
2757 $eventparams['other']['categoryid'] = $sub->categoryid
;
2760 $eventparams['other']['courseid'] = $sub->courseid
;
2763 $eventparams['other']['courseid'] = $sub->courseid
;
2764 $eventparams['other']['groupid'] = $sub->groupid
;
2767 $eventparams['other']['courseid'] = $sub->courseid
;
2770 $event = \core\event\calendar_subscription_created
::create($eventparams);
2774 // Why are we doing an update here?
2775 calendar_update_subscription($sub);
2779 print_error('errorbadsubscription', 'importcalendar');
2784 * Add an iCalendar event to the Moodle calendar.
2786 * @param stdClass $event The RFC-2445 iCalendar event
2787 * @param int $unused Deprecated
2788 * @param int $subscriptionid The iCalendar subscription ID
2789 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2790 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2791 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2793 function calendar_add_icalendar_event($event, $unused = null, $subscriptionid, $timezone='UTC') {
2796 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2797 if (empty($event->properties
['SUMMARY'])) {
2801 $name = $event->properties
['SUMMARY'][0]->value
;
2802 $name = str_replace('\n', '<br />', $name);
2803 $name = str_replace('\\', '', $name);
2804 $name = preg_replace('/\s+/u', ' ', $name);
2806 $eventrecord = new \stdClass
;
2807 $eventrecord->name
= clean_param($name, PARAM_NOTAGS
);
2809 if (empty($event->properties
['DESCRIPTION'][0]->value
)) {
2812 $description = $event->properties
['DESCRIPTION'][0]->value
;
2813 $description = clean_param($description, PARAM_NOTAGS
);
2814 $description = str_replace('\n', '<br />', $description);
2815 $description = str_replace('\\', '', $description);
2816 $description = preg_replace('/\s+/u', ' ', $description);
2818 $eventrecord->description
= $description;
2820 // Probably a repeating event with RRULE etc. TODO: skip for now.
2821 if (empty($event->properties
['DTSTART'][0]->value
)) {
2825 if (isset($event->properties
['DTSTART'][0]->parameters
['TZID'])) {
2826 $tz = $event->properties
['DTSTART'][0]->parameters
['TZID'];
2830 $tz = \core_date
::normalise_timezone($tz);
2831 $eventrecord->timestart
= strtotime($event->properties
['DTSTART'][0]->value
. ' ' . $tz);
2832 if (empty($event->properties
['DTEND'])) {
2833 $eventrecord->timeduration
= 0; // No duration if no end time specified.
2835 if (isset($event->properties
['DTEND'][0]->parameters
['TZID'])) {
2836 $endtz = $event->properties
['DTEND'][0]->parameters
['TZID'];
2840 $endtz = \core_date
::normalise_timezone($endtz);
2841 $eventrecord->timeduration
= strtotime($event->properties
['DTEND'][0]->value
. ' ' . $endtz) - $eventrecord->timestart
;
2844 // Check to see if it should be treated as an all day event.
2845 if ($eventrecord->timeduration
== DAYSECS
) {
2846 // Check to see if the event started at Midnight on the imported calendar.
2847 date_default_timezone_set($timezone);
2848 if (date('H:i:s', $eventrecord->timestart
) === "00:00:00") {
2849 // This event should be an all day event. This is not correct, we don't do anything differently for all day events.
2851 $eventrecord->timeduration
= 0;
2853 \core_date
::set_default_server_timezone();
2856 $eventrecord->location
= empty($event->properties
['LOCATION'][0]->value
) ?
'' :
2857 str_replace('\\', '', $event->properties
['LOCATION'][0]->value
);
2858 $eventrecord->uuid
= $event->properties
['UID'][0]->value
;
2859 $eventrecord->timemodified
= time();
2861 // Add the iCal subscription details if required.
2862 // We should never do anything with an event without a subscription reference.
2863 $sub = calendar_get_subscription($subscriptionid);
2864 $eventrecord->subscriptionid
= $subscriptionid;
2865 $eventrecord->userid
= $sub->userid
;
2866 $eventrecord->groupid
= $sub->groupid
;
2867 $eventrecord->courseid
= $sub->courseid
;
2868 $eventrecord->categoryid
= $sub->categoryid
;
2869 $eventrecord->eventtype
= $sub->eventtype
;
2871 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid
,
2872 'subscriptionid' => $eventrecord->subscriptionid
))) {
2873 $eventrecord->id
= $updaterecord->id
;
2874 $return = CALENDAR_IMPORT_EVENT_UPDATED
; // Update.
2876 $return = CALENDAR_IMPORT_EVENT_INSERTED
; // Insert.
2878 if ($createdevent = \calendar_event
::create($eventrecord, false)) {
2879 if (!empty($event->properties
['RRULE'])) {
2880 // Repeating events.
2881 date_default_timezone_set($tz); // Change time zone to parse all events.
2882 $rrule = new \core_calendar\rrule_manager
($event->properties
['RRULE'][0]->value
);
2883 $rrule->parse_rrule();
2884 $rrule->create_events($createdevent);
2885 \core_date
::set_default_server_timezone(); // Change time zone back to what it was.
2894 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2896 * @param int $subscriptionid The ID of the subscription we are acting upon.
2897 * @param int $pollinterval The poll interval to use.
2898 * @param int $action The action to be performed. One of update or remove.
2899 * @throws dml_exception if invalid subscriptionid is provided
2900 * @return string A log of the import progress, including errors
2902 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2903 // Fetch the subscription from the database making sure it exists.
2904 $sub = calendar_get_subscription($subscriptionid);
2906 // Update or remove the subscription, based on action.
2908 case CALENDAR_SUBSCRIPTION_UPDATE
:
2909 // Skip updating file subscriptions.
2910 if (empty($sub->url
)) {
2913 $sub->pollinterval
= $pollinterval;
2914 calendar_update_subscription($sub);
2916 // Update the events.
2917 return "<p>" . get_string('subscriptionupdated', 'calendar', $sub->name
) . "</p>" .
2918 calendar_update_subscription_events($subscriptionid);
2919 case CALENDAR_SUBSCRIPTION_REMOVE
:
2920 calendar_delete_subscription($subscriptionid);
2921 return get_string('subscriptionremoved', 'calendar', $sub->name
);
2930 * Delete subscription and all related events.
2932 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
2934 function calendar_delete_subscription($subscription) {
2937 if (!is_object($subscription)) {
2938 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST
);
2941 // Delete subscription and related events.
2942 $DB->delete_records('event', array('subscriptionid' => $subscription->id
));
2943 $DB->delete_records('event_subscriptions', array('id' => $subscription->id
));
2944 \cache_helper
::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id
));
2946 // Trigger event, calendar subscription deleted.
2947 $eventparams = array('objectid' => $subscription->id
,
2948 'context' => calendar_get_calendar_context($subscription),
2950 'eventtype' => $subscription->eventtype
,
2953 switch ($subscription->eventtype
) {
2955 $eventparams['other']['categoryid'] = $subscription->categoryid
;
2958 $eventparams['other']['courseid'] = $subscription->courseid
;
2961 $eventparams['other']['courseid'] = $subscription->courseid
;
2962 $eventparams['other']['groupid'] = $subscription->groupid
;
2965 $eventparams['other']['courseid'] = $subscription->courseid
;
2967 $event = \core\event\calendar_subscription_deleted
::create($eventparams);
2972 * From a URL, fetch the calendar and return an iCalendar object.
2974 * @param string $url The iCalendar URL
2975 * @return iCalendar The iCalendar object
2977 function calendar_get_icalendar($url) {
2980 require_once($CFG->libdir
. '/filelib.php');
2982 $curl = new \
curl();
2983 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
2984 $calendar = $curl->get($url);
2986 // Http code validation should actually be the job of curl class.
2987 if (!$calendar ||
$curl->info
['http_code'] != 200 ||
!empty($curl->errorno
)) {
2988 throw new \
moodle_exception('errorinvalidicalurl', 'calendar');
2991 $ical = new \
iCalendar();
2992 $ical->unserialize($calendar);
2998 * Import events from an iCalendar object into a course calendar.
3000 * @param iCalendar $ical The iCalendar object.
3001 * @param int $courseid The course ID for the calendar.
3002 * @param int $subscriptionid The subscription ID.
3003 * @return string A log of the import progress, including errors.
3005 function calendar_import_icalendar_events($ical, $unused = null, $subscriptionid = null) {
3012 // Large calendars take a while...
3014 \core_php_time_limit
::raise(300);
3017 // Mark all events in a subscription with a zero timestamp.
3018 if (!empty($subscriptionid)) {
3019 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
3020 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3023 // Grab the timezone from the iCalendar file to be used later.
3024 if (isset($ical->properties
['X-WR-TIMEZONE'][0]->value
)) {
3025 $timezone = $ical->properties
['X-WR-TIMEZONE'][0]->value
;
3031 foreach ($ical->components
['VEVENT'] as $event) {
3032 $res = calendar_add_icalendar_event($event, null, $subscriptionid, $timezone);
3034 case CALENDAR_IMPORT_EVENT_UPDATED
:
3037 case CALENDAR_IMPORT_EVENT_INSERTED
:
3041 $return .= '<p>' . get_string('erroraddingevent', 'calendar') . ': ';
3042 if (empty($event->properties
['SUMMARY'])) {
3043 $return .= '(' . get_string('notitle', 'calendar') . ')';
3045 $return .= $event->properties
['SUMMARY'][0]->value
;
3047 $return .= "</p>\n";
3052 $return .= "<p>" . get_string('eventsimported', 'calendar', $eventcount) . "</p> ";
3053 $return .= "<p>" . get_string('eventsupdated', 'calendar', $updatecount) . "</p>";
3055 // Delete remaining zero-marked events since they're not in remote calendar.
3056 if (!empty($subscriptionid)) {
3057 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3058 if (!empty($deletecount)) {
3059 $DB->delete_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3060 $return .= "<p> " . get_string('eventsdeleted', 'calendar') . ": {$deletecount} </p>\n";
3068 * Fetch a calendar subscription and update the events in the calendar.
3070 * @param int $subscriptionid The course ID for the calendar.
3071 * @return string A log of the import progress, including errors.
3073 function calendar_update_subscription_events($subscriptionid) {
3074 $sub = calendar_get_subscription($subscriptionid);
3076 // Don't update a file subscription.
3077 if (empty($sub->url
)) {
3078 return 'File subscription not updated.';
3081 $ical = calendar_get_icalendar($sub->url
);
3082 $return = calendar_import_icalendar_events($ical, null, $subscriptionid);
3083 $sub->lastupdated
= time();
3085 calendar_update_subscription($sub);
3091 * Update a calendar subscription. Also updates the associated cache.
3093 * @param stdClass|array $subscription Subscription record.
3094 * @throws coding_exception If something goes wrong
3097 function calendar_update_subscription($subscription) {
3100 if (is_array($subscription)) {
3101 $subscription = (object)$subscription;
3103 if (empty($subscription->id
) ||
!$DB->record_exists('event_subscriptions', array('id' => $subscription->id
))) {
3104 throw new \
coding_exception('Cannot update a subscription without a valid id');
3107 $DB->update_record('event_subscriptions', $subscription);
3110 $cache = \cache
::make('core', 'calendar_subscriptions');
3111 $cache->set($subscription->id
, $subscription);
3113 // Trigger event, calendar subscription updated.
3114 $eventparams = array('userid' => $subscription->userid
,
3115 'objectid' => $subscription->id
,
3116 'context' => calendar_get_calendar_context($subscription),
3118 'eventtype' => $subscription->eventtype
,
3121 switch ($subscription->eventtype
) {
3123 $eventparams['other']['categoryid'] = $subscription->categoryid
;
3126 $eventparams['other']['courseid'] = $subscription->courseid
;
3129 $eventparams['other']['courseid'] = $subscription->courseid
;
3130 $eventparams['other']['groupid'] = $subscription->groupid
;
3133 $eventparams['other']['courseid'] = $subscription->courseid
;
3135 $event = \core\event\calendar_subscription_updated
::create($eventparams);
3140 * Checks to see if the user can edit a given subscription feed.
3142 * @param mixed $subscriptionorid Subscription object or id
3143 * @return bool true if current user can edit the subscription else false
3145 function calendar_can_edit_subscription($subscriptionorid) {
3146 if (is_array($subscriptionorid)) {
3147 $subscription = (object)$subscriptionorid;
3148 } else if (is_object($subscriptionorid)) {
3149 $subscription = $subscriptionorid;
3151 $subscription = calendar_get_subscription($subscriptionorid);
3154 $allowed = new \stdClass
;
3155 $courseid = $subscription->courseid
;
3156 $categoryid = $subscription->categoryid
;
3157 $groupid = $subscription->groupid
;
3160 if (!empty($categoryid)) {
3161 $category = \core_course_category
::get($categoryid);
3163 calendar_get_allowed_types($allowed, $courseid, null, $category);
3164 switch ($subscription->eventtype
) {
3166 return $allowed->user
;
3168 if (isset($allowed->courses
[$courseid])) {
3169 return $allowed->courses
[$courseid];
3174 if (isset($allowed->categories
[$categoryid])) {
3175 return $allowed->categories
[$categoryid];
3180 return $allowed->site
;
3182 if (isset($allowed->groups
[$groupid])) {
3183 return $allowed->groups
[$groupid];
3193 * Helper function to determine the context of a calendar subscription.
3194 * Subscriptions can be created in two contexts COURSE, or USER.
3196 * @param stdClass $subscription
3197 * @return context instance
3199 function calendar_get_calendar_context($subscription) {
3200 // Determine context based on calendar type.
3201 if ($subscription->eventtype
=== 'site') {
3202 $context = \context_course
::instance(SITEID
);
3203 } else if ($subscription->eventtype
=== 'group' ||
$subscription->eventtype
=== 'course') {
3204 $context = \context_course
::instance($subscription->courseid
);
3206 $context = \context_user
::instance($subscription->userid
);
3212 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
3214 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3218 function core_calendar_user_preferences() {
3220 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS
, 'null' => NULL_NOT_ALLOWED
, 'default' => '0',
3221 'choices' => array('0', CALENDAR_TF_12
, CALENDAR_TF_24
)
3223 $preferences['calendar_startwday'] = array('type' => PARAM_INT
, 'null' => NULL_NOT_ALLOWED
, 'default' => 0,
3224 'choices' => array(0, 1, 2, 3, 4, 5, 6));
3225 $preferences['calendar_maxevents'] = array('type' => PARAM_INT
, 'choices' => range(1, 20));
3226 $preferences['calendar_lookahead'] = array('type' => PARAM_INT
, 'null' => NULL_NOT_ALLOWED
, 'default' => 365,
3227 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3228 $preferences['calendar_persistflt'] = array('type' => PARAM_INT
, 'null' => NULL_NOT_ALLOWED
, 'default' => 0,
3229 'choices' => array(0, 1));
3230 return $preferences;
3234 * Get legacy calendar events
3236 * @param int $tstart Start time of time range for events
3237 * @param int $tend End time of time range for events
3238 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3239 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3240 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3241 * @param boolean $withduration whether only events starting within time range selected
3242 * or events in progress/already started selected as well
3243 * @param boolean $ignorehidden whether to select only visible events or all events
3244 * @param array $categories array of category ids and/or objects.
3245 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3247 function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses,
3248 $withduration = true, $ignorehidden = true, $categories = []) {
3249 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3250 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3251 // parameters, but with the new API method, only null and arrays are accepted.
3252 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3253 // If parameter is true, return null.
3254 if ($param === true) {
3258 // If parameter is false, return an empty array.
3259 if ($param === false) {
3263 // If the parameter is a scalar value, enclose it in an array.
3264 if (!is_array($param)) {
3268 // No normalisation required.
3270 }, [$users, $groups, $courses, $categories]);
3272 // If a single user is provided, we can use that for capability checks.
3273 // Otherwise current logged in user is used - See MDL-58768.
3274 if (is_array($userparam) && count($userparam) == 1) {
3275 \core_calendar\local\event\container
::set_requesting_user($userparam[0]);
3277 $mapper = \core_calendar\local\event\container
::get_event_mapper();
3278 $events = \core_calendar\local\api
::get_events(
3295 return array_reduce($events, function($carry, $event) use ($mapper) {
3296 return $carry +
[$event->get_id() => $mapper->from_event_to_stdclass($event)];
3302 * Get the calendar view output.
3304 * @param \calendar_information $calendar The calendar being represented
3305 * @param string $view The type of calendar to have displayed
3306 * @param bool $includenavigation Whether to include navigation
3307 * @param bool $skipevents Whether to load the events or not
3308 * @param int $lookahead Overwrites site and users's lookahead setting.
3309 * @return array[array, string]
3311 function calendar_get_view(\calendar_information
$calendar, $view, $includenavigation = true, bool $skipevents = false,
3312 ?
int $lookahead = null) {
3315 $renderer = $PAGE->get_renderer('core_calendar');
3316 $type = \core_calendar\type_factory
::get_calendar_instance();
3318 // Calculate the bounds of the month.
3319 $calendardate = $type->timestamp_to_date_array($calendar->time
);
3321 $date = new \
DateTime('now', core_date
::get_user_timezone_object(99));
3324 if ($view === 'day') {
3325 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday']);
3326 $date->setTimestamp($tstart);
3327 $date->modify('+1 day');
3328 } else if ($view === 'upcoming' ||
$view === 'upcoming_mini') {
3329 // Number of days in the future that will be used to fetch events.
3331 if (isset($CFG->calendar_lookahead
)) {
3332 $defaultlookahead = intval($CFG->calendar_lookahead
);
3334 $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD
;
3336 $lookahead = get_user_preferences('calendar_lookahead', $defaultlookahead);
3339 // Maximum number of events to be displayed on upcoming view.
3340 $defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS
;
3341 if (isset($CFG->calendar_maxevents
)) {
3342 $defaultmaxevents = intval($CFG->calendar_maxevents
);
3344 $eventlimit = get_user_preferences('calendar_maxevents', $defaultmaxevents);
3346 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday'],
3347 $calendardate['hours']);
3348 $date->setTimestamp($tstart);
3349 $date->modify('+' . $lookahead . ' days');
3351 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], 1);
3352 $monthdays = $type->get_num_days_in_month($calendardate['year'], $calendardate['mon']);
3353 $date->setTimestamp($tstart);
3354 $date->modify('+' . $monthdays . ' days');
3356 if ($view === 'mini' ||
$view === 'minithree') {
3357 $template = 'core_calendar/calendar_mini';
3359 $template = 'core_calendar/calendar_month';
3363 // We need to extract 1 second to ensure that we don't get into the next day.
3364 $date->modify('-1 second');
3365 $tend = $date->getTimestamp();
3367 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3368 // If parameter is true, return null.
3369 if ($param === true) {
3373 // If parameter is false, return an empty array.
3374 if ($param === false) {
3378 // If the parameter is a scalar value, enclose it in an array.
3379 if (!is_array($param)) {
3383 // No normalisation required.
3385 }, [$calendar->users
, $calendar->groups
, $calendar->courses
, $calendar->categories
]);
3390 $events = \core_calendar\local\api
::get_events(
3406 if ($proxy = $event->get_course_module()) {
3407 $cminfo = $proxy->get_proxied_instance();
3408 return $cminfo->uservisible
;
3411 if ($proxy = $event->get_category()) {
3412 $category = $proxy->get_proxied_instance();
3414 return $category->is_uservisible();
3423 'events' => $events,
3424 'cache' => new \core_calendar\external\
events_related_objects_cache($events),
3429 if ($view == "month" ||
$view == "mini" ||
$view == "minithree") {
3430 $month = new \core_calendar\external\
month_exporter($calendar, $type, $related);
3431 $month->set_includenavigation($includenavigation);
3432 $month->set_initialeventsloaded(!$skipevents);
3433 $month->set_showcoursefilter($view == "month");
3434 $data = $month->export($renderer);
3435 } else if ($view == "day") {
3436 $day = new \core_calendar\external\
calendar_day_exporter($calendar, $related);
3437 $data = $day->export($renderer);
3438 $template = 'core_calendar/calendar_day';
3439 } else if ($view == "upcoming" ||
$view == "upcoming_mini") {
3440 $upcoming = new \core_calendar\external\
calendar_upcoming_exporter($calendar, $related);
3441 $data = $upcoming->export($renderer);
3443 if ($view == "upcoming") {
3444 $template = 'core_calendar/calendar_upcoming';
3445 } else if ($view == "upcoming_mini") {
3446 $template = 'core_calendar/calendar_upcoming_mini';
3450 return [$data, $template];
3454 * Request and render event form fragment.
3456 * @param array $args The fragment arguments.
3457 * @return string The rendered mform fragment.
3459 function calendar_output_fragment_event_form($args) {
3460 global $CFG, $OUTPUT, $USER;
3461 require_once($CFG->libdir
. '/grouplib.php');
3464 $eventid = isset($args['eventid']) ?
clean_param($args['eventid'], PARAM_INT
) : null;
3465 $starttime = isset($args['starttime']) ?
clean_param($args['starttime'], PARAM_INT
) : null;
3466 $courseid = (isset($args['courseid']) && $args['courseid'] != SITEID
) ?
clean_param($args['courseid'], PARAM_INT
) : null;
3467 $categoryid = isset($args['categoryid']) ?
clean_param($args['categoryid'], PARAM_INT
) : null;
3469 $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
3470 $context = \context_user
::instance($USER->id
);
3471 $editoroptions = \core_calendar\local\event\forms\create
::build_editor_options($context);
3472 $formoptions = ['editoroptions' => $editoroptions, 'courseid' => $courseid];
3476 parse_str(clean_param($args['formdata'], PARAM_TEXT
), $data);
3477 if (isset($data['description']['itemid'])) {
3478 $draftitemid = $data['description']['itemid'];
3483 $formoptions['starttime'] = $starttime;
3486 if (is_null($eventid)) {
3487 if (!empty($courseid)) {
3488 $groupcoursedata = groups_get_course_data($courseid);
3489 $formoptions['groups'] = [];
3490 foreach ($groupcoursedata->groups
as $groupid => $groupdata) {
3491 $formoptions['groups'][$groupid] = $groupdata->name
;
3494 $mform = new \core_calendar\local\event\forms\
create(
3504 // Let's check first which event types user can add.
3505 $eventtypes = calendar_get_allowed_event_types($courseid);
3507 // If the user is on course context and is allowed to add course events set the event type default to course.
3508 if ($courseid != SITEID
&& !empty($eventtypes['course'])) {
3509 $data['eventtype'] = 'course';
3510 $data['courseid'] = $courseid;
3511 $data['groupcourseid'] = $courseid;
3512 } else if (!empty($categoryid) && !empty($eventtypes['category'])) {
3513 $data['eventtype'] = 'category';
3514 $data['categoryid'] = $categoryid;
3515 } else if (!empty($groupcoursedata) && !empty($eventtypes['group'])) {
3516 $data['groupcourseid'] = $courseid;
3517 $data['groups'] = $groupcoursedata->groups
;
3519 $mform->set_data($data);
3521 $event = calendar_event
::load($eventid);
3523 if (!calendar_edit_event_allowed($event)) {
3524 print_error('nopermissiontoupdatecalendar');
3527 $mapper = new \core_calendar\local\event\mappers\
create_update_form_mapper();
3528 $eventdata = $mapper->from_legacy_event_to_data($event);
3529 $data = array_merge((array) $eventdata, $data);
3530 $event->count_repeats();
3531 $formoptions['event'] = $event;
3533 if (!empty($event->courseid
)) {
3534 $groupcoursedata = groups_get_course_data($event->courseid
);
3535 $formoptions['groups'] = [];
3536 foreach ($groupcoursedata->groups
as $groupid => $groupdata) {
3537 $formoptions['groups'][$groupid] = $groupdata->name
;
3541 $data['description']['text'] = file_prepare_draft_area(
3543 $event->context
->id
,
3545 'event_description',
3548 $data['description']['text']
3550 $data['description']['itemid'] = $draftitemid;
3552 $mform = new \core_calendar\local\event\forms\
update(
3561 $mform->set_data($data);
3563 // Check to see if this event is part of a subscription or import.
3564 // If so display a warning on edit.
3565 if (isset($event->subscriptionid
) && ($event->subscriptionid
!= null)) {
3566 $renderable = new \core\output\notification
(
3567 get_string('eventsubscriptioneditwarning', 'calendar'),
3568 \core\output\notification
::NOTIFY_INFO
3571 $html .= $OUTPUT->render($renderable);
3576 $mform->is_validated();
3579 $html .= $mform->render();
3584 * Calculate the timestamp from the supplied Gregorian Year, Month, and Day.
3586 * @param int $d The day
3587 * @param int $m The month
3588 * @param int $y The year
3589 * @param int $time The timestamp to use instead of a separate y/m/d.
3590 * @return int The timestamp
3592 function calendar_get_timestamp($d, $m, $y, $time = 0) {
3593 // If a day, month and year were passed then convert it to a timestamp. If these were passed
3594 // then we can assume the day, month and year are passed as Gregorian, as no where in core
3595 // should we be passing these values rather than the time.
3596 if (!empty($d) && !empty($m) && !empty($y)) {
3597 if (checkdate($m, $d, $y)) {
3598 $time = make_timestamp($y, $m, $d);
3602 } else if (empty($time)) {
3610 * Get the calendar footer options.
3612 * @param calendar_information $calendar The calendar information object.
3613 * @return array The data for template and template name.
3615 function calendar_get_footer_options($calendar) {
3616 global $CFG, $USER, $DB, $PAGE;
3618 // Generate hash for iCal link.
3619 $rawhash = $USER->id
. $DB->get_field('user', 'password', ['id' => $USER->id
]) . $CFG->calendar_exportsalt
;
3620 $authtoken = sha1($rawhash);
3622 $renderer = $PAGE->get_renderer('core_calendar');
3623 $footer = new \core_calendar\external\footer_options_exporter
($calendar, $USER->id
, $authtoken);
3624 $data = $footer->export($renderer);
3625 $template = 'core_calendar/footer_options';
3627 return [$data, $template];
3631 * Get the list of potential calendar filter types as a type => name
3636 function calendar_get_filter_types() {
3645 return array_map(function($type) {
3647 'eventtype' => $type,
3648 'name' => get_string("eventtype{$type}", "calendar"),
3654 * Check whether the specified event type is valid.
3656 * @param string $type
3659 function calendar_is_valid_eventtype($type) {
3667 return in_array($type, $validtypes);
3671 * Get event types the user can create event based on categories, courses and groups
3672 * the logged in user belongs to.
3674 * @param int|null $courseid The course id.
3675 * @return array The array of allowed types.
3677 function calendar_get_allowed_event_types(int $courseid = null) {
3678 global $DB, $CFG, $USER;
3688 if (!empty($courseid) && $courseid != SITEID
) {
3689 $context = \context_course
::instance($courseid);
3690 $groups = groups_get_all_groups($courseid);
3692 $types['user'] = has_capability('moodle/calendar:manageownentries', $context);
3694 if (has_capability('moodle/calendar:manageentries', $context) ||
!empty($CFG->calendar_adminseesall
)) {
3695 $types['course'] = true;
3697 $types['group'] = (!empty($groups) && has_capability('moodle/site:accessallgroups', $context))
3698 ||
array_filter($groups, function($group) use ($USER) {
3699 return groups_is_member($group->id
);
3701 } else if (has_capability('moodle/calendar:managegroupentries', $context)) {
3702 $types['group'] = (!empty($groups) && has_capability('moodle/site:accessallgroups', $context))
3703 ||
array_filter($groups, function($group) use ($USER) {
3704 return groups_is_member($group->id
);
3709 if (has_capability('moodle/calendar:manageentries', \context_course
::instance(SITEID
))) {
3710 $types['site'] = true;
3713 if (has_capability('moodle/calendar:manageownentries', \context_system
::instance())) {
3714 $types['user'] = true;
3716 if (core_course_category
::has_manage_capability_on_any()) {
3717 $types['category'] = true;
3720 // We still don't know if the user can create group and course events, so iterate over the courses to find out
3721 // if the user has capabilities in one of the courses.
3722 if ($types['course'] == false ||
$types['group'] == false) {
3723 if ($CFG->calendar_adminseesall
&& has_capability('moodle/calendar:manageentries', context_system
::instance())) {
3724 $sql = "SELECT c.id, " . context_helper
::get_preload_record_columns_sql('ctx') . "
3726 JOIN {context} ctx ON ctx.contextlevel = ? AND ctx.instanceid = c.id
3728 SELECT DISTINCT courseid FROM {groups}
3730 $courseswithgroups = $DB->get_recordset_sql($sql, [CONTEXT_COURSE
]);
3731 foreach ($courseswithgroups as $course) {
3732 context_helper
::preload_from_record($course);
3733 $context = context_course
::instance($course->id
);
3735 if (has_capability('moodle/calendar:manageentries', $context)) {
3736 if (has_any_capability(['moodle/site:accessallgroups', 'moodle/calendar:managegroupentries'], $context)) {
3737 // The user can manage group entries or access any group.
3738 $types['group'] = true;
3739 $types['course'] = true;
3744 $courseswithgroups->close();
3746 if (false === $types['course']) {
3747 // Course is still not confirmed. There may have been no courses with a group in them.
3748 $ctxfields = context_helper
::get_preload_record_columns_sql('ctx');
3750 c.id, c.visible, {$ctxfields}
3752 JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
3754 'contextlevel' => CONTEXT_COURSE
,
3756 $courses = $DB->get_recordset_sql($sql, $params);
3757 foreach ($courses as $course) {
3758 context_helper
::preload_from_record($course);
3759 $context = context_course
::instance($course->id
);
3760 if (has_capability('moodle/calendar:manageentries', $context)) {
3761 $types['course'] = true;
3769 $courses = calendar_get_default_courses(null, 'id');
3770 if (empty($courses)) {
3774 $courseids = array_map(function($c) {
3778 // Check whether the user has access to create events within courses which have groups.
3779 list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED
);
3780 $sql = "SELECT c.id, " . context_helper
::get_preload_record_columns_sql('ctx') . "
3782 JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3784 AND c.id IN (SELECT DISTINCT courseid FROM {groups})";
3785 $params['contextlevel'] = CONTEXT_COURSE
;
3786 $courseswithgroups = $DB->get_recordset_sql($sql, $params);
3787 foreach ($courseswithgroups as $coursewithgroup) {
3788 context_helper
::preload_from_record($coursewithgroup);
3789 $context = context_course
::instance($coursewithgroup->id
);
3791 if (has_capability('moodle/calendar:manageentries', $context)) {
3792 // The user has access to manage calendar entries for the whole course.
3793 // This includes groups if they have the accessallgroups capability.
3794 $types['course'] = true;
3795 if (has_capability('moodle/site:accessallgroups', $context)) {
3796 // The user also has access to all groups so they can add calendar entries to any group.
3797 // The manageentries capability overrides the managegroupentries capability.
3798 $types['group'] = true;
3802 if (empty($types['group']) && has_capability('moodle/calendar:managegroupentries', $context)) {
3803 // The user has the managegroupentries capability.
3804 // If they have access to _any_ group, then they can create calendar entries within that group.
3805 $types['group'] = !empty(groups_get_all_groups($coursewithgroup->id
, $USER->id
));
3809 // Okay, course and group event types are allowed, no need to keep the loop iteration.
3810 if ($types['course'] == true && $types['group'] == true) {
3814 $courseswithgroups->close();
3816 if (false === $types['course']) {
3817 list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED
);
3818 $contextsql = "SELECT c.id, " . context_helper
::get_preload_record_columns_sql('ctx') . "
3820 JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3822 $params['contextlevel'] = CONTEXT_COURSE
;
3823 $contextrecords = $DB->get_recordset_sql($contextsql, $params);
3824 foreach ($contextrecords as $course) {
3825 context_helper
::preload_from_record($course);
3826 $coursecontext = context_course
::instance($course->id
);
3827 if (has_capability('moodle/calendar:manageentries', $coursecontext)
3828 && ($courseid == $course->id ||
empty($courseid))) {
3829 $types['course'] = true;
3833 $contextrecords->close();