MDL-51177 core: Ignore built files in stylelint
[moodle.git] / calendar / lib.php
blob2a0bc58977ff35807774328ab6d7d38e85835244
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 - imported event was updated
110 define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
113 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
115 define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
118 * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
120 define('CALENDAR_SUBSCRIPTION_UPDATE', 1);
123 * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
125 define('CALENDAR_SUBSCRIPTION_REMOVE', 2);
128 * CALENDAR_EVENT_USER_OVERRIDE_PRIORITY - Constant for the user override priority.
130 define('CALENDAR_EVENT_USER_OVERRIDE_PRIORITY', 0);
133 * CALENDAR_EVENT_TYPE_STANDARD - Standard events.
135 define('CALENDAR_EVENT_TYPE_STANDARD', 0);
138 * CALENDAR_EVENT_TYPE_ACTION - Action events.
140 define('CALENDAR_EVENT_TYPE_ACTION', 1);
143 * Manage calendar events.
145 * This class provides the required functionality in order to manage calendar events.
146 * It was introduced as part of Moodle 2.0 and was created in order to provide a
147 * better framework for dealing with calendar events in particular regard to file
148 * handling through the new file API.
150 * @package core_calendar
151 * @category calendar
152 * @copyright 2009 Sam Hemelryk
153 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
155 * @property int $id The id within the event table
156 * @property string $name The name of the event
157 * @property string $description The description of the event
158 * @property int $format The format of the description FORMAT_?
159 * @property int $courseid The course the event is associated with (0 if none)
160 * @property int $groupid The group the event is associated with (0 if none)
161 * @property int $userid The user the event is associated with (0 if none)
162 * @property int $repeatid If this is a repeated event this will be set to the
163 * id of the original
164 * @property string $modulename If added by a module this will be the module name
165 * @property int $instance If added by a module this will be the module instance
166 * @property string $eventtype The event type
167 * @property int $timestart The start time as a timestamp
168 * @property int $timeduration The duration of the event in seconds
169 * @property int $visible 1 if the event is visible
170 * @property int $uuid ?
171 * @property int $sequence ?
172 * @property int $timemodified The time last modified as a timestamp
174 class calendar_event {
176 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
177 protected $properties = null;
179 /** @var string The converted event discription with file paths resolved.
180 * This gets populated when someone requests description for the first time */
181 protected $_description = null;
183 /** @var array The options to use with this description editor */
184 protected $editoroptions = array(
185 'subdirs' => false,
186 'forcehttps' => false,
187 'maxfiles' => -1,
188 'maxbytes' => null,
189 'trusttext' => false);
191 /** @var object The context to use with the description editor */
192 protected $editorcontext = null;
195 * Instantiates a new event and optionally populates its properties with the data provided.
197 * @param \stdClass $data Optional. An object containing the properties to for
198 * an event
200 public function __construct($data = null) {
201 global $CFG, $USER;
203 // First convert to object if it is not already (should either be object or assoc array).
204 if (!is_object($data)) {
205 $data = (object) $data;
208 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
210 $data->eventrepeats = 0;
212 if (empty($data->id)) {
213 $data->id = null;
216 if (!empty($data->subscriptionid)) {
217 $data->subscription = calendar_get_subscription($data->subscriptionid);
220 // Default to a user event.
221 if (empty($data->eventtype)) {
222 $data->eventtype = 'user';
225 // Default to the current user.
226 if (empty($data->userid)) {
227 $data->userid = $USER->id;
230 if (!empty($data->timeduration) && is_array($data->timeduration)) {
231 $data->timeduration = make_timestamp(
232 $data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'],
233 $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
236 if (!empty($data->description) && is_array($data->description)) {
237 $data->format = $data->description['format'];
238 $data->description = $data->description['text'];
239 } else if (empty($data->description)) {
240 $data->description = '';
241 $data->format = editors_get_preferred_format();
244 // Ensure form is defaulted correctly.
245 if (empty($data->format)) {
246 $data->format = editors_get_preferred_format();
249 $this->properties = $data;
253 * Magic set method.
255 * Attempts to call a set_$key method if one exists otherwise falls back
256 * to simply set the property.
258 * @param string $key property name
259 * @param mixed $value value of the property
261 public function __set($key, $value) {
262 if (method_exists($this, 'set_'.$key)) {
263 $this->{'set_'.$key}($value);
265 $this->properties->{$key} = $value;
269 * Magic get method.
271 * Attempts to call a get_$key method to return the property and ralls over
272 * to return the raw property.
274 * @param string $key property name
275 * @return mixed property value
276 * @throws \coding_exception
278 public function __get($key) {
279 if (method_exists($this, 'get_'.$key)) {
280 return $this->{'get_'.$key}();
282 if (!property_exists($this->properties, $key)) {
283 throw new \coding_exception('Undefined property requested');
285 return $this->properties->{$key};
289 * Magic isset method.
291 * PHP needs an isset magic method if you use the get magic method and
292 * still want empty calls to work.
294 * @param string $key $key property name
295 * @return bool|mixed property value, false if property is not exist
297 public function __isset($key) {
298 return !empty($this->properties->{$key});
302 * Calculate the context value needed for an event.
304 * Event's type can be determine by the available value store in $data
305 * It is important to check for the existence of course/courseid to determine
306 * the course event.
307 * Default value is set to CONTEXT_USER
309 * @return \stdClass The context object.
311 protected function calculate_context() {
312 global $USER, $DB;
314 $context = null;
315 if (isset($this->properties->categoryid) && $this->properties->categoryid > 0) {
316 $context = \context_coursecat::instance($this->properties->categoryid);
317 } else if (isset($this->properties->courseid) && $this->properties->courseid > 0) {
318 $context = \context_course::instance($this->properties->courseid);
319 } else if (isset($this->properties->course) && $this->properties->course > 0) {
320 $context = \context_course::instance($this->properties->course);
321 } else if (isset($this->properties->groupid) && $this->properties->groupid > 0) {
322 $group = $DB->get_record('groups', array('id' => $this->properties->groupid));
323 $context = \context_course::instance($group->courseid);
324 } else if (isset($this->properties->userid) && $this->properties->userid > 0
325 && $this->properties->userid == $USER->id) {
326 $context = \context_user::instance($this->properties->userid);
327 } else if (isset($this->properties->userid) && $this->properties->userid > 0
328 && $this->properties->userid != $USER->id &&
329 isset($this->properties->instance) && $this->properties->instance > 0) {
330 $cm = get_coursemodule_from_instance($this->properties->modulename, $this->properties->instance, 0,
331 false, MUST_EXIST);
332 $context = \context_course::instance($cm->course);
333 } else {
334 $context = \context_user::instance($this->properties->userid);
337 return $context;
341 * Returns the context for this event. The context is calculated
342 * the first time is is requested and then stored in a member
343 * variable to be returned each subsequent time.
345 * This is a magical getter function that will be called when
346 * ever the context property is accessed, e.g. $event->context.
348 * @return context
350 protected function get_context() {
351 if (!isset($this->properties->context)) {
352 $this->properties->context = $this->calculate_context();
355 return $this->properties->context;
359 * Returns an array of editoroptions for this event.
361 * @return array event editor options
363 protected function get_editoroptions() {
364 return $this->editoroptions;
368 * Returns an event description: Called by __get
369 * Please use $blah = $event->description;
371 * @return string event description
373 protected function get_description() {
374 global $CFG;
376 require_once($CFG->libdir . '/filelib.php');
378 if ($this->_description === null) {
379 // Check if we have already resolved the context for this event.
380 if ($this->editorcontext === null) {
381 // Switch on the event type to decide upon the appropriate context to use for this event.
382 $this->editorcontext = $this->get_context();
383 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
384 return clean_text($this->properties->description, $this->properties->format);
388 // Work out the item id for the editor, if this is a repeated event
389 // then the files will be associated with the original.
390 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
391 $itemid = $this->properties->repeatid;
392 } else {
393 $itemid = $this->properties->id;
396 // Convert file paths in the description so that things display correctly.
397 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php',
398 $this->editorcontext->id, 'calendar', 'event_description', $itemid);
399 // Clean the text so no nasties get through.
400 $this->_description = clean_text($this->_description, $this->properties->format);
403 // Finally return the description.
404 return $this->_description;
408 * Return the number of repeat events there are in this events series.
410 * @return int number of event repeated
412 public function count_repeats() {
413 global $DB;
414 if (!empty($this->properties->repeatid)) {
415 $this->properties->eventrepeats = $DB->count_records('event',
416 array('repeatid' => $this->properties->repeatid));
417 // We don't want to count ourselves.
418 $this->properties->eventrepeats--;
420 return $this->properties->eventrepeats;
424 * Update or create an event within the database
426 * Pass in a object containing the event properties and this function will
427 * insert it into the database and deal with any associated files
429 * Capability checking should be performed if the user is directly manipulating the event
430 * and no other capability has been tested. However if the event is not being manipulated
431 * directly by the user and another capability has been checked for them to do this then
432 * capabilites should not be checked.
434 * For example if a user is editing an event in the calendar the check should be true,
435 * but if you are updating an event in an activities settings are changed then the calendar
436 * capabilites should not be checked.
438 * @see self::create()
439 * @see self::update()
441 * @param \stdClass $data object of event
442 * @param bool $checkcapability If Moodle should check the user can manage the calendar events for this call or not.
443 * @return bool event updated
445 public function update($data, $checkcapability=true) {
446 global $DB, $USER;
448 foreach ($data as $key => $value) {
449 $this->properties->$key = $value;
452 $this->properties->timemodified = time();
453 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
455 // Prepare event data.
456 $eventargs = array(
457 'context' => $this->get_context(),
458 'objectid' => $this->properties->id,
459 'other' => array(
460 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
461 'timestart' => $this->properties->timestart,
462 'name' => $this->properties->name
466 if (empty($this->properties->id) || $this->properties->id < 1) {
467 if ($checkcapability) {
468 if (!calendar_add_event_allowed($this->properties)) {
469 print_error('nopermissiontoupdatecalendar');
473 if ($usingeditor) {
474 switch ($this->properties->eventtype) {
475 case 'user':
476 $this->properties->courseid = 0;
477 $this->properties->course = 0;
478 $this->properties->groupid = 0;
479 $this->properties->userid = $USER->id;
480 break;
481 case 'site':
482 $this->properties->courseid = SITEID;
483 $this->properties->course = SITEID;
484 $this->properties->groupid = 0;
485 $this->properties->userid = $USER->id;
486 break;
487 case 'course':
488 $this->properties->groupid = 0;
489 $this->properties->userid = $USER->id;
490 break;
491 case 'category':
492 $this->properties->groupid = 0;
493 $this->properties->category = 0;
494 $this->properties->userid = $USER->id;
495 break;
496 case 'group':
497 $this->properties->userid = $USER->id;
498 break;
499 default:
500 // We should NEVER get here, but just incase we do lets fail gracefully.
501 $usingeditor = false;
502 break;
505 // If we are actually using the editor, we recalculate the context because some default values
506 // were set when calculate_context() was called from the constructor.
507 if ($usingeditor) {
508 $this->properties->context = $this->calculate_context();
509 $this->editorcontext = $this->get_context();
512 $editor = $this->properties->description;
513 $this->properties->format = $this->properties->description['format'];
514 $this->properties->description = $this->properties->description['text'];
517 // Insert the event into the database.
518 $this->properties->id = $DB->insert_record('event', $this->properties);
520 if ($usingeditor) {
521 $this->properties->description = file_save_draft_area_files(
522 $editor['itemid'],
523 $this->editorcontext->id,
524 'calendar',
525 'event_description',
526 $this->properties->id,
527 $this->editoroptions,
528 $editor['text'],
529 $this->editoroptions['forcehttps']);
530 $DB->set_field('event', 'description', $this->properties->description,
531 array('id' => $this->properties->id));
534 // Log the event entry.
535 $eventargs['objectid'] = $this->properties->id;
536 $eventargs['context'] = $this->get_context();
537 $event = \core\event\calendar_event_created::create($eventargs);
538 $event->trigger();
540 $repeatedids = array();
542 if (!empty($this->properties->repeat)) {
543 $this->properties->repeatid = $this->properties->id;
544 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id' => $this->properties->id));
546 $eventcopy = clone($this->properties);
547 unset($eventcopy->id);
549 $timestart = new \DateTime('@' . $eventcopy->timestart);
550 $timestart->setTimezone(\core_date::get_user_timezone_object());
552 for ($i = 1; $i < $eventcopy->repeats; $i++) {
554 $timestart->add(new \DateInterval('P7D'));
555 $eventcopy->timestart = $timestart->getTimestamp();
557 // Get the event id for the log record.
558 $eventcopyid = $DB->insert_record('event', $eventcopy);
560 // If the context has been set delete all associated files.
561 if ($usingeditor) {
562 $fs = get_file_storage();
563 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description',
564 $this->properties->id);
565 foreach ($files as $file) {
566 $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
570 $repeatedids[] = $eventcopyid;
572 // Trigger an event.
573 $eventargs['objectid'] = $eventcopyid;
574 $eventargs['other']['timestart'] = $eventcopy->timestart;
575 $event = \core\event\calendar_event_created::create($eventargs);
576 $event->trigger();
580 return true;
581 } else {
583 if ($checkcapability) {
584 if (!calendar_edit_event_allowed($this->properties)) {
585 print_error('nopermissiontoupdatecalendar');
589 if ($usingeditor) {
590 if ($this->editorcontext !== null) {
591 $this->properties->description = file_save_draft_area_files(
592 $this->properties->description['itemid'],
593 $this->editorcontext->id,
594 'calendar',
595 'event_description',
596 $this->properties->id,
597 $this->editoroptions,
598 $this->properties->description['text'],
599 $this->editoroptions['forcehttps']);
600 } else {
601 $this->properties->format = $this->properties->description['format'];
602 $this->properties->description = $this->properties->description['text'];
606 $event = $DB->get_record('event', array('id' => $this->properties->id));
608 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
610 if ($updaterepeated) {
611 // Update all.
612 if ($this->properties->timestart != $event->timestart) {
613 $timestartoffset = $this->properties->timestart - $event->timestart;
614 $sql = "UPDATE {event}
615 SET name = ?,
616 description = ?,
617 timestart = timestart + ?,
618 timeduration = ?,
619 timemodified = ?,
620 groupid = ?,
621 courseid = ?
622 WHERE repeatid = ?";
623 // Note: Group and course id may not be set. If not, keep their current values.
624 $params = [
625 $this->properties->name,
626 $this->properties->description,
627 $timestartoffset,
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,
632 $event->repeatid
634 } else {
635 $sql = "UPDATE {event}
636 SET name = ?,
637 description = ?,
638 timeduration = ?,
639 timemodified = ?,
640 groupid = ?,
641 courseid = ?
642 WHERE repeatid = ?";
643 // Note: Group and course id may not be set. If not, keep their current values.
644 $params = [
645 $this->properties->name,
646 $this->properties->description,
647 $this->properties->timeduration,
648 time(),
649 isset($this->properties->groupid) ? $this->properties->groupid : $event->groupid,
650 isset($this->properties->courseid) ? $this->properties->courseid : $event->courseid,
651 $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;
2206 $mycourses = enrol_get_my_courses('id');
2207 return isset($mycourses[$event->courseid]);
2208 } else if ($event->userid) {
2209 if ($event->userid != $USER->id) {
2210 // No-one can ever see another users events.
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($value);
2356 }, $fieldlist);
2357 $courses = get_courses('all', 'c.shortname', implode(',', $prefixedfields));
2358 } else {
2359 $courses = enrol_get_users_courses($userid, true, $fields);
2362 if ($courseid && $courseid != SITEID) {
2363 if (empty($courses[$courseid]) && has_capability('moodle/calendar:manageentries', context_system::instance(), $userid)) {
2364 // Allow a site admin to see calendars from courses he is not enrolled in.
2365 // This will come from $COURSE.
2366 $courses[$courseid] = get_course($courseid);
2370 return $courses;
2374 * Get event format time.
2376 * @param calendar_event $event event object
2377 * @param int $now current time in gmt
2378 * @param array $linkparams list of params for event link
2379 * @param bool $usecommonwords the words as formatted date/time.
2380 * @param int $showtime determine the show time GMT timestamp
2381 * @return string $eventtime link/string for event time
2383 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
2384 $starttime = $event->timestart;
2385 $endtime = $event->timestart + $event->timeduration;
2387 if (empty($linkparams) || !is_array($linkparams)) {
2388 $linkparams = array();
2391 $linkparams['view'] = 'day';
2393 // OK, now to get a meaningful display.
2394 // Check if there is a duration for this event.
2395 if ($event->timeduration) {
2396 // Get the midnight of the day the event will start.
2397 $usermidnightstart = usergetmidnight($starttime);
2398 // Get the midnight of the day the event will end.
2399 $usermidnightend = usergetmidnight($endtime);
2400 // Check if we will still be on the same day.
2401 if ($usermidnightstart == $usermidnightend) {
2402 // Check if we are running all day.
2403 if ($event->timeduration == DAYSECS) {
2404 $time = get_string('allday', 'calendar');
2405 } else { // Specify the time we will be running this from.
2406 $datestart = calendar_time_representation($starttime);
2407 $dateend = calendar_time_representation($endtime);
2408 $time = $datestart . ' <strong>&raquo;</strong> ' . $dateend;
2411 // Set printable representation.
2412 if (!$showtime) {
2413 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2414 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2415 $eventtime = \html_writer::link($url, $day) . ', ' . $time;
2416 } else {
2417 $eventtime = $time;
2419 } else { // It must spans two or more days.
2420 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
2421 if ($showtime == $usermidnightstart) {
2422 $daystart = '';
2424 $timestart = calendar_time_representation($event->timestart);
2425 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
2426 if ($showtime == $usermidnightend) {
2427 $dayend = '';
2429 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
2431 // Set printable representation.
2432 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2433 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2434 $eventtime = $timestart . ' <strong>&raquo;</strong> ' . \html_writer::link($url, $dayend) . $timeend;
2435 } else {
2436 // The event is in the future, print start and end links.
2437 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2438 $eventtime = \html_writer::link($url, $daystart) . $timestart . ' <strong>&raquo;</strong> ';
2440 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2441 $eventtime .= \html_writer::link($url, $dayend) . $timeend;
2444 } else { // There is no time duration.
2445 $time = calendar_time_representation($event->timestart);
2446 // Set printable representation.
2447 if (!$showtime) {
2448 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2449 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2450 $eventtime = \html_writer::link($url, $day) . ', ' . trim($time);
2451 } else {
2452 $eventtime = $time;
2456 // Check if It has expired.
2457 if ($event->timestart + $event->timeduration < $now) {
2458 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2461 return $eventtime;
2465 * Checks to see if the requested type of event should be shown for the given user.
2467 * @param int $type The type to check the display for (default is to display all)
2468 * @param stdClass|int|null $user The user to check for - by default the current user
2469 * @return bool True if the tyep should be displayed false otherwise
2471 function calendar_show_event_type($type, $user = null) {
2472 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
2474 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2475 global $SESSION;
2476 if (!isset($SESSION->calendarshoweventtype)) {
2477 $SESSION->calendarshoweventtype = $default;
2479 return $SESSION->calendarshoweventtype & $type;
2480 } else {
2481 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2486 * Sets the display of the event type given $display.
2488 * If $display = true the event type will be shown.
2489 * If $display = false the event type will NOT be shown.
2490 * If $display = null the current value will be toggled and saved.
2492 * @param int $type object of CALENDAR_EVENT_XXX
2493 * @param bool $display option to display event type
2494 * @param stdClass|int $user moodle user object or id, null means current user
2496 function calendar_set_event_type_display($type, $display = null, $user = null) {
2497 $persist = get_user_preferences('calendar_persistflt', 0, $user);
2498 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP
2499 + CALENDAR_EVENT_USER + CALENDAR_EVENT_COURSECAT;
2500 if ($persist === 0) {
2501 global $SESSION;
2502 if (!isset($SESSION->calendarshoweventtype)) {
2503 $SESSION->calendarshoweventtype = $default;
2505 $preference = $SESSION->calendarshoweventtype;
2506 } else {
2507 $preference = get_user_preferences('calendar_savedflt', $default, $user);
2509 $current = $preference & $type;
2510 if ($display === null) {
2511 $display = !$current;
2513 if ($display && !$current) {
2514 $preference += $type;
2515 } else if (!$display && $current) {
2516 $preference -= $type;
2518 if ($persist === 0) {
2519 $SESSION->calendarshoweventtype = $preference;
2520 } else {
2521 if ($preference == $default) {
2522 unset_user_preference('calendar_savedflt', $user);
2523 } else {
2524 set_user_preference('calendar_savedflt', $preference, $user);
2530 * Get calendar's allowed types.
2532 * @param stdClass $allowed list of allowed edit for event type
2533 * @param stdClass|int $course object of a course or course id
2534 * @param array $groups array of groups for the given course
2535 * @param stdClass|int $category object of a category
2537 function calendar_get_allowed_types(&$allowed, $course = null, $groups = null, $category = null) {
2538 global $USER, $DB;
2540 $allowed = new \stdClass();
2541 $allowed->user = has_capability('moodle/calendar:manageownentries', \context_system::instance());
2542 $allowed->groups = false;
2543 $allowed->courses = false;
2544 $allowed->categories = false;
2545 $allowed->site = has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID));
2546 $getgroupsfunc = function($course, $context, $user) use ($groups) {
2547 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2548 if (has_capability('moodle/site:accessallgroups', $context)) {
2549 return is_null($groups) ? groups_get_all_groups($course->id) : $groups;
2550 } else {
2551 if (is_null($groups)) {
2552 return groups_get_all_groups($course->id, $user->id);
2553 } else {
2554 return array_filter($groups, function($group) use ($user) {
2555 return isset($group->members[$user->id]);
2561 return false;
2564 if (!empty($course)) {
2565 if (!is_object($course)) {
2566 $course = $DB->get_record('course', array('id' => $course), 'id, groupmode, groupmodeforce', MUST_EXIST);
2568 if ($course->id != SITEID) {
2569 $coursecontext = \context_course::instance($course->id);
2570 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
2572 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2573 $allowed->courses = array($course->id => 1);
2574 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2575 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
2576 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2581 if (!empty($category)) {
2582 $catcontext = \context_coursecat::instance($category->id);
2583 if (has_capability('moodle/category:manage', $catcontext)) {
2584 $allowed->categories = [$category->id => 1];
2590 * See if user can add calendar entries at all used to print the "New Event" button.
2592 * @param stdClass $course object of a course or course id
2593 * @return bool has the capability to add at least one event type
2595 function calendar_user_can_add_event($course) {
2596 if (!isloggedin() || isguestuser()) {
2597 return false;
2600 calendar_get_allowed_types($allowed, $course);
2602 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->categories || $allowed->site);
2606 * Check wether the current user is permitted to add events.
2608 * @param stdClass $event object of event
2609 * @return bool has the capability to add event
2611 function calendar_add_event_allowed($event) {
2612 global $USER, $DB;
2614 // Can not be using guest account.
2615 if (!isloggedin() or isguestuser()) {
2616 return false;
2619 $sitecontext = \context_system::instance();
2621 // If user has manageentries at site level, always return true.
2622 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2623 return true;
2626 switch ($event->eventtype) {
2627 case 'category':
2628 return has_capability('moodle/category:manage', $event->context);
2629 case 'course':
2630 return has_capability('moodle/calendar:manageentries', $event->context);
2631 case 'group':
2632 // Allow users to add/edit group events if -
2633 // 1) They have manageentries (= entries for whole course).
2634 // 2) They have managegroupentries AND are in the group.
2635 $group = $DB->get_record('groups', array('id' => $event->groupid));
2636 return $group && (
2637 has_capability('moodle/calendar:manageentries', $event->context) ||
2638 (has_capability('moodle/calendar:managegroupentries', $event->context)
2639 && groups_is_member($event->groupid)));
2640 case 'user':
2641 if ($event->userid == $USER->id) {
2642 return (has_capability('moodle/calendar:manageownentries', $event->context));
2644 // There is intentionally no 'break'.
2645 case 'site':
2646 return has_capability('moodle/calendar:manageentries', $event->context);
2647 default:
2648 return has_capability('moodle/calendar:manageentries', $event->context);
2653 * Returns option list for the poll interval setting.
2655 * @return array An array of poll interval options. Interval => description.
2657 function calendar_get_pollinterval_choices() {
2658 return array(
2659 '0' => new \lang_string('never', 'calendar'),
2660 HOURSECS => new \lang_string('hourly', 'calendar'),
2661 DAYSECS => new \lang_string('daily', 'calendar'),
2662 WEEKSECS => new \lang_string('weekly', 'calendar'),
2663 '2628000' => new \lang_string('monthly', 'calendar'),
2664 YEARSECS => new \lang_string('annually', 'calendar')
2669 * Returns option list of available options for the calendar event type, given the current user and course.
2671 * @param int $courseid The id of the course
2672 * @return array An array containing the event types the user can create.
2674 function calendar_get_eventtype_choices($courseid) {
2675 $choices = array();
2676 $allowed = new \stdClass;
2677 calendar_get_allowed_types($allowed, $courseid);
2679 if ($allowed->user) {
2680 $choices['user'] = get_string('userevents', 'calendar');
2682 if ($allowed->site) {
2683 $choices['site'] = get_string('siteevents', 'calendar');
2685 if (!empty($allowed->courses)) {
2686 $choices['course'] = get_string('courseevents', 'calendar');
2688 if (!empty($allowed->categories)) {
2689 $choices['category'] = get_string('categoryevents', 'calendar');
2691 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2692 $choices['group'] = get_string('group');
2695 return array($choices, $allowed->groups);
2699 * Add an iCalendar subscription to the database.
2701 * @param stdClass $sub The subscription object (e.g. from the form)
2702 * @return int The insert ID, if any.
2704 function calendar_add_subscription($sub) {
2705 global $DB, $USER, $SITE;
2707 // Undo the form definition work around to allow us to have two different
2708 // course selectors present depending on which event type the user selects.
2709 if (!empty($sub->groupcourseid)) {
2710 $sub->courseid = $sub->groupcourseid;
2711 unset($sub->groupcourseid);
2714 // Pull the group id back out of the value. The form saves the value
2715 // as "<courseid>-<groupid>" to allow the javascript to work correctly.
2716 if (!empty($sub->groupid)) {
2717 list($courseid, $groupid) = explode('-', $sub->groupid);
2718 $sub->courseid = $courseid;
2719 $sub->groupid = $groupid;
2722 // Default course id if none is set.
2723 if (empty($sub->courseid)) {
2724 if ($sub->eventtype === 'site') {
2725 $sub->courseid = SITEID;
2726 } else {
2727 $sub->courseid = 0;
2731 if ($sub->eventtype === 'site') {
2732 $sub->courseid = $SITE->id;
2733 } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
2734 $sub->courseid = $sub->courseid;
2735 } else if ($sub->eventtype === 'category') {
2736 $sub->categoryid = $sub->categoryid;
2737 } else {
2738 // User events.
2739 $sub->courseid = 0;
2741 $sub->userid = $USER->id;
2743 // File subscriptions never update.
2744 if (empty($sub->url)) {
2745 $sub->pollinterval = 0;
2748 if (!empty($sub->name)) {
2749 if (empty($sub->id)) {
2750 $id = $DB->insert_record('event_subscriptions', $sub);
2751 // We cannot cache the data here because $sub is not complete.
2752 $sub->id = $id;
2753 // Trigger event, calendar subscription added.
2754 $eventparams = array('objectid' => $sub->id,
2755 'context' => calendar_get_calendar_context($sub),
2756 'other' => array(
2757 'eventtype' => $sub->eventtype,
2760 switch ($sub->eventtype) {
2761 case 'category':
2762 $eventparams['other']['categoryid'] = $sub->categoryid;
2763 break;
2764 case 'course':
2765 $eventparams['other']['courseid'] = $sub->courseid;
2766 break;
2767 case 'group':
2768 $eventparams['other']['courseid'] = $sub->courseid;
2769 $eventparams['other']['groupid'] = $sub->groupid;
2770 break;
2771 default:
2772 $eventparams['other']['courseid'] = $sub->courseid;
2775 $event = \core\event\calendar_subscription_created::create($eventparams);
2776 $event->trigger();
2777 return $id;
2778 } else {
2779 // Why are we doing an update here?
2780 calendar_update_subscription($sub);
2781 return $sub->id;
2783 } else {
2784 print_error('errorbadsubscription', 'importcalendar');
2789 * Add an iCalendar event to the Moodle calendar.
2791 * @param stdClass $event The RFC-2445 iCalendar event
2792 * @param int $unused Deprecated
2793 * @param int $subscriptionid The iCalendar subscription ID
2794 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2795 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2796 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2798 function calendar_add_icalendar_event($event, $unused = null, $subscriptionid, $timezone='UTC') {
2799 global $DB;
2801 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2802 if (empty($event->properties['SUMMARY'])) {
2803 return 0;
2806 $name = $event->properties['SUMMARY'][0]->value;
2807 $name = str_replace('\n', '<br />', $name);
2808 $name = str_replace('\\', '', $name);
2809 $name = preg_replace('/\s+/u', ' ', $name);
2811 $eventrecord = new \stdClass;
2812 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
2814 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2815 $description = '';
2816 } else {
2817 $description = $event->properties['DESCRIPTION'][0]->value;
2818 $description = clean_param($description, PARAM_NOTAGS);
2819 $description = str_replace('\n', '<br />', $description);
2820 $description = str_replace('\\', '', $description);
2821 $description = preg_replace('/\s+/u', ' ', $description);
2823 $eventrecord->description = $description;
2825 // Probably a repeating event with RRULE etc. TODO: skip for now.
2826 if (empty($event->properties['DTSTART'][0]->value)) {
2827 return 0;
2830 if (isset($event->properties['DTSTART'][0]->parameters['TZID'])) {
2831 $tz = $event->properties['DTSTART'][0]->parameters['TZID'];
2832 } else {
2833 $tz = $timezone;
2835 $tz = \core_date::normalise_timezone($tz);
2836 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value . ' ' . $tz);
2837 if (empty($event->properties['DTEND'])) {
2838 $eventrecord->timeduration = 0; // No duration if no end time specified.
2839 } else {
2840 if (isset($event->properties['DTEND'][0]->parameters['TZID'])) {
2841 $endtz = $event->properties['DTEND'][0]->parameters['TZID'];
2842 } else {
2843 $endtz = $timezone;
2845 $endtz = \core_date::normalise_timezone($endtz);
2846 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value . ' ' . $endtz) - $eventrecord->timestart;
2849 // Check to see if it should be treated as an all day event.
2850 if ($eventrecord->timeduration == DAYSECS) {
2851 // Check to see if the event started at Midnight on the imported calendar.
2852 date_default_timezone_set($timezone);
2853 if (date('H:i:s', $eventrecord->timestart) === "00:00:00") {
2854 // This event should be an all day event. This is not correct, we don't do anything differently for all day events.
2855 // See MDL-56227.
2856 $eventrecord->timeduration = 0;
2858 \core_date::set_default_server_timezone();
2861 $eventrecord->location = empty($event->properties['LOCATION'][0]->value) ? '' :
2862 str_replace('\\', '', $event->properties['LOCATION'][0]->value);
2863 $eventrecord->uuid = $event->properties['UID'][0]->value;
2864 $eventrecord->timemodified = time();
2866 // Add the iCal subscription details if required.
2867 // We should never do anything with an event without a subscription reference.
2868 $sub = calendar_get_subscription($subscriptionid);
2869 $eventrecord->subscriptionid = $subscriptionid;
2870 $eventrecord->userid = $sub->userid;
2871 $eventrecord->groupid = $sub->groupid;
2872 $eventrecord->courseid = $sub->courseid;
2873 $eventrecord->categoryid = $sub->categoryid;
2874 $eventrecord->eventtype = $sub->eventtype;
2876 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid,
2877 'subscriptionid' => $eventrecord->subscriptionid))) {
2878 $eventrecord->id = $updaterecord->id;
2879 $return = CALENDAR_IMPORT_EVENT_UPDATED; // Update.
2880 } else {
2881 $return = CALENDAR_IMPORT_EVENT_INSERTED; // Insert.
2883 if ($createdevent = \calendar_event::create($eventrecord, false)) {
2884 if (!empty($event->properties['RRULE'])) {
2885 // Repeating events.
2886 date_default_timezone_set($tz); // Change time zone to parse all events.
2887 $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
2888 $rrule->parse_rrule();
2889 $rrule->create_events($createdevent);
2890 \core_date::set_default_server_timezone(); // Change time zone back to what it was.
2892 return $return;
2893 } else {
2894 return 0;
2899 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2901 * @param int $subscriptionid The ID of the subscription we are acting upon.
2902 * @param int $pollinterval The poll interval to use.
2903 * @param int $action The action to be performed. One of update or remove.
2904 * @throws dml_exception if invalid subscriptionid is provided
2905 * @return string A log of the import progress, including errors
2907 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2908 // Fetch the subscription from the database making sure it exists.
2909 $sub = calendar_get_subscription($subscriptionid);
2911 // Update or remove the subscription, based on action.
2912 switch ($action) {
2913 case CALENDAR_SUBSCRIPTION_UPDATE:
2914 // Skip updating file subscriptions.
2915 if (empty($sub->url)) {
2916 break;
2918 $sub->pollinterval = $pollinterval;
2919 calendar_update_subscription($sub);
2921 // Update the events.
2922 return "<p>" . get_string('subscriptionupdated', 'calendar', $sub->name) . "</p>" .
2923 calendar_update_subscription_events($subscriptionid);
2924 case CALENDAR_SUBSCRIPTION_REMOVE:
2925 calendar_delete_subscription($subscriptionid);
2926 return get_string('subscriptionremoved', 'calendar', $sub->name);
2927 break;
2928 default:
2929 break;
2931 return '';
2935 * Delete subscription and all related events.
2937 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
2939 function calendar_delete_subscription($subscription) {
2940 global $DB;
2942 if (!is_object($subscription)) {
2943 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST);
2946 // Delete subscription and related events.
2947 $DB->delete_records('event', array('subscriptionid' => $subscription->id));
2948 $DB->delete_records('event_subscriptions', array('id' => $subscription->id));
2949 \cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id));
2951 // Trigger event, calendar subscription deleted.
2952 $eventparams = array('objectid' => $subscription->id,
2953 'context' => calendar_get_calendar_context($subscription),
2954 'other' => array(
2955 'eventtype' => $subscription->eventtype,
2958 switch ($subscription->eventtype) {
2959 case 'category':
2960 $eventparams['other']['categoryid'] = $subscription->categoryid;
2961 break;
2962 case 'course':
2963 $eventparams['other']['courseid'] = $subscription->courseid;
2964 break;
2965 case 'group':
2966 $eventparams['other']['courseid'] = $subscription->courseid;
2967 $eventparams['other']['groupid'] = $subscription->groupid;
2968 break;
2969 default:
2970 $eventparams['other']['courseid'] = $subscription->courseid;
2972 $event = \core\event\calendar_subscription_deleted::create($eventparams);
2973 $event->trigger();
2977 * From a URL, fetch the calendar and return an iCalendar object.
2979 * @param string $url The iCalendar URL
2980 * @return iCalendar The iCalendar object
2982 function calendar_get_icalendar($url) {
2983 global $CFG;
2985 require_once($CFG->libdir . '/filelib.php');
2987 $curl = new \curl();
2988 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
2989 $calendar = $curl->get($url);
2991 // Http code validation should actually be the job of curl class.
2992 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
2993 throw new \moodle_exception('errorinvalidicalurl', 'calendar');
2996 $ical = new \iCalendar();
2997 $ical->unserialize($calendar);
2999 return $ical;
3003 * Import events from an iCalendar object into a course calendar.
3005 * @param iCalendar $ical The iCalendar object.
3006 * @param int $courseid The course ID for the calendar.
3007 * @param int $subscriptionid The subscription ID.
3008 * @return string A log of the import progress, including errors.
3010 function calendar_import_icalendar_events($ical, $unused = null, $subscriptionid = null) {
3011 global $DB;
3013 $return = '';
3014 $eventcount = 0;
3015 $updatecount = 0;
3017 // Large calendars take a while...
3018 if (!CLI_SCRIPT) {
3019 \core_php_time_limit::raise(300);
3022 // Mark all events in a subscription with a zero timestamp.
3023 if (!empty($subscriptionid)) {
3024 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
3025 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3028 // Grab the timezone from the iCalendar file to be used later.
3029 if (isset($ical->properties['X-WR-TIMEZONE'][0]->value)) {
3030 $timezone = $ical->properties['X-WR-TIMEZONE'][0]->value;
3031 } else {
3032 $timezone = 'UTC';
3035 $return = '';
3036 foreach ($ical->components['VEVENT'] as $event) {
3037 $res = calendar_add_icalendar_event($event, null, $subscriptionid, $timezone);
3038 switch ($res) {
3039 case CALENDAR_IMPORT_EVENT_UPDATED:
3040 $updatecount++;
3041 break;
3042 case CALENDAR_IMPORT_EVENT_INSERTED:
3043 $eventcount++;
3044 break;
3045 case 0:
3046 $return .= '<p>' . get_string('erroraddingevent', 'calendar') . ': ';
3047 if (empty($event->properties['SUMMARY'])) {
3048 $return .= '(' . get_string('notitle', 'calendar') . ')';
3049 } else {
3050 $return .= $event->properties['SUMMARY'][0]->value;
3052 $return .= "</p>\n";
3053 break;
3057 $return .= "<p>" . get_string('eventsimported', 'calendar', $eventcount) . "</p> ";
3058 $return .= "<p>" . get_string('eventsupdated', 'calendar', $updatecount) . "</p>";
3060 // Delete remaining zero-marked events since they're not in remote calendar.
3061 if (!empty($subscriptionid)) {
3062 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3063 if (!empty($deletecount)) {
3064 $DB->delete_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3065 $return .= "<p> " . get_string('eventsdeleted', 'calendar') . ": {$deletecount} </p>\n";
3069 return $return;
3073 * Fetch a calendar subscription and update the events in the calendar.
3075 * @param int $subscriptionid The course ID for the calendar.
3076 * @return string A log of the import progress, including errors.
3078 function calendar_update_subscription_events($subscriptionid) {
3079 $sub = calendar_get_subscription($subscriptionid);
3081 // Don't update a file subscription.
3082 if (empty($sub->url)) {
3083 return 'File subscription not updated.';
3086 $ical = calendar_get_icalendar($sub->url);
3087 $return = calendar_import_icalendar_events($ical, null, $subscriptionid);
3088 $sub->lastupdated = time();
3090 calendar_update_subscription($sub);
3092 return $return;
3096 * Update a calendar subscription. Also updates the associated cache.
3098 * @param stdClass|array $subscription Subscription record.
3099 * @throws coding_exception If something goes wrong
3100 * @since Moodle 2.5
3102 function calendar_update_subscription($subscription) {
3103 global $DB;
3105 if (is_array($subscription)) {
3106 $subscription = (object)$subscription;
3108 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
3109 throw new \coding_exception('Cannot update a subscription without a valid id');
3112 $DB->update_record('event_subscriptions', $subscription);
3114 // Update cache.
3115 $cache = \cache::make('core', 'calendar_subscriptions');
3116 $cache->set($subscription->id, $subscription);
3118 // Trigger event, calendar subscription updated.
3119 $eventparams = array('userid' => $subscription->userid,
3120 'objectid' => $subscription->id,
3121 'context' => calendar_get_calendar_context($subscription),
3122 'other' => array(
3123 'eventtype' => $subscription->eventtype,
3126 switch ($subscription->eventtype) {
3127 case 'category':
3128 $eventparams['other']['categoryid'] = $subscription->categoryid;
3129 break;
3130 case 'course':
3131 $eventparams['other']['courseid'] = $subscription->courseid;
3132 break;
3133 case 'group':
3134 $eventparams['other']['courseid'] = $subscription->courseid;
3135 $eventparams['other']['groupid'] = $subscription->groupid;
3136 break;
3137 default:
3138 $eventparams['other']['courseid'] = $subscription->courseid;
3140 $event = \core\event\calendar_subscription_updated::create($eventparams);
3141 $event->trigger();
3145 * Checks to see if the user can edit a given subscription feed.
3147 * @param mixed $subscriptionorid Subscription object or id
3148 * @return bool true if current user can edit the subscription else false
3150 function calendar_can_edit_subscription($subscriptionorid) {
3151 if (is_array($subscriptionorid)) {
3152 $subscription = (object)$subscriptionorid;
3153 } else if (is_object($subscriptionorid)) {
3154 $subscription = $subscriptionorid;
3155 } else {
3156 $subscription = calendar_get_subscription($subscriptionorid);
3159 $allowed = new \stdClass;
3160 $courseid = $subscription->courseid;
3161 $categoryid = $subscription->categoryid;
3162 $groupid = $subscription->groupid;
3163 $category = null;
3165 if (!empty($categoryid)) {
3166 $category = \core_course_category::get($categoryid);
3168 calendar_get_allowed_types($allowed, $courseid, null, $category);
3169 switch ($subscription->eventtype) {
3170 case 'user':
3171 return $allowed->user;
3172 case 'course':
3173 if (isset($allowed->courses[$courseid])) {
3174 return $allowed->courses[$courseid];
3175 } else {
3176 return false;
3178 case 'category':
3179 if (isset($allowed->categories[$categoryid])) {
3180 return $allowed->categories[$categoryid];
3181 } else {
3182 return false;
3184 case 'site':
3185 return $allowed->site;
3186 case 'group':
3187 if (isset($allowed->groups[$groupid])) {
3188 return $allowed->groups[$groupid];
3189 } else {
3190 return false;
3192 default:
3193 return false;
3198 * Helper function to determine the context of a calendar subscription.
3199 * Subscriptions can be created in two contexts COURSE, or USER.
3201 * @param stdClass $subscription
3202 * @return context instance
3204 function calendar_get_calendar_context($subscription) {
3205 // Determine context based on calendar type.
3206 if ($subscription->eventtype === 'site') {
3207 $context = \context_course::instance(SITEID);
3208 } else if ($subscription->eventtype === 'group' || $subscription->eventtype === 'course') {
3209 $context = \context_course::instance($subscription->courseid);
3210 } else {
3211 $context = \context_user::instance($subscription->userid);
3213 return $context;
3217 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
3219 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3221 * @return array
3223 function core_calendar_user_preferences() {
3224 $preferences = [];
3225 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED, 'default' => '0',
3226 'choices' => array('0', CALENDAR_TF_12, CALENDAR_TF_24)
3228 $preferences['calendar_startwday'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3229 'choices' => array(0, 1, 2, 3, 4, 5, 6));
3230 $preferences['calendar_maxevents'] = array('type' => PARAM_INT, 'choices' => range(1, 20));
3231 $preferences['calendar_lookahead'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 365,
3232 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3233 $preferences['calendar_persistflt'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3234 'choices' => array(0, 1));
3235 return $preferences;
3239 * Get legacy calendar events
3241 * @param int $tstart Start time of time range for events
3242 * @param int $tend End time of time range for events
3243 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3244 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3245 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3246 * @param boolean $withduration whether only events starting within time range selected
3247 * or events in progress/already started selected as well
3248 * @param boolean $ignorehidden whether to select only visible events or all events
3249 * @param array $categories array of category ids and/or objects.
3250 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3252 function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses,
3253 $withduration = true, $ignorehidden = true, $categories = []) {
3254 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3255 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3256 // parameters, but with the new API method, only null and arrays are accepted.
3257 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3258 // If parameter is true, return null.
3259 if ($param === true) {
3260 return null;
3263 // If parameter is false, return an empty array.
3264 if ($param === false) {
3265 return [];
3268 // If the parameter is a scalar value, enclose it in an array.
3269 if (!is_array($param)) {
3270 return [$param];
3273 // No normalisation required.
3274 return $param;
3275 }, [$users, $groups, $courses, $categories]);
3277 // If a single user is provided, we can use that for capability checks.
3278 // Otherwise current logged in user is used - See MDL-58768.
3279 if (is_array($userparam) && count($userparam) == 1) {
3280 \core_calendar\local\event\container::set_requesting_user($userparam[0]);
3282 $mapper = \core_calendar\local\event\container::get_event_mapper();
3283 $events = \core_calendar\local\api::get_events(
3284 $tstart,
3285 $tend,
3286 null,
3287 null,
3288 null,
3289 null,
3291 null,
3292 $userparam,
3293 $groupparam,
3294 $courseparam,
3295 $categoryparam,
3296 $withduration,
3297 $ignorehidden
3300 return array_reduce($events, function($carry, $event) use ($mapper) {
3301 return $carry + [$event->get_id() => $mapper->from_event_to_stdclass($event)];
3302 }, []);
3307 * Get the calendar view output.
3309 * @param \calendar_information $calendar The calendar being represented
3310 * @param string $view The type of calendar to have displayed
3311 * @param bool $includenavigation Whether to include navigation
3312 * @param bool $skipevents Whether to load the events or not
3313 * @return array[array, string]
3315 function calendar_get_view(\calendar_information $calendar, $view, $includenavigation = true, bool $skipevents = false) {
3316 global $PAGE, $CFG;
3318 $renderer = $PAGE->get_renderer('core_calendar');
3319 $type = \core_calendar\type_factory::get_calendar_instance();
3321 // Calculate the bounds of the month.
3322 $calendardate = $type->timestamp_to_date_array($calendar->time);
3324 $date = new \DateTime('now', core_date::get_user_timezone_object(99));
3325 $eventlimit = 200;
3327 if ($view === 'day') {
3328 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday']);
3329 $date->setTimestamp($tstart);
3330 $date->modify('+1 day');
3331 } else if ($view === 'upcoming' || $view === 'upcoming_mini') {
3332 // Number of days in the future that will be used to fetch events.
3333 if (isset($CFG->calendar_lookahead)) {
3334 $defaultlookahead = intval($CFG->calendar_lookahead);
3335 } else {
3336 $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD;
3338 $lookahead = get_user_preferences('calendar_lookahead', $defaultlookahead);
3340 // Maximum number of events to be displayed on upcoming view.
3341 $defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS;
3342 if (isset($CFG->calendar_maxevents)) {
3343 $defaultmaxevents = intval($CFG->calendar_maxevents);
3345 $eventlimit = get_user_preferences('calendar_maxevents', $defaultmaxevents);
3347 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday'],
3348 $calendardate['hours']);
3349 $date->setTimestamp($tstart);
3350 $date->modify('+' . $lookahead . ' days');
3351 } else {
3352 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], 1);
3353 $monthdays = $type->get_num_days_in_month($calendardate['year'], $calendardate['mon']);
3354 $date->setTimestamp($tstart);
3355 $date->modify('+' . $monthdays . ' days');
3357 if ($view === 'mini' || $view === 'minithree') {
3358 $template = 'core_calendar/calendar_mini';
3359 } else {
3360 $template = 'core_calendar/calendar_month';
3364 // We need to extract 1 second to ensure that we don't get into the next day.
3365 $date->modify('-1 second');
3366 $tend = $date->getTimestamp();
3368 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3369 // If parameter is true, return null.
3370 if ($param === true) {
3371 return null;
3374 // If parameter is false, return an empty array.
3375 if ($param === false) {
3376 return [];
3379 // If the parameter is a scalar value, enclose it in an array.
3380 if (!is_array($param)) {
3381 return [$param];
3384 // No normalisation required.
3385 return $param;
3386 }, [$calendar->users, $calendar->groups, $calendar->courses, $calendar->categories]);
3388 if ($skipevents) {
3389 $events = [];
3390 } else {
3391 $events = \core_calendar\local\api::get_events(
3392 $tstart,
3393 $tend,
3394 null,
3395 null,
3396 null,
3397 null,
3398 $eventlimit,
3399 null,
3400 $userparam,
3401 $groupparam,
3402 $courseparam,
3403 $categoryparam,
3404 true,
3405 true,
3406 function ($event) {
3407 if ($proxy = $event->get_course_module()) {
3408 $cminfo = $proxy->get_proxied_instance();
3409 return $cminfo->uservisible;
3412 if ($proxy = $event->get_category()) {
3413 $category = $proxy->get_proxied_instance();
3415 return $category->is_uservisible();
3418 return true;
3423 $related = [
3424 'events' => $events,
3425 'cache' => new \core_calendar\external\events_related_objects_cache($events),
3426 'type' => $type,
3429 $data = [];
3430 if ($view == "month" || $view == "mini" || $view == "minithree") {
3431 $month = new \core_calendar\external\month_exporter($calendar, $type, $related);
3432 $month->set_includenavigation($includenavigation);
3433 $month->set_initialeventsloaded(!$skipevents);
3434 $month->set_showcoursefilter($view == "month");
3435 $data = $month->export($renderer);
3436 } else if ($view == "day") {
3437 $day = new \core_calendar\external\calendar_day_exporter($calendar, $related);
3438 $data = $day->export($renderer);
3439 $template = 'core_calendar/calendar_day';
3440 } else if ($view == "upcoming" || $view == "upcoming_mini") {
3441 $upcoming = new \core_calendar\external\calendar_upcoming_exporter($calendar, $related);
3442 $data = $upcoming->export($renderer);
3444 if ($view == "upcoming") {
3445 $template = 'core_calendar/calendar_upcoming';
3446 } else if ($view == "upcoming_mini") {
3447 $template = 'core_calendar/calendar_upcoming_mini';
3451 return [$data, $template];
3455 * Request and render event form fragment.
3457 * @param array $args The fragment arguments.
3458 * @return string The rendered mform fragment.
3460 function calendar_output_fragment_event_form($args) {
3461 global $CFG, $OUTPUT, $USER;
3462 require_once($CFG->libdir . '/grouplib.php');
3463 $html = '';
3464 $data = [];
3465 $eventid = isset($args['eventid']) ? clean_param($args['eventid'], PARAM_INT) : null;
3466 $starttime = isset($args['starttime']) ? clean_param($args['starttime'], PARAM_INT) : null;
3467 $courseid = (isset($args['courseid']) && $args['courseid'] != SITEID) ? clean_param($args['courseid'], PARAM_INT) : null;
3468 $categoryid = isset($args['categoryid']) ? clean_param($args['categoryid'], PARAM_INT) : null;
3469 $event = null;
3470 $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
3471 $context = \context_user::instance($USER->id);
3472 $editoroptions = \core_calendar\local\event\forms\create::build_editor_options($context);
3473 $formoptions = ['editoroptions' => $editoroptions, 'courseid' => $courseid];
3474 $draftitemid = 0;
3476 if ($hasformdata) {
3477 parse_str(clean_param($args['formdata'], PARAM_TEXT), $data);
3478 if (isset($data['description']['itemid'])) {
3479 $draftitemid = $data['description']['itemid'];
3483 if ($starttime) {
3484 $formoptions['starttime'] = $starttime;
3487 if (is_null($eventid)) {
3488 if (!empty($courseid)) {
3489 $groupcoursedata = groups_get_course_data($courseid);
3490 $formoptions['groups'] = [];
3491 foreach ($groupcoursedata->groups as $groupid => $groupdata) {
3492 $formoptions['groups'][$groupid] = $groupdata->name;
3495 $mform = new \core_calendar\local\event\forms\create(
3496 null,
3497 $formoptions,
3498 'post',
3500 null,
3501 true,
3502 $data
3505 // Let's check first which event types user can add.
3506 $eventtypes = calendar_get_allowed_event_types($courseid);
3508 // If the user is on course context and is allowed to add course events set the event type default to course.
3509 if ($courseid != SITEID && !empty($eventtypes['course'])) {
3510 $data['eventtype'] = 'course';
3511 $data['courseid'] = $courseid;
3512 $data['groupcourseid'] = $courseid;
3513 } else if (!empty($categoryid) && !empty($eventtypes['category'])) {
3514 $data['eventtype'] = 'category';
3515 $data['categoryid'] = $categoryid;
3516 } else if (!empty($groupcoursedata) && !empty($eventtypes['group'])) {
3517 $data['groupcourseid'] = $courseid;
3518 $data['groups'] = $groupcoursedata->groups;
3520 $mform->set_data($data);
3521 } else {
3522 $event = calendar_event::load($eventid);
3523 $mapper = new \core_calendar\local\event\mappers\create_update_form_mapper();
3524 $eventdata = $mapper->from_legacy_event_to_data($event);
3525 $data = array_merge((array) $eventdata, $data);
3526 $event->count_repeats();
3527 $formoptions['event'] = $event;
3529 if (!empty($event->courseid)) {
3530 $groupcoursedata = groups_get_course_data($event->courseid);
3531 $formoptions['groups'] = [];
3532 foreach ($groupcoursedata->groups as $groupid => $groupdata) {
3533 $formoptions['groups'][$groupid] = $groupdata->name;
3537 $data['description']['text'] = file_prepare_draft_area(
3538 $draftitemid,
3539 $event->context->id,
3540 'calendar',
3541 'event_description',
3542 $event->id,
3543 null,
3544 $data['description']['text']
3546 $data['description']['itemid'] = $draftitemid;
3548 $mform = new \core_calendar\local\event\forms\update(
3549 null,
3550 $formoptions,
3551 'post',
3553 null,
3554 true,
3555 $data
3557 $mform->set_data($data);
3559 // Check to see if this event is part of a subscription or import.
3560 // If so display a warning on edit.
3561 if (isset($event->subscriptionid) && ($event->subscriptionid != null)) {
3562 $renderable = new \core\output\notification(
3563 get_string('eventsubscriptioneditwarning', 'calendar'),
3564 \core\output\notification::NOTIFY_INFO
3567 $html .= $OUTPUT->render($renderable);
3571 if ($hasformdata) {
3572 $mform->is_validated();
3575 $html .= $mform->render();
3576 return $html;
3580 * Calculate the timestamp from the supplied Gregorian Year, Month, and Day.
3582 * @param int $d The day
3583 * @param int $m The month
3584 * @param int $y The year
3585 * @param int $time The timestamp to use instead of a separate y/m/d.
3586 * @return int The timestamp
3588 function calendar_get_timestamp($d, $m, $y, $time = 0) {
3589 // If a day, month and year were passed then convert it to a timestamp. If these were passed
3590 // then we can assume the day, month and year are passed as Gregorian, as no where in core
3591 // should we be passing these values rather than the time.
3592 if (!empty($d) && !empty($m) && !empty($y)) {
3593 if (checkdate($m, $d, $y)) {
3594 $time = make_timestamp($y, $m, $d);
3595 } else {
3596 $time = time();
3598 } else if (empty($time)) {
3599 $time = time();
3602 return $time;
3606 * Get the calendar footer options.
3608 * @param calendar_information $calendar The calendar information object.
3609 * @return array The data for template and template name.
3611 function calendar_get_footer_options($calendar) {
3612 global $CFG, $USER, $DB, $PAGE;
3614 // Generate hash for iCal link.
3615 $rawhash = $USER->id . $DB->get_field('user', 'password', ['id' => $USER->id]) . $CFG->calendar_exportsalt;
3616 $authtoken = sha1($rawhash);
3618 $renderer = $PAGE->get_renderer('core_calendar');
3619 $footer = new \core_calendar\external\footer_options_exporter($calendar, $USER->id, $authtoken);
3620 $data = $footer->export($renderer);
3621 $template = 'core_calendar/footer_options';
3623 return [$data, $template];
3627 * Get the list of potential calendar filter types as a type => name
3628 * combination.
3630 * @return array
3632 function calendar_get_filter_types() {
3633 $types = [
3634 'site',
3635 'category',
3636 'course',
3637 'group',
3638 'user',
3641 return array_map(function($type) {
3642 return [
3643 'eventtype' => $type,
3644 'name' => get_string("eventtype{$type}", "calendar"),
3646 }, $types);
3650 * Check whether the specified event type is valid.
3652 * @param string $type
3653 * @return bool
3655 function calendar_is_valid_eventtype($type) {
3656 $validtypes = [
3657 'user',
3658 'group',
3659 'course',
3660 'category',
3661 'site',
3663 return in_array($type, $validtypes);
3667 * Get event types the user can create event based on categories, courses and groups
3668 * the logged in user belongs to.
3670 * @param int|null $courseid The course id.
3671 * @return array The array of allowed types.
3673 function calendar_get_allowed_event_types(int $courseid = null) {
3674 global $DB, $CFG, $USER;
3676 $types = [
3677 'user' => false,
3678 'site' => false,
3679 'course' => false,
3680 'group' => false,
3681 'category' => false
3684 if (!empty($courseid) && $courseid != SITEID) {
3685 $context = \context_course::instance($courseid);
3686 $groups = groups_get_all_groups($courseid);
3688 $types['user'] = has_capability('moodle/calendar:manageownentries', $context);
3690 if (has_capability('moodle/calendar:manageentries', $context) || !empty($CFG->calendar_adminseesall)) {
3691 $types['course'] = true;
3693 $types['group'] = (!empty($groups) && has_capability('moodle/site:accessallgroups', $context))
3694 || array_filter($groups, function($group) use ($USER) {
3695 return groups_is_member($group->id);
3697 } else if (has_capability('moodle/calendar:managegroupentries', $context)) {
3698 $types['group'] = (!empty($groups) && has_capability('moodle/site:accessallgroups', $context))
3699 || array_filter($groups, function($group) use ($USER) {
3700 return groups_is_member($group->id);
3705 if (has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID))) {
3706 $types['site'] = true;
3709 if (has_capability('moodle/calendar:manageownentries', \context_system::instance())) {
3710 $types['user'] = true;
3712 if (core_course_category::has_manage_capability_on_any()) {
3713 $types['category'] = true;
3716 // We still don't know if the user can create group and course events, so iterate over the courses to find out
3717 // if the user has capabilities in one of the courses.
3718 if ($types['course'] == false || $types['group'] == false) {
3719 if ($CFG->calendar_adminseesall && has_capability('moodle/calendar:manageentries', context_system::instance())) {
3720 $sql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3721 FROM {course} c
3722 JOIN {context} ctx ON ctx.contextlevel = ? AND ctx.instanceid = c.id
3723 WHERE c.id IN (
3724 SELECT DISTINCT courseid FROM {groups}
3726 $courseswithgroups = $DB->get_recordset_sql($sql, [CONTEXT_COURSE]);
3727 foreach ($courseswithgroups as $course) {
3728 context_helper::preload_from_record($course);
3729 $context = context_course::instance($course->id);
3731 if (has_capability('moodle/calendar:manageentries', $context)) {
3732 if (has_any_capability(['moodle/site:accessallgroups', 'moodle/calendar:managegroupentries'], $context)) {
3733 // The user can manage group entries or access any group.
3734 $types['group'] = true;
3735 $types['course'] = true;
3736 break;
3740 $courseswithgroups->close();
3742 if (false === $types['course']) {
3743 // Course is still not confirmed. There may have been no courses with a group in them.
3744 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
3745 $sql = "SELECT
3746 c.id, c.visible, {$ctxfields}
3747 FROM {course}
3748 JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
3749 $params = [
3750 'contextlevel' => CONTEXT_COURSE,
3752 $courses = $DB->get_recordset_sql($sql, $params);
3753 foreach ($courses as $course) {
3754 context_helper::preload_from_record($course);
3755 $context = context_course::instance($course->id);
3756 if (has_capability('moodle/calendar:manageentries', $context)) {
3757 $types['course'] = true;
3758 break;
3761 $courses->close();
3764 } else {
3765 $courses = calendar_get_default_courses(null, 'id');
3766 if (empty($courses)) {
3767 return $types;
3770 $courseids = array_map(function($c) {
3771 return $c->id;
3772 }, $courses);
3774 // Check whether the user has access to create events within courses which have groups.
3775 list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
3776 $sql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3777 FROM {course} c
3778 JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3779 WHERE c.id $insql
3780 AND c.id IN (SELECT DISTINCT courseid FROM {groups})";
3781 $params['contextlevel'] = CONTEXT_COURSE;
3782 $courseswithgroups = $DB->get_recordset_sql($sql, $params);
3783 foreach ($courseswithgroups as $coursewithgroup) {
3784 context_helper::preload_from_record($coursewithgroup);
3785 $context = context_course::instance($coursewithgroup->id);
3787 if (has_capability('moodle/calendar:manageentries', $context)) {
3788 // The user has access to manage calendar entries for the whole course.
3789 // This includes groups if they have the accessallgroups capability.
3790 $types['course'] = true;
3791 if (has_capability('moodle/site:accessallgroups', $context)) {
3792 // The user also has access to all groups so they can add calendar entries to any group.
3793 // The manageentries capability overrides the managegroupentries capability.
3794 $types['group'] = true;
3795 break;
3798 if (empty($types['group']) && has_capability('moodle/calendar:managegroupentries', $context)) {
3799 // The user has the managegroupentries capability.
3800 // If they have access to _any_ group, then they can create calendar entries within that group.
3801 $types['group'] = !empty(groups_get_all_groups($coursewithgroup->id, $USER->id));
3805 // Okay, course and group event types are allowed, no need to keep the loop iteration.
3806 if ($types['course'] == true && $types['group'] == true) {
3807 break;
3810 $courseswithgroups->close();
3812 if (false === $types['course']) {
3813 list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
3814 $contextsql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3815 FROM {course} c
3816 JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3817 WHERE c.id $insql";
3818 $params['contextlevel'] = CONTEXT_COURSE;
3819 $contextrecords = $DB->get_recordset_sql($contextsql, $params);
3820 foreach ($contextrecords as $course) {
3821 context_helper::preload_from_record($course);
3822 $coursecontext = context_course::instance($course->id);
3823 if (has_capability('moodle/calendar:manageentries', $coursecontext)
3824 && ($courseid == $course->id || empty($courseid))) {
3825 $types['course'] = true;
3826 break;
3829 $contextrecords->close();
3835 return $types;