Merge branch 'MDL-67732-37' of https://github.com/paulholden/moodle into MOODLE_37_STABLE
[moodle.git] / calendar / lib.php
bloba9df414b51d15f9b14d3a165c808ce26f1ef0d9f
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Calendar extension
20 * @package core_calendar
21 * @copyright 2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
22 * Avgoustos Tsinakos
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 if (!defined('MOODLE_INTERNAL')) {
27 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
30 /**
31 * These are read by the administration component to provide default values
34 /**
35 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
37 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
39 /**
40 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
42 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
44 /**
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
52 /**
53 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
55 define('CALENDAR_DEFAULT_WEEKEND', 65);
57 /**
58 * CALENDAR_URL - path to calendar's folder
60 define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
62 /**
63 * CALENDAR_TF_24 - Calendar time in 24 hours format
65 define('CALENDAR_TF_24', '%H:%M');
67 /**
68 * CALENDAR_TF_12 - Calendar time in 12 hours format
70 define('CALENDAR_TF_12', '%I:%M %p');
72 /**
73 * CALENDAR_EVENT_GLOBAL - Global calendar event types
75 define('CALENDAR_EVENT_GLOBAL', 1);
77 /**
78 * CALENDAR_EVENT_COURSE - Course calendar event types
80 define('CALENDAR_EVENT_COURSE', 2);
82 /**
83 * CALENDAR_EVENT_GROUP - group calendar event types
85 define('CALENDAR_EVENT_GROUP', 4);
87 /**
88 * CALENDAR_EVENT_USER - user calendar event types
90 define('CALENDAR_EVENT_USER', 8);
92 /**
93 * CALENDAR_EVENT_COURSECAT - Course category calendar event types
95 define('CALENDAR_EVENT_COURSECAT', 16);
97 /**
98 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
100 define('CALENDAR_IMPORT_FROM_FILE', 0);
103 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
105 define('CALENDAR_IMPORT_FROM_URL', 1);
108 * CALENDAR_IMPORT_EVENT_UPDATED_SKIPPED - imported event was skipped
110 define('CALENDAR_IMPORT_EVENT_SKIPPED', -1);
113 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
115 define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
118 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
120 define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
123 * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
125 define('CALENDAR_SUBSCRIPTION_UPDATE', 1);
128 * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
130 define('CALENDAR_SUBSCRIPTION_REMOVE', 2);
133 * CALENDAR_EVENT_USER_OVERRIDE_PRIORITY - Constant for the user override priority.
135 define('CALENDAR_EVENT_USER_OVERRIDE_PRIORITY', 0);
138 * CALENDAR_EVENT_TYPE_STANDARD - Standard events.
140 define('CALENDAR_EVENT_TYPE_STANDARD', 0);
143 * CALENDAR_EVENT_TYPE_ACTION - Action events.
145 define('CALENDAR_EVENT_TYPE_ACTION', 1);
148 * Manage calendar events.
150 * This class provides the required functionality in order to manage calendar events.
151 * It was introduced as part of Moodle 2.0 and was created in order to provide a
152 * better framework for dealing with calendar events in particular regard to file
153 * handling through the new file API.
155 * @package core_calendar
156 * @category calendar
157 * @copyright 2009 Sam Hemelryk
158 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
160 * @property int $id The id within the event table
161 * @property string $name The name of the event
162 * @property string $description The description of the event
163 * @property int $format The format of the description FORMAT_?
164 * @property int $courseid The course the event is associated with (0 if none)
165 * @property int $groupid The group the event is associated with (0 if none)
166 * @property int $userid The user the event is associated with (0 if none)
167 * @property int $repeatid If this is a repeated event this will be set to the
168 * id of the original
169 * @property string $modulename If added by a module this will be the module name
170 * @property int $instance If added by a module this will be the module instance
171 * @property string $eventtype The event type
172 * @property int $timestart The start time as a timestamp
173 * @property int $timeduration The duration of the event in seconds
174 * @property int $visible 1 if the event is visible
175 * @property int $uuid ?
176 * @property int $sequence ?
177 * @property int $timemodified The time last modified as a timestamp
179 class calendar_event {
181 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
182 protected $properties = null;
184 /** @var string The converted event discription with file paths resolved.
185 * This gets populated when someone requests description for the first time */
186 protected $_description = null;
188 /** @var array The options to use with this description editor */
189 protected $editoroptions = array(
190 'subdirs' => false,
191 'forcehttps' => false,
192 'maxfiles' => -1,
193 'maxbytes' => null,
194 'trusttext' => false);
196 /** @var object The context to use with the description editor */
197 protected $editorcontext = null;
200 * Instantiates a new event and optionally populates its properties with the data provided.
202 * @param \stdClass $data Optional. An object containing the properties to for
203 * an event
205 public function __construct($data = null) {
206 global $CFG, $USER;
208 // First convert to object if it is not already (should either be object or assoc array).
209 if (!is_object($data)) {
210 $data = (object) $data;
213 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
215 $data->eventrepeats = 0;
217 if (empty($data->id)) {
218 $data->id = null;
221 if (!empty($data->subscriptionid)) {
222 $data->subscription = calendar_get_subscription($data->subscriptionid);
225 // Default to a user event.
226 if (empty($data->eventtype)) {
227 $data->eventtype = 'user';
230 // Default to the current user.
231 if (empty($data->userid)) {
232 $data->userid = $USER->id;
235 if (!empty($data->timeduration) && is_array($data->timeduration)) {
236 $data->timeduration = make_timestamp(
237 $data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'],
238 $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
241 if (!empty($data->description) && is_array($data->description)) {
242 $data->format = $data->description['format'];
243 $data->description = $data->description['text'];
244 } else if (empty($data->description)) {
245 $data->description = '';
246 $data->format = editors_get_preferred_format();
249 // Ensure form is defaulted correctly.
250 if (empty($data->format)) {
251 $data->format = editors_get_preferred_format();
254 $this->properties = $data;
258 * Magic set method.
260 * Attempts to call a set_$key method if one exists otherwise falls back
261 * to simply set the property.
263 * @param string $key property name
264 * @param mixed $value value of the property
266 public function __set($key, $value) {
267 if (method_exists($this, 'set_'.$key)) {
268 $this->{'set_'.$key}($value);
270 $this->properties->{$key} = $value;
274 * Magic get method.
276 * Attempts to call a get_$key method to return the property and ralls over
277 * to return the raw property.
279 * @param string $key property name
280 * @return mixed property value
281 * @throws \coding_exception
283 public function __get($key) {
284 if (method_exists($this, 'get_'.$key)) {
285 return $this->{'get_'.$key}();
287 if (!property_exists($this->properties, $key)) {
288 throw new \coding_exception('Undefined property requested');
290 return $this->properties->{$key};
294 * Magic isset method.
296 * PHP needs an isset magic method if you use the get magic method and
297 * still want empty calls to work.
299 * @param string $key $key property name
300 * @return bool|mixed property value, false if property is not exist
302 public function __isset($key) {
303 return !empty($this->properties->{$key});
307 * Calculate the context value needed for an event.
309 * Event's type can be determine by the available value store in $data
310 * It is important to check for the existence of course/courseid to determine
311 * the course event.
312 * Default value is set to CONTEXT_USER
314 * @return \stdClass The context object.
316 protected function calculate_context() {
317 global $USER, $DB;
319 $context = null;
320 if (isset($this->properties->categoryid) && $this->properties->categoryid > 0) {
321 $context = \context_coursecat::instance($this->properties->categoryid);
322 } else if (isset($this->properties->courseid) && $this->properties->courseid > 0) {
323 $context = \context_course::instance($this->properties->courseid);
324 } else if (isset($this->properties->course) && $this->properties->course > 0) {
325 $context = \context_course::instance($this->properties->course);
326 } else if (isset($this->properties->groupid) && $this->properties->groupid > 0) {
327 $group = $DB->get_record('groups', array('id' => $this->properties->groupid));
328 $context = \context_course::instance($group->courseid);
329 } else if (isset($this->properties->userid) && $this->properties->userid > 0
330 && $this->properties->userid == $USER->id) {
331 $context = \context_user::instance($this->properties->userid);
332 } else if (isset($this->properties->userid) && $this->properties->userid > 0
333 && $this->properties->userid != $USER->id &&
334 isset($this->properties->instance) && $this->properties->instance > 0) {
335 $cm = get_coursemodule_from_instance($this->properties->modulename, $this->properties->instance, 0,
336 false, MUST_EXIST);
337 $context = \context_course::instance($cm->course);
338 } else {
339 $context = \context_user::instance($this->properties->userid);
342 return $context;
346 * Returns the context for this event. The context is calculated
347 * the first time is is requested and then stored in a member
348 * variable to be returned each subsequent time.
350 * This is a magical getter function that will be called when
351 * ever the context property is accessed, e.g. $event->context.
353 * @return context
355 protected function get_context() {
356 if (!isset($this->properties->context)) {
357 $this->properties->context = $this->calculate_context();
360 return $this->properties->context;
364 * Returns an array of editoroptions for this event.
366 * @return array event editor options
368 protected function get_editoroptions() {
369 return $this->editoroptions;
373 * Returns an event description: Called by __get
374 * Please use $blah = $event->description;
376 * @return string event description
378 protected function get_description() {
379 global $CFG;
381 require_once($CFG->libdir . '/filelib.php');
383 if ($this->_description === null) {
384 // Check if we have already resolved the context for this event.
385 if ($this->editorcontext === null) {
386 // Switch on the event type to decide upon the appropriate context to use for this event.
387 $this->editorcontext = $this->get_context();
388 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
389 return clean_text($this->properties->description, $this->properties->format);
393 // Work out the item id for the editor, if this is a repeated event
394 // then the files will be associated with the original.
395 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
396 $itemid = $this->properties->repeatid;
397 } else {
398 $itemid = $this->properties->id;
401 // Convert file paths in the description so that things display correctly.
402 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php',
403 $this->editorcontext->id, 'calendar', 'event_description', $itemid);
404 // Clean the text so no nasties get through.
405 $this->_description = clean_text($this->_description, $this->properties->format);
408 // Finally return the description.
409 return $this->_description;
413 * Return the number of repeat events there are in this events series.
415 * @return int number of event repeated
417 public function count_repeats() {
418 global $DB;
419 if (!empty($this->properties->repeatid)) {
420 $this->properties->eventrepeats = $DB->count_records('event',
421 array('repeatid' => $this->properties->repeatid));
422 // We don't want to count ourselves.
423 $this->properties->eventrepeats--;
425 return $this->properties->eventrepeats;
429 * Update or create an event within the database
431 * Pass in a object containing the event properties and this function will
432 * insert it into the database and deal with any associated files
434 * Capability checking should be performed if the user is directly manipulating the event
435 * and no other capability has been tested. However if the event is not being manipulated
436 * directly by the user and another capability has been checked for them to do this then
437 * capabilites should not be checked.
439 * For example if a user is editing an event in the calendar the check should be true,
440 * but if you are updating an event in an activities settings are changed then the calendar
441 * capabilites should not be checked.
443 * @see self::create()
444 * @see self::update()
446 * @param \stdClass $data object of event
447 * @param bool $checkcapability If Moodle should check the user can manage the calendar events for this call or not.
448 * @return bool event updated
450 public function update($data, $checkcapability=true) {
451 global $DB, $USER;
453 foreach ($data as $key => $value) {
454 $this->properties->$key = $value;
457 $this->properties->timemodified = time();
458 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
460 // Prepare event data.
461 $eventargs = array(
462 'context' => $this->get_context(),
463 'objectid' => $this->properties->id,
464 'other' => array(
465 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
466 'timestart' => $this->properties->timestart,
467 'name' => $this->properties->name
471 if (empty($this->properties->id) || $this->properties->id < 1) {
472 if ($checkcapability) {
473 if (!calendar_add_event_allowed($this->properties)) {
474 print_error('nopermissiontoupdatecalendar');
478 if ($usingeditor) {
479 switch ($this->properties->eventtype) {
480 case 'user':
481 $this->properties->courseid = 0;
482 $this->properties->course = 0;
483 $this->properties->groupid = 0;
484 $this->properties->userid = $USER->id;
485 break;
486 case 'site':
487 $this->properties->courseid = SITEID;
488 $this->properties->course = SITEID;
489 $this->properties->groupid = 0;
490 $this->properties->userid = $USER->id;
491 break;
492 case 'course':
493 $this->properties->groupid = 0;
494 $this->properties->userid = $USER->id;
495 break;
496 case 'category':
497 $this->properties->groupid = 0;
498 $this->properties->category = 0;
499 $this->properties->userid = $USER->id;
500 break;
501 case 'group':
502 $this->properties->userid = $USER->id;
503 break;
504 default:
505 // We should NEVER get here, but just incase we do lets fail gracefully.
506 $usingeditor = false;
507 break;
510 // If we are actually using the editor, we recalculate the context because some default values
511 // were set when calculate_context() was called from the constructor.
512 if ($usingeditor) {
513 $this->properties->context = $this->calculate_context();
514 $this->editorcontext = $this->get_context();
517 $editor = $this->properties->description;
518 $this->properties->format = $this->properties->description['format'];
519 $this->properties->description = $this->properties->description['text'];
522 // Insert the event into the database.
523 $this->properties->id = $DB->insert_record('event', $this->properties);
525 if ($usingeditor) {
526 $this->properties->description = file_save_draft_area_files(
527 $editor['itemid'],
528 $this->editorcontext->id,
529 'calendar',
530 'event_description',
531 $this->properties->id,
532 $this->editoroptions,
533 $editor['text'],
534 $this->editoroptions['forcehttps']);
535 $DB->set_field('event', 'description', $this->properties->description,
536 array('id' => $this->properties->id));
539 // Log the event entry.
540 $eventargs['objectid'] = $this->properties->id;
541 $eventargs['context'] = $this->get_context();
542 $event = \core\event\calendar_event_created::create($eventargs);
543 $event->trigger();
545 $repeatedids = array();
547 if (!empty($this->properties->repeat)) {
548 $this->properties->repeatid = $this->properties->id;
549 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id' => $this->properties->id));
551 $eventcopy = clone($this->properties);
552 unset($eventcopy->id);
554 $timestart = new \DateTime('@' . $eventcopy->timestart);
555 $timestart->setTimezone(\core_date::get_user_timezone_object());
557 for ($i = 1; $i < $eventcopy->repeats; $i++) {
559 $timestart->add(new \DateInterval('P7D'));
560 $eventcopy->timestart = $timestart->getTimestamp();
562 // Get the event id for the log record.
563 $eventcopyid = $DB->insert_record('event', $eventcopy);
565 // If the context has been set delete all associated files.
566 if ($usingeditor) {
567 $fs = get_file_storage();
568 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description',
569 $this->properties->id);
570 foreach ($files as $file) {
571 $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
575 $repeatedids[] = $eventcopyid;
577 // Trigger an event.
578 $eventargs['objectid'] = $eventcopyid;
579 $eventargs['other']['timestart'] = $eventcopy->timestart;
580 $event = \core\event\calendar_event_created::create($eventargs);
581 $event->trigger();
585 return true;
586 } else {
588 if ($checkcapability) {
589 if (!calendar_edit_event_allowed($this->properties)) {
590 print_error('nopermissiontoupdatecalendar');
594 if ($usingeditor) {
595 if ($this->editorcontext !== null) {
596 $this->properties->description = file_save_draft_area_files(
597 $this->properties->description['itemid'],
598 $this->editorcontext->id,
599 'calendar',
600 'event_description',
601 $this->properties->id,
602 $this->editoroptions,
603 $this->properties->description['text'],
604 $this->editoroptions['forcehttps']);
605 } else {
606 $this->properties->format = $this->properties->description['format'];
607 $this->properties->description = $this->properties->description['text'];
611 $event = $DB->get_record('event', array('id' => $this->properties->id));
613 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
615 if ($updaterepeated) {
617 $sqlset = 'name = ?,
618 description = ?,
619 timeduration = ?,
620 timemodified = ?,
621 groupid = ?,
622 courseid = ?';
624 // Note: Group and course id may not be set. If not, keep their current values.
625 $params = [
626 $this->properties->name,
627 $this->properties->description,
628 $this->properties->timeduration,
629 time(),
630 isset($this->properties->groupid) ? $this->properties->groupid : $event->groupid,
631 isset($this->properties->courseid) ? $this->properties->courseid : $event->courseid,
634 // Note: Only update start date, if it was changed by the user.
635 if ($this->properties->timestart != $event->timestart) {
636 $timestartoffset = $this->properties->timestart - $event->timestart;
637 $sqlset .= ', timestart = timestart + ?';
638 $params[] = $timestartoffset;
641 // Note: Only update location, if it was changed by the user.
642 $updatelocation = (!empty($this->properties->location) && $this->properties->location !== $event->location);
643 if ($updatelocation) {
644 $sqlset .= ', location = ?';
645 $params[] = $this->properties->location;
648 // Update all.
649 $sql = "UPDATE {event}
650 SET $sqlset
651 WHERE repeatid = ?";
653 $params[] = $event->repeatid;
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);
663 $event->trigger();
665 } else {
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);
673 $event->trigger();
676 return true;
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) {
692 global $DB;
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);
697 return false;
699 $calevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
700 // Delete the event.
701 $DB->delete_records('event', array('id' => $this->properties->id));
703 // Trigger an event for the delete action.
704 $eventargs = array(
705 'context' => $this->get_context(),
706 'objectid' => $this->properties->id,
707 'other' => array(
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);
714 $event->trigger();
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);
732 $event->trigger();
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) {
747 $file->delete();
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);
763 return true;
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) {
779 global $DB;
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') {
797 // Site context.
798 $this->editorcontext = $this->get_context();
799 } else if ($properties->eventtype === 'user') {
800 // User context.
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));
805 if (!$course) {
806 print_error('invalidcourse');
808 // Course context.
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);
816 // Course context.
817 $this->editorcontext = $this->get_context();
818 } else {
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)) {
827 $contextid = false;
828 } else {
829 // Get the context id that is what we really want.
830 $contextid = $this->editorcontext->id;
832 } else {
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.
836 $contextid = null;
839 // If the contextid === false we don't support files so no preparing
840 // a draft area.
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);
847 } else {
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.
857 return $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
865 * is made visible.
866 * @return bool if event is successfully updated, toggle will be visible
868 public function toggle_visibility($force = null) {
869 global $DB;
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;
879 } else {
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.
889 $eventargs = array(
890 'context' => $this->get_context(),
891 'objectid' => $this->properties->id,
892 'other' => array(
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);
900 $event->trigger();
902 return $success;
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) {
915 global $DB;
916 if (is_object($param)) {
917 $event = new calendar_event($param);
918 } else {
919 $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST);
920 $event = new calendar_event($event);
922 return $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)) {
952 return $event;
953 } else {
954 return false;
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;
980 } else {
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
996 * @category 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.
1008 public $time;
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());
1046 if (empty($day)) {
1047 $day = $date['mday'];
1049 if (empty($month)) {
1050 $month = $date['mon'];
1052 if (empty($year)) {
1053 $year = $date['year'];
1055 if (checkdate($month, $day, $year)) {
1056 $time = make_timestamp($year, $month, $day);
1057 } else {
1058 $time = time();
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);
1101 } else {
1102 $course = get_site();
1103 $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1104 $category = null;
1106 $calendar->context = context_system::instance();
1109 $calendar->set_sources($course, $courses, $category);
1111 return $calendar;
1115 * Set the time period of this instance.
1117 * @param int $time the unixtimestamp representing the date we want to view.
1118 * @return $this
1120 public function set_time($time = null) {
1121 if (empty($time)) {
1122 $this->time = time();
1123 } else {
1124 $this->time = $time;
1127 return $this;
1131 * Initialize calendar information
1133 * @deprecated 3.4
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()',
1140 DEBUG_DEVELOPER);
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) {
1155 global $USER;
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;
1200 }, $courses));
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.
1206 $categories = [];
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)) {
1234 if ($defaultonow) {
1235 $now = usergetdate(time());
1236 $this->day = intval($now['mday']);
1237 $this->month = intval($now['mon']);
1238 $this->year = intval($now['year']);
1239 return true;
1240 } else {
1241 throw new moodle_exception('invaliddate');
1244 return true;
1248 * Gets todays timestamp for the calendar
1250 * @return int today timestamp
1252 public function timestamp_today() {
1253 return $this->time;
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) {
1271 if ($showfilters) {
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 = []) {
1302 global $DB;
1304 $whereclause = '';
1305 $params = array();
1306 // Quick test.
1307 if (empty($users) && empty($groups) && empty($courses) && empty($categories)) {
1308 return array();
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)) {
1369 return array();
1372 if($withduration) {
1373 $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1375 else {
1376 $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1378 if(!empty($whereclause)) {
1379 // We have additional constraints
1380 $whereclause = $timeclause.' AND ('.$whereclause.')';
1382 else {
1383 // Just basic time filtering
1384 $whereclause = $timeclause;
1387 if ($ignorehidden) {
1388 $whereclause .= ' AND e.visible = 1';
1391 $sql = "SELECT e.*
1392 FROM {event} e
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) {
1400 $events = array();
1402 return $events;
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.
1418 * @since Moodle 2.5
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) {
1424 global $DB;
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);
1441 * @return int
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) {
1455 if (!$course) {
1456 return '';
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);
1467 return $link;
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)) {
1535 return;
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);
1543 } else {
1544 $eventtype = '';
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));
1564 } else {
1565 $groupname = '';
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';
1577 return $event;
1581 * Get calendar events by id.
1583 * @since Moodle 2.5
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) {
1588 global $DB;
1590 if (!is_array($eventids) || empty($eventids)) {
1591 return array();
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();
1613 $content = '';
1615 // Ensure course id passed if relevant.
1616 $courseid = '';
1617 if (!empty($data['id'])) {
1618 $courseid = '&amp;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'])) {
1626 $data['d'] = 1;
1628 if (!checkdate($data['m'], $data['d'], $data['y'])) {
1629 $time = time();
1630 } else {
1631 $time = make_timestamp($data['y'], $data['m'], $data['d']);
1633 } else if (!empty($data['time'])) {
1634 $time = $data['time'];
1635 } else {
1636 $time = 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']);
1657 switch ($type) {
1658 case 'frontpage':
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,
1662 $nextmonthtime);
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']);
1670 $right = $nextlink;
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');
1681 break;
1682 case 'course':
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');
1702 break;
1703 case 'upcoming':
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'));
1711 break;
1712 case 'display':
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);
1720 break;
1721 case 'month':
1722 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1723 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $prevmonthtime);
1724 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1725 'view.php?view=month' . $courseid . '&amp;', 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";
1733 break;
1734 case 'day':
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 . '&amp;', false, false,
1746 false, false, $prevtimestamp);
1747 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&amp;', 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";
1758 break;
1761 return $content;
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) {
1780 $now = time();
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.
1791 return $formal;
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');
1802 } else {
1803 return $formal;
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)) {
1849 return null;
1852 if (!($linkbase instanceof \moodle_url)) {
1853 $linkbase = new \moodle_url($linkbase);
1856 $linkbase->param('time', calendar_get_timestamp($d, $m, $y, $time));
1858 return $linkbase;
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);
1877 if (empty($href)) {
1878 return $text;
1881 $attrs = [
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);
1905 if (empty($href)) {
1906 return $text;
1909 $attrs = [
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
1922 * @return int
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
1963 * @return void
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) {
1973 return;
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);
1980 } else {
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)) {
1987 continue;
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.
2018 continue;
2021 // The event starts on $month $year or before.
2022 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2023 $lowerbound = intval($startdate['mday']);
2024 } else {
2025 $lowerbound = 0;
2028 // Also, it ends on $month $year or later.
2029 if ($enddate['mon'] == $month && $enddate['year'] == $year) {
2030 $upperbound = intval($enddate['mday']);
2031 } else {
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;
2050 return;
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) {
2062 global $CFG, $USER;
2064 if (is_null($user)) {
2065 $user = $USER;
2068 $courses = array();
2069 $userid = false;
2070 $group = false;
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);
2084 sort($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())) {
2109 $group = true;
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)) {
2124 $group = $groupids;
2129 if (empty($courses)) {
2130 $courses = false;
2133 return array($courses, $group, $userid);
2137 * Return the capability for viewing a calendar event.
2139 * @param calendar_event $event event object
2140 * @return boolean
2142 function calendar_view_event_allowed(calendar_event $event) {
2143 global $USER;
2145 // Anyone can see site events.
2146 if ($event->courseid && $event->courseid == SITEID) {
2147 return true;
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)) {
2154 return true;
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)) {
2161 return true;
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 = [];
2169 $courseid = 0;
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;
2174 } else {
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) {
2184 return false;
2187 // Must be able to see the course and the module - MDL-59304.
2188 $cm = $coursemodules[$event->modulename][$event->instance];
2189 if (!$cm->uservisible) {
2190 return false;
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);
2197 if (!$cat) {
2198 return false;
2200 return true;
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)) {
2204 return true;
2207 return can_access_course(get_course($event->courseid));
2208 } else if ($event->userid) {
2209 if ($event->userid != $USER->id) {
2210 // No-one can ever see another users events.
2211 return false;
2213 return true;
2214 } else {
2215 throw new moodle_exception('unknown event type');
2218 return false;
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) {
2229 global $USER, $DB;
2231 // Must be logged in.
2232 if (!isloggedin()) {
2233 return false;
2236 // Can not be using guest account.
2237 if (isguestuser()) {
2238 return false;
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.
2251 return false;
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) {
2260 return false;
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.
2277 return false;
2281 $sitecontext = \context_system::instance();
2283 // If user has manageentries at site level, return true.
2284 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2285 return true;
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));
2294 return $group && (
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));
2311 return false;
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) {
2339 global $CFG, $USER;
2341 if (!$userid) {
2342 if (!isloggedin()) {
2343 return array();
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));
2356 }, $fieldlist);
2357 if (!in_array('c.visible', $prefixedfields) && !in_array('c.*', $prefixedfields)) {
2358 $prefixedfields[] = 'c.visible';
2360 $courses = get_courses('all', 'c.shortname', implode(',', $prefixedfields));
2361 } else {
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);
2373 return $courses;
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>&raquo;</strong> ' . $dateend;
2414 // Set printable representation.
2415 if (!$showtime) {
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;
2419 } else {
2420 $eventtime = $time;
2422 } else { // It must spans two or more days.
2423 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
2424 if ($showtime == $usermidnightstart) {
2425 $daystart = '';
2427 $timestart = calendar_time_representation($event->timestart);
2428 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
2429 if ($showtime == $usermidnightend) {
2430 $dayend = '';
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>&raquo;</strong> ' . \html_writer::link($url, $dayend) . $timeend;
2438 } else {
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>&raquo;</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.
2450 if (!$showtime) {
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);
2454 } else {
2455 $eventtime = $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>';
2464 return $eventtime;
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) {
2478 global $SESSION;
2479 if (!isset($SESSION->calendarshoweventtype)) {
2480 $SESSION->calendarshoweventtype = $default;
2482 return $SESSION->calendarshoweventtype & $type;
2483 } else {
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) {
2504 global $SESSION;
2505 if (!isset($SESSION->calendarshoweventtype)) {
2506 $SESSION->calendarshoweventtype = $default;
2508 $preference = $SESSION->calendarshoweventtype;
2509 } else {
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;
2523 } else {
2524 if ($preference == $default) {
2525 unset_user_preference('calendar_savedflt', $user);
2526 } else {
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) {
2541 global $USER, $DB;
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;
2553 } else {
2554 if (is_null($groups)) {
2555 return groups_get_all_groups($course->id, $user->id);
2556 } else {
2557 return array_filter($groups, function($group) use ($user) {
2558 return isset($group->members[$user->id]);
2564 return false;
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()) {
2600 return false;
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) {
2615 global $USER, $DB;
2617 // Can not be using guest account.
2618 if (!isloggedin() or isguestuser()) {
2619 return false;
2622 $sitecontext = \context_system::instance();
2624 // If user has manageentries at site level, always return true.
2625 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2626 return true;
2629 switch ($event->eventtype) {
2630 case 'category':
2631 return has_capability('moodle/category:manage', $event->context);
2632 case 'course':
2633 return has_capability('moodle/calendar:manageentries', $event->context);
2634 case 'group':
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));
2639 return $group && (
2640 has_capability('moodle/calendar:manageentries', $event->context) ||
2641 (has_capability('moodle/calendar:managegroupentries', $event->context)
2642 && groups_is_member($event->groupid)));
2643 case 'user':
2644 if ($event->userid == $USER->id) {
2645 return (has_capability('moodle/calendar:manageownentries', $event->context));
2647 // There is intentionally no 'break'.
2648 case 'site':
2649 return has_capability('moodle/calendar:manageentries', $event->context);
2650 default:
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() {
2661 return array(
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) {
2678 $choices = array();
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;
2721 } else {
2722 $sub->courseid = 0;
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;
2732 } else {
2733 // User events.
2734 $sub->courseid = 0;
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.
2747 $sub->id = $id;
2748 // Trigger event, calendar subscription added.
2749 $eventparams = array('objectid' => $sub->id,
2750 'context' => calendar_get_calendar_context($sub),
2751 'other' => array(
2752 'eventtype' => $sub->eventtype,
2755 switch ($sub->eventtype) {
2756 case 'category':
2757 $eventparams['other']['categoryid'] = $sub->categoryid;
2758 break;
2759 case 'course':
2760 $eventparams['other']['courseid'] = $sub->courseid;
2761 break;
2762 case 'group':
2763 $eventparams['other']['courseid'] = $sub->courseid;
2764 $eventparams['other']['groupid'] = $sub->groupid;
2765 break;
2766 default:
2767 $eventparams['other']['courseid'] = $sub->courseid;
2770 $event = \core\event\calendar_subscription_created::create($eventparams);
2771 $event->trigger();
2772 return $id;
2773 } else {
2774 // Why are we doing an update here?
2775 calendar_update_subscription($sub);
2776 return $sub->id;
2778 } else {
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') {
2794 global $DB;
2796 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2797 if (empty($event->properties['SUMMARY'])) {
2798 return 0;
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)) {
2810 $description = '';
2811 } else {
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)) {
2822 return 0;
2825 if (isset($event->properties['DTSTART'][0]->parameters['TZID'])) {
2826 $tz = $event->properties['DTSTART'][0]->parameters['TZID'];
2827 } else {
2828 $tz = $timezone;
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.
2834 } else {
2835 if (isset($event->properties['DTEND'][0]->parameters['TZID'])) {
2836 $endtz = $event->properties['DTEND'][0]->parameters['TZID'];
2837 } else {
2838 $endtz = $timezone;
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.
2850 // See MDL-56227.
2851 $eventrecord->timeduration = 0;
2853 \core_date::set_default_server_timezone();
2856 $eventrecord->location = empty($event->properties['LOCATION'][0]->value) ? '' :
2857 trim(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))) {
2874 // Compare iCal event data against the moodle event to see if something has changed.
2875 $result = array_diff((array) $eventrecord, (array) $updaterecord);
2877 // Unset timemodified field because it's always going to be different.
2878 unset($result['timemodified']);
2880 if (count($result)) {
2881 $eventrecord->id = $updaterecord->id;
2882 $return = CALENDAR_IMPORT_EVENT_UPDATED; // Update.
2883 } else {
2884 return CALENDAR_IMPORT_EVENT_SKIPPED;
2886 } else {
2887 $return = CALENDAR_IMPORT_EVENT_INSERTED; // Insert.
2890 if ($createdevent = \calendar_event::create($eventrecord, false)) {
2891 if (!empty($event->properties['RRULE'])) {
2892 // Repeating events.
2893 date_default_timezone_set($tz); // Change time zone to parse all events.
2894 $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
2895 $rrule->parse_rrule();
2896 $rrule->create_events($createdevent);
2897 \core_date::set_default_server_timezone(); // Change time zone back to what it was.
2899 return $return;
2900 } else {
2901 return 0;
2906 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2908 * @param int $subscriptionid The ID of the subscription we are acting upon.
2909 * @param int $pollinterval The poll interval to use.
2910 * @param int $action The action to be performed. One of update or remove.
2911 * @throws dml_exception if invalid subscriptionid is provided
2912 * @return string A log of the import progress, including errors
2914 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2915 // Fetch the subscription from the database making sure it exists.
2916 $sub = calendar_get_subscription($subscriptionid);
2918 // Update or remove the subscription, based on action.
2919 switch ($action) {
2920 case CALENDAR_SUBSCRIPTION_UPDATE:
2921 // Skip updating file subscriptions.
2922 if (empty($sub->url)) {
2923 break;
2925 $sub->pollinterval = $pollinterval;
2926 calendar_update_subscription($sub);
2928 // Update the events.
2929 return "<p>" . get_string('subscriptionupdated', 'calendar', $sub->name) . "</p>" .
2930 calendar_update_subscription_events($subscriptionid);
2931 case CALENDAR_SUBSCRIPTION_REMOVE:
2932 calendar_delete_subscription($subscriptionid);
2933 return get_string('subscriptionremoved', 'calendar', $sub->name);
2934 break;
2935 default:
2936 break;
2938 return '';
2942 * Delete subscription and all related events.
2944 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
2946 function calendar_delete_subscription($subscription) {
2947 global $DB;
2949 if (!is_object($subscription)) {
2950 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST);
2953 // Delete subscription and related events.
2954 $DB->delete_records('event', array('subscriptionid' => $subscription->id));
2955 $DB->delete_records('event_subscriptions', array('id' => $subscription->id));
2956 \cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id));
2958 // Trigger event, calendar subscription deleted.
2959 $eventparams = array('objectid' => $subscription->id,
2960 'context' => calendar_get_calendar_context($subscription),
2961 'other' => array(
2962 'eventtype' => $subscription->eventtype,
2965 switch ($subscription->eventtype) {
2966 case 'category':
2967 $eventparams['other']['categoryid'] = $subscription->categoryid;
2968 break;
2969 case 'course':
2970 $eventparams['other']['courseid'] = $subscription->courseid;
2971 break;
2972 case 'group':
2973 $eventparams['other']['courseid'] = $subscription->courseid;
2974 $eventparams['other']['groupid'] = $subscription->groupid;
2975 break;
2976 default:
2977 $eventparams['other']['courseid'] = $subscription->courseid;
2979 $event = \core\event\calendar_subscription_deleted::create($eventparams);
2980 $event->trigger();
2984 * From a URL, fetch the calendar and return an iCalendar object.
2986 * @param string $url The iCalendar URL
2987 * @return iCalendar The iCalendar object
2989 function calendar_get_icalendar($url) {
2990 global $CFG;
2992 require_once($CFG->libdir . '/filelib.php');
2994 $curl = new \curl();
2995 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
2996 $calendar = $curl->get($url);
2998 // Http code validation should actually be the job of curl class.
2999 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
3000 throw new \moodle_exception('errorinvalidicalurl', 'calendar');
3003 $ical = new \iCalendar();
3004 $ical->unserialize($calendar);
3006 return $ical;
3010 * Import events from an iCalendar object into a course calendar.
3012 * @param iCalendar $ical The iCalendar object.
3013 * @param int $unused Deprecated
3014 * @param int $subscriptionid The subscription ID.
3015 * @return string A log of the import progress, including errors.
3017 function calendar_import_icalendar_events($ical, $unused = null, $subscriptionid = null) {
3018 global $DB;
3020 $return = '';
3021 $eventcount = 0;
3022 $updatecount = 0;
3023 $skippedcount = 0;
3025 // Large calendars take a while...
3026 if (!CLI_SCRIPT) {
3027 \core_php_time_limit::raise(300);
3030 // Grab the timezone from the iCalendar file to be used later.
3031 if (isset($ical->properties['X-WR-TIMEZONE'][0]->value)) {
3032 $timezone = $ical->properties['X-WR-TIMEZONE'][0]->value;
3033 } else {
3034 $timezone = 'UTC';
3037 $icaluuids = [];
3038 foreach ($ical->components['VEVENT'] as $event) {
3039 $icaluuids[] = $event->properties['UID'][0]->value;
3040 $res = calendar_add_icalendar_event($event, null, $subscriptionid, $timezone);
3041 switch ($res) {
3042 case CALENDAR_IMPORT_EVENT_UPDATED:
3043 $updatecount++;
3044 break;
3045 case CALENDAR_IMPORT_EVENT_INSERTED:
3046 $eventcount++;
3047 break;
3048 case CALENDAR_IMPORT_EVENT_SKIPPED:
3049 $skippedcount++;
3050 break;
3051 case 0:
3052 $return .= '<p>' . get_string('erroraddingevent', 'calendar') . ': ';
3053 if (empty($event->properties['SUMMARY'])) {
3054 $return .= '(' . get_string('notitle', 'calendar') . ')';
3055 } else {
3056 $return .= $event->properties['SUMMARY'][0]->value;
3058 $return .= "</p>\n";
3059 break;
3063 $existing = $DB->get_field('event_subscriptions', 'lastupdated', ['id' => $subscriptionid]);
3064 if (!empty($existing)) {
3065 $eventsuuids = $DB->get_records_menu('event', ['subscriptionid' => $subscriptionid], '', 'id, uuid');
3067 $icaleventscount = count($icaluuids);
3068 $tobedeleted = [];
3069 if (count($eventsuuids) > $icaleventscount) {
3070 foreach ($eventsuuids as $eventid => $eventuuid) {
3071 if (!in_array($eventuuid, $icaluuids)) {
3072 $tobedeleted[] = $eventid;
3075 if (!empty($tobedeleted)) {
3076 $DB->delete_records_list('event', 'id', $tobedeleted);
3077 $return .= "<p> " . get_string('eventsdeleted', 'calendar') . ": " . count($tobedeleted) . "</p> ";
3082 $return .= "<p>" . get_string('eventsimported', 'calendar', $eventcount) . "</p> ";
3083 $return .= "<p>" . get_string('eventsskipped', 'calendar', $skippedcount) . "</p> ";
3084 $return .= "<p>" . get_string('eventsupdated', 'calendar', $updatecount) . "</p>";
3085 return $return;
3089 * Fetch a calendar subscription and update the events in the calendar.
3091 * @param int $subscriptionid The course ID for the calendar.
3092 * @return string A log of the import progress, including errors.
3094 function calendar_update_subscription_events($subscriptionid) {
3095 $sub = calendar_get_subscription($subscriptionid);
3097 // Don't update a file subscription.
3098 if (empty($sub->url)) {
3099 return 'File subscription not updated.';
3102 $ical = calendar_get_icalendar($sub->url);
3103 $return = calendar_import_icalendar_events($ical, null, $subscriptionid);
3104 $sub->lastupdated = time();
3106 calendar_update_subscription($sub);
3108 return $return;
3112 * Update a calendar subscription. Also updates the associated cache.
3114 * @param stdClass|array $subscription Subscription record.
3115 * @throws coding_exception If something goes wrong
3116 * @since Moodle 2.5
3118 function calendar_update_subscription($subscription) {
3119 global $DB;
3121 if (is_array($subscription)) {
3122 $subscription = (object)$subscription;
3124 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
3125 throw new \coding_exception('Cannot update a subscription without a valid id');
3128 $DB->update_record('event_subscriptions', $subscription);
3130 // Update cache.
3131 $cache = \cache::make('core', 'calendar_subscriptions');
3132 $cache->set($subscription->id, $subscription);
3134 // Trigger event, calendar subscription updated.
3135 $eventparams = array('userid' => $subscription->userid,
3136 'objectid' => $subscription->id,
3137 'context' => calendar_get_calendar_context($subscription),
3138 'other' => array(
3139 'eventtype' => $subscription->eventtype,
3142 switch ($subscription->eventtype) {
3143 case 'category':
3144 $eventparams['other']['categoryid'] = $subscription->categoryid;
3145 break;
3146 case 'course':
3147 $eventparams['other']['courseid'] = $subscription->courseid;
3148 break;
3149 case 'group':
3150 $eventparams['other']['courseid'] = $subscription->courseid;
3151 $eventparams['other']['groupid'] = $subscription->groupid;
3152 break;
3153 default:
3154 $eventparams['other']['courseid'] = $subscription->courseid;
3156 $event = \core\event\calendar_subscription_updated::create($eventparams);
3157 $event->trigger();
3161 * Checks to see if the user can edit a given subscription feed.
3163 * @param mixed $subscriptionorid Subscription object or id
3164 * @return bool true if current user can edit the subscription else false
3166 function calendar_can_edit_subscription($subscriptionorid) {
3167 if (is_array($subscriptionorid)) {
3168 $subscription = (object)$subscriptionorid;
3169 } else if (is_object($subscriptionorid)) {
3170 $subscription = $subscriptionorid;
3171 } else {
3172 $subscription = calendar_get_subscription($subscriptionorid);
3175 $allowed = new \stdClass;
3176 $courseid = $subscription->courseid;
3177 $categoryid = $subscription->categoryid;
3178 $groupid = $subscription->groupid;
3179 $category = null;
3181 if (!empty($categoryid)) {
3182 $category = \core_course_category::get($categoryid);
3184 calendar_get_allowed_types($allowed, $courseid, null, $category);
3185 switch ($subscription->eventtype) {
3186 case 'user':
3187 return $allowed->user;
3188 case 'course':
3189 if (isset($allowed->courses[$courseid])) {
3190 return $allowed->courses[$courseid];
3191 } else {
3192 return false;
3194 case 'category':
3195 if (isset($allowed->categories[$categoryid])) {
3196 return $allowed->categories[$categoryid];
3197 } else {
3198 return false;
3200 case 'site':
3201 return $allowed->site;
3202 case 'group':
3203 if (isset($allowed->groups[$groupid])) {
3204 return $allowed->groups[$groupid];
3205 } else {
3206 return false;
3208 default:
3209 return false;
3214 * Helper function to determine the context of a calendar subscription.
3215 * Subscriptions can be created in two contexts COURSE, or USER.
3217 * @param stdClass $subscription
3218 * @return context instance
3220 function calendar_get_calendar_context($subscription) {
3221 // Determine context based on calendar type.
3222 if ($subscription->eventtype === 'site') {
3223 $context = \context_course::instance(SITEID);
3224 } else if ($subscription->eventtype === 'group' || $subscription->eventtype === 'course') {
3225 $context = \context_course::instance($subscription->courseid);
3226 } else {
3227 $context = \context_user::instance($subscription->userid);
3229 return $context;
3233 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
3235 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3237 * @return array
3239 function core_calendar_user_preferences() {
3240 $preferences = [];
3241 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED, 'default' => '0',
3242 'choices' => array('0', CALENDAR_TF_12, CALENDAR_TF_24)
3244 $preferences['calendar_startwday'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3245 'choices' => array(0, 1, 2, 3, 4, 5, 6));
3246 $preferences['calendar_maxevents'] = array('type' => PARAM_INT, 'choices' => range(1, 20));
3247 $preferences['calendar_lookahead'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 365,
3248 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3249 $preferences['calendar_persistflt'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3250 'choices' => array(0, 1));
3251 return $preferences;
3255 * Get legacy calendar events
3257 * @param int $tstart Start time of time range for events
3258 * @param int $tend End time of time range for events
3259 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3260 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3261 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3262 * @param boolean $withduration whether only events starting within time range selected
3263 * or events in progress/already started selected as well
3264 * @param boolean $ignorehidden whether to select only visible events or all events
3265 * @param array $categories array of category ids and/or objects.
3266 * @param int $limitnum Number of events to fetch or zero to fetch all.
3268 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3270 function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses,
3271 $withduration = true, $ignorehidden = true, $categories = [], $limitnum = 0) {
3272 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3273 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3274 // parameters, but with the new API method, only null and arrays are accepted.
3275 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3276 // If parameter is true, return null.
3277 if ($param === true) {
3278 return null;
3281 // If parameter is false, return an empty array.
3282 if ($param === false) {
3283 return [];
3286 // If the parameter is a scalar value, enclose it in an array.
3287 if (!is_array($param)) {
3288 return [$param];
3291 // No normalisation required.
3292 return $param;
3293 }, [$users, $groups, $courses, $categories]);
3295 // If a single user is provided, we can use that for capability checks.
3296 // Otherwise current logged in user is used - See MDL-58768.
3297 if (is_array($userparam) && count($userparam) == 1) {
3298 \core_calendar\local\event\container::set_requesting_user($userparam[0]);
3300 $mapper = \core_calendar\local\event\container::get_event_mapper();
3301 $events = \core_calendar\local\api::get_events(
3302 $tstart,
3303 $tend,
3304 null,
3305 null,
3306 null,
3307 null,
3308 $limitnum,
3309 null,
3310 $userparam,
3311 $groupparam,
3312 $courseparam,
3313 $categoryparam,
3314 $withduration,
3315 $ignorehidden
3318 return array_reduce($events, function($carry, $event) use ($mapper) {
3319 return $carry + [$event->get_id() => $mapper->from_event_to_stdclass($event)];
3320 }, []);
3325 * Get the calendar view output.
3327 * @param \calendar_information $calendar The calendar being represented
3328 * @param string $view The type of calendar to have displayed
3329 * @param bool $includenavigation Whether to include navigation
3330 * @param bool $skipevents Whether to load the events or not
3331 * @param int $lookahead Overwrites site and users's lookahead setting.
3332 * @return array[array, string]
3334 function calendar_get_view(\calendar_information $calendar, $view, $includenavigation = true, bool $skipevents = false,
3335 ?int $lookahead = null) {
3336 global $PAGE, $CFG;
3338 $renderer = $PAGE->get_renderer('core_calendar');
3339 $type = \core_calendar\type_factory::get_calendar_instance();
3341 // Calculate the bounds of the month.
3342 $calendardate = $type->timestamp_to_date_array($calendar->time);
3344 $date = new \DateTime('now', core_date::get_user_timezone_object(99));
3345 $eventlimit = 0;
3347 if ($view === 'day') {
3348 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday']);
3349 $date->setTimestamp($tstart);
3350 $date->modify('+1 day');
3351 } else if ($view === 'upcoming' || $view === 'upcoming_mini') {
3352 // Number of days in the future that will be used to fetch events.
3353 if (!$lookahead) {
3354 if (isset($CFG->calendar_lookahead)) {
3355 $defaultlookahead = intval($CFG->calendar_lookahead);
3356 } else {
3357 $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD;
3359 $lookahead = get_user_preferences('calendar_lookahead', $defaultlookahead);
3362 // Maximum number of events to be displayed on upcoming view.
3363 $defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS;
3364 if (isset($CFG->calendar_maxevents)) {
3365 $defaultmaxevents = intval($CFG->calendar_maxevents);
3367 $eventlimit = get_user_preferences('calendar_maxevents', $defaultmaxevents);
3369 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday'],
3370 $calendardate['hours']);
3371 $date->setTimestamp($tstart);
3372 $date->modify('+' . $lookahead . ' days');
3373 } else {
3374 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], 1);
3375 $monthdays = $type->get_num_days_in_month($calendardate['year'], $calendardate['mon']);
3376 $date->setTimestamp($tstart);
3377 $date->modify('+' . $monthdays . ' days');
3379 if ($view === 'mini' || $view === 'minithree') {
3380 $template = 'core_calendar/calendar_mini';
3381 } else {
3382 $template = 'core_calendar/calendar_month';
3386 // We need to extract 1 second to ensure that we don't get into the next day.
3387 $date->modify('-1 second');
3388 $tend = $date->getTimestamp();
3390 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3391 // If parameter is true, return null.
3392 if ($param === true) {
3393 return null;
3396 // If parameter is false, return an empty array.
3397 if ($param === false) {
3398 return [];
3401 // If the parameter is a scalar value, enclose it in an array.
3402 if (!is_array($param)) {
3403 return [$param];
3406 // No normalisation required.
3407 return $param;
3408 }, [$calendar->users, $calendar->groups, $calendar->courses, $calendar->categories]);
3410 if ($skipevents) {
3411 $events = [];
3412 } else {
3413 $events = \core_calendar\local\api::get_events(
3414 $tstart,
3415 $tend,
3416 null,
3417 null,
3418 null,
3419 null,
3420 $eventlimit,
3421 null,
3422 $userparam,
3423 $groupparam,
3424 $courseparam,
3425 $categoryparam,
3426 true,
3427 true,
3428 function ($event) {
3429 if ($proxy = $event->get_course_module()) {
3430 $cminfo = $proxy->get_proxied_instance();
3431 return $cminfo->uservisible;
3434 if ($proxy = $event->get_category()) {
3435 $category = $proxy->get_proxied_instance();
3437 return $category->is_uservisible();
3440 return true;
3445 $related = [
3446 'events' => $events,
3447 'cache' => new \core_calendar\external\events_related_objects_cache($events),
3448 'type' => $type,
3451 $data = [];
3452 if ($view == "month" || $view == "mini" || $view == "minithree") {
3453 $month = new \core_calendar\external\month_exporter($calendar, $type, $related);
3454 $month->set_includenavigation($includenavigation);
3455 $month->set_initialeventsloaded(!$skipevents);
3456 $month->set_showcoursefilter($view == "month");
3457 $data = $month->export($renderer);
3458 } else if ($view == "day") {
3459 $day = new \core_calendar\external\calendar_day_exporter($calendar, $related);
3460 $data = $day->export($renderer);
3461 $template = 'core_calendar/calendar_day';
3462 } else if ($view == "upcoming" || $view == "upcoming_mini") {
3463 $upcoming = new \core_calendar\external\calendar_upcoming_exporter($calendar, $related);
3464 $data = $upcoming->export($renderer);
3466 if ($view == "upcoming") {
3467 $template = 'core_calendar/calendar_upcoming';
3468 } else if ($view == "upcoming_mini") {
3469 $template = 'core_calendar/calendar_upcoming_mini';
3473 return [$data, $template];
3477 * Request and render event form fragment.
3479 * @param array $args The fragment arguments.
3480 * @return string The rendered mform fragment.
3482 function calendar_output_fragment_event_form($args) {
3483 global $CFG, $OUTPUT, $USER;
3484 require_once($CFG->libdir . '/grouplib.php');
3485 $html = '';
3486 $data = [];
3487 $eventid = isset($args['eventid']) ? clean_param($args['eventid'], PARAM_INT) : null;
3488 $starttime = isset($args['starttime']) ? clean_param($args['starttime'], PARAM_INT) : null;
3489 $courseid = (isset($args['courseid']) && $args['courseid'] != SITEID) ? clean_param($args['courseid'], PARAM_INT) : null;
3490 $categoryid = isset($args['categoryid']) ? clean_param($args['categoryid'], PARAM_INT) : null;
3491 $event = null;
3492 $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
3493 $context = \context_user::instance($USER->id);
3494 $editoroptions = \core_calendar\local\event\forms\create::build_editor_options($context);
3495 $formoptions = ['editoroptions' => $editoroptions, 'courseid' => $courseid];
3496 $draftitemid = 0;
3498 if ($hasformdata) {
3499 parse_str(clean_param($args['formdata'], PARAM_TEXT), $data);
3500 if (isset($data['description']['itemid'])) {
3501 $draftitemid = $data['description']['itemid'];
3505 if ($starttime) {
3506 $formoptions['starttime'] = $starttime;
3509 if (is_null($eventid)) {
3510 if (!empty($courseid)) {
3511 $groupcoursedata = groups_get_course_data($courseid);
3512 $formoptions['groups'] = [];
3513 foreach ($groupcoursedata->groups as $groupid => $groupdata) {
3514 $formoptions['groups'][$groupid] = $groupdata->name;
3517 $mform = new \core_calendar\local\event\forms\create(
3518 null,
3519 $formoptions,
3520 'post',
3522 null,
3523 true,
3524 $data
3527 // Let's check first which event types user can add.
3528 $eventtypes = calendar_get_allowed_event_types($courseid);
3530 // If the user is on course context and is allowed to add course events set the event type default to course.
3531 if (!empty($courseid) && !empty($eventtypes['course'])) {
3532 $data['eventtype'] = 'course';
3533 $data['courseid'] = $courseid;
3534 $data['groupcourseid'] = $courseid;
3535 } else if (!empty($categoryid) && !empty($eventtypes['category'])) {
3536 $data['eventtype'] = 'category';
3537 $data['categoryid'] = $categoryid;
3538 } else if (!empty($groupcoursedata) && !empty($eventtypes['group'])) {
3539 $data['groupcourseid'] = $courseid;
3540 $data['groups'] = $groupcoursedata->groups;
3542 $mform->set_data($data);
3543 } else {
3544 $event = calendar_event::load($eventid);
3546 if (!calendar_edit_event_allowed($event)) {
3547 print_error('nopermissiontoupdatecalendar');
3550 $mapper = new \core_calendar\local\event\mappers\create_update_form_mapper();
3551 $eventdata = $mapper->from_legacy_event_to_data($event);
3552 $data = array_merge((array) $eventdata, $data);
3553 $event->count_repeats();
3554 $formoptions['event'] = $event;
3556 if (!empty($event->courseid)) {
3557 $groupcoursedata = groups_get_course_data($event->courseid);
3558 $formoptions['groups'] = [];
3559 foreach ($groupcoursedata->groups as $groupid => $groupdata) {
3560 $formoptions['groups'][$groupid] = $groupdata->name;
3564 $data['description']['text'] = file_prepare_draft_area(
3565 $draftitemid,
3566 $event->context->id,
3567 'calendar',
3568 'event_description',
3569 $event->id,
3570 null,
3571 $data['description']['text']
3573 $data['description']['itemid'] = $draftitemid;
3575 $mform = new \core_calendar\local\event\forms\update(
3576 null,
3577 $formoptions,
3578 'post',
3580 null,
3581 true,
3582 $data
3584 $mform->set_data($data);
3586 // Check to see if this event is part of a subscription or import.
3587 // If so display a warning on edit.
3588 if (isset($event->subscriptionid) && ($event->subscriptionid != null)) {
3589 $renderable = new \core\output\notification(
3590 get_string('eventsubscriptioneditwarning', 'calendar'),
3591 \core\output\notification::NOTIFY_INFO
3594 $html .= $OUTPUT->render($renderable);
3598 if ($hasformdata) {
3599 $mform->is_validated();
3602 $html .= $mform->render();
3603 return $html;
3607 * Calculate the timestamp from the supplied Gregorian Year, Month, and Day.
3609 * @param int $d The day
3610 * @param int $m The month
3611 * @param int $y The year
3612 * @param int $time The timestamp to use instead of a separate y/m/d.
3613 * @return int The timestamp
3615 function calendar_get_timestamp($d, $m, $y, $time = 0) {
3616 // If a day, month and year were passed then convert it to a timestamp. If these were passed
3617 // then we can assume the day, month and year are passed as Gregorian, as no where in core
3618 // should we be passing these values rather than the time.
3619 if (!empty($d) && !empty($m) && !empty($y)) {
3620 if (checkdate($m, $d, $y)) {
3621 $time = make_timestamp($y, $m, $d);
3622 } else {
3623 $time = time();
3625 } else if (empty($time)) {
3626 $time = time();
3629 return $time;
3633 * Get the calendar footer options.
3635 * @param calendar_information $calendar The calendar information object.
3636 * @return array The data for template and template name.
3638 function calendar_get_footer_options($calendar) {
3639 global $CFG, $USER, $DB, $PAGE;
3641 // Generate hash for iCal link.
3642 $rawhash = $USER->id . $DB->get_field('user', 'password', ['id' => $USER->id]) . $CFG->calendar_exportsalt;
3643 $authtoken = sha1($rawhash);
3645 $renderer = $PAGE->get_renderer('core_calendar');
3646 $footer = new \core_calendar\external\footer_options_exporter($calendar, $USER->id, $authtoken);
3647 $data = $footer->export($renderer);
3648 $template = 'core_calendar/footer_options';
3650 return [$data, $template];
3654 * Get the list of potential calendar filter types as a type => name
3655 * combination.
3657 * @return array
3659 function calendar_get_filter_types() {
3660 $types = [
3661 'site',
3662 'category',
3663 'course',
3664 'group',
3665 'user',
3668 return array_map(function($type) {
3669 return [
3670 'eventtype' => $type,
3671 'name' => get_string("eventtype{$type}", "calendar"),
3672 'icon' => true,
3673 'key' => 'i/'.$type.'event',
3674 'component' => 'core'
3676 }, $types);
3680 * Check whether the specified event type is valid.
3682 * @param string $type
3683 * @return bool
3685 function calendar_is_valid_eventtype($type) {
3686 $validtypes = [
3687 'user',
3688 'group',
3689 'course',
3690 'category',
3691 'site',
3693 return in_array($type, $validtypes);
3697 * Get event types the user can create event based on categories, courses and groups
3698 * the logged in user belongs to.
3700 * @param int|null $courseid The course id.
3701 * @return array The array of allowed types.
3703 function calendar_get_allowed_event_types(int $courseid = null) {
3704 global $DB, $CFG, $USER;
3706 $types = [
3707 'user' => false,
3708 'site' => false,
3709 'course' => false,
3710 'group' => false,
3711 'category' => false
3714 if (!empty($courseid) && $courseid != SITEID) {
3715 $context = \context_course::instance($courseid);
3716 $types['user'] = has_capability('moodle/calendar:manageownentries', $context);
3717 calendar_internal_update_course_and_group_permission($courseid, $context, $types);
3720 if (has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID))) {
3721 $types['site'] = true;
3724 if (has_capability('moodle/calendar:manageownentries', \context_system::instance())) {
3725 $types['user'] = true;
3727 if (core_course_category::has_manage_capability_on_any()) {
3728 $types['category'] = true;
3731 // We still don't know if the user can create group and course events, so iterate over the courses to find out
3732 // if the user has capabilities in one of the courses.
3733 if ($types['course'] == false || $types['group'] == false) {
3734 if ($CFG->calendar_adminseesall && has_capability('moodle/calendar:manageentries', context_system::instance())) {
3735 $sql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3736 FROM {course} c
3737 JOIN {context} ctx ON ctx.contextlevel = ? AND ctx.instanceid = c.id
3738 WHERE c.id IN (
3739 SELECT DISTINCT courseid FROM {groups}
3741 $courseswithgroups = $DB->get_recordset_sql($sql, [CONTEXT_COURSE]);
3742 foreach ($courseswithgroups as $course) {
3743 context_helper::preload_from_record($course);
3744 $context = context_course::instance($course->id);
3746 if (has_capability('moodle/calendar:manageentries', $context)) {
3747 if (has_any_capability(['moodle/site:accessallgroups', 'moodle/calendar:managegroupentries'], $context)) {
3748 // The user can manage group entries or access any group.
3749 $types['group'] = true;
3750 $types['course'] = true;
3751 break;
3755 $courseswithgroups->close();
3757 if (false === $types['course']) {
3758 // Course is still not confirmed. There may have been no courses with a group in them.
3759 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
3760 $sql = "SELECT
3761 c.id, c.visible, {$ctxfields}
3762 FROM {course} c
3763 JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
3764 $params = [
3765 'contextlevel' => CONTEXT_COURSE,
3767 $courses = $DB->get_recordset_sql($sql, $params);
3768 foreach ($courses as $course) {
3769 context_helper::preload_from_record($course);
3770 $context = context_course::instance($course->id);
3771 if (has_capability('moodle/calendar:manageentries', $context)) {
3772 $types['course'] = true;
3773 break;
3776 $courses->close();
3779 } else {
3780 $courses = calendar_get_default_courses(null, 'id');
3781 if (empty($courses)) {
3782 return $types;
3785 $courseids = array_map(function($c) {
3786 return $c->id;
3787 }, $courses);
3789 // Check whether the user has access to create events within courses which have groups.
3790 list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
3791 $sql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3792 FROM {course} c
3793 JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3794 WHERE c.id $insql
3795 AND c.id IN (SELECT DISTINCT courseid FROM {groups})";
3796 $params['contextlevel'] = CONTEXT_COURSE;
3797 $courseswithgroups = $DB->get_recordset_sql($sql, $params);
3798 foreach ($courseswithgroups as $coursewithgroup) {
3799 context_helper::preload_from_record($coursewithgroup);
3800 $context = context_course::instance($coursewithgroup->id);
3802 calendar_internal_update_course_and_group_permission($coursewithgroup->id, $context, $types);
3804 // Okay, course and group event types are allowed, no need to keep the loop iteration.
3805 if ($types['course'] == true && $types['group'] == true) {
3806 break;
3809 $courseswithgroups->close();
3811 if (false === $types['course']) {
3812 list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
3813 $contextsql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3814 FROM {course} c
3815 JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3816 WHERE c.id $insql";
3817 $params['contextlevel'] = CONTEXT_COURSE;
3818 $contextrecords = $DB->get_recordset_sql($contextsql, $params);
3819 foreach ($contextrecords as $course) {
3820 context_helper::preload_from_record($course);
3821 $coursecontext = context_course::instance($course->id);
3822 if (has_capability('moodle/calendar:manageentries', $coursecontext)
3823 && ($courseid == $course->id || empty($courseid))) {
3824 $types['course'] = true;
3825 break;
3828 $contextrecords->close();
3834 return $types;
3838 * Given a course id, and context, updates the permission types array to add the 'course' or 'group'
3839 * permission if it is relevant for that course.
3841 * For efficiency, if they already have 'course' or 'group' then it skips checks.
3843 * Do not call this function directly, it is only for use by calendar_get_allowed_event_types().
3845 * @param int $courseid Course id
3846 * @param context $context Context for that course
3847 * @param array $types Current permissions
3849 function calendar_internal_update_course_and_group_permission(int $courseid, context $context, array &$types) {
3850 if (!$types['course']) {
3851 // If they have manageentries permission on the course, then they can update this course.
3852 if (has_capability('moodle/calendar:manageentries', $context)) {
3853 $types['course'] = true;
3856 // To update group events they must have EITHER manageentries OR managegroupentries.
3857 if (!$types['group'] && (has_capability('moodle/calendar:manageentries', $context) ||
3858 has_capability('moodle/calendar:managegroupentries', $context))) {
3859 // And they also need for a group to exist on the course.
3860 $groups = groups_get_all_groups($courseid);
3861 if (!empty($groups)) {
3862 // And either accessallgroups, or belong to one of the groups.
3863 if (has_capability('moodle/site:accessallgroups', $context)) {
3864 $types['group'] = true;
3865 } else {
3866 foreach ($groups as $group) {
3867 if (groups_is_member($group->id)) {
3868 $types['group'] = true;
3869 break;