MDL-66979 behat: Goutte driver doesn't implement setTimeouts()
[moodle.git] / calendar / lib.php
blob1fceea977d4e7ac2c532d1d386d91b495f8c9671
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 - Site calendar event types
74 * @deprecated since 3.8
76 define('CALENDAR_EVENT_GLOBAL', 1);
78 /**
79 * CALENDAR_EVENT_SITE - Site calendar event types
81 define('CALENDAR_EVENT_SITE', 1);
83 /**
84 * CALENDAR_EVENT_COURSE - Course calendar event types
86 define('CALENDAR_EVENT_COURSE', 2);
88 /**
89 * CALENDAR_EVENT_GROUP - group calendar event types
91 define('CALENDAR_EVENT_GROUP', 4);
93 /**
94 * CALENDAR_EVENT_USER - user calendar event types
96 define('CALENDAR_EVENT_USER', 8);
98 /**
99 * CALENDAR_EVENT_COURSECAT - Course category calendar event types
101 define('CALENDAR_EVENT_COURSECAT', 16);
104 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
106 define('CALENDAR_IMPORT_FROM_FILE', 0);
109 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
111 define('CALENDAR_IMPORT_FROM_URL', 1);
114 * CALENDAR_IMPORT_EVENT_UPDATED_SKIPPED - imported event was skipped
116 define('CALENDAR_IMPORT_EVENT_SKIPPED', -1);
119 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
121 define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
124 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
126 define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
129 * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
131 define('CALENDAR_SUBSCRIPTION_UPDATE', 1);
134 * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
136 define('CALENDAR_SUBSCRIPTION_REMOVE', 2);
139 * CALENDAR_EVENT_USER_OVERRIDE_PRIORITY - Constant for the user override priority.
141 define('CALENDAR_EVENT_USER_OVERRIDE_PRIORITY', 0);
144 * CALENDAR_EVENT_TYPE_STANDARD - Standard events.
146 define('CALENDAR_EVENT_TYPE_STANDARD', 0);
149 * CALENDAR_EVENT_TYPE_ACTION - Action events.
151 define('CALENDAR_EVENT_TYPE_ACTION', 1);
154 * Manage calendar events.
156 * This class provides the required functionality in order to manage calendar events.
157 * It was introduced as part of Moodle 2.0 and was created in order to provide a
158 * better framework for dealing with calendar events in particular regard to file
159 * handling through the new file API.
161 * @package core_calendar
162 * @category calendar
163 * @copyright 2009 Sam Hemelryk
164 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
166 * @property int $id The id within the event table
167 * @property string $name The name of the event
168 * @property string $description The description of the event
169 * @property int $format The format of the description FORMAT_?
170 * @property int $courseid The course the event is associated with (0 if none)
171 * @property int $groupid The group the event is associated with (0 if none)
172 * @property int $userid The user the event is associated with (0 if none)
173 * @property int $repeatid If this is a repeated event this will be set to the
174 * id of the original
175 * @property string $component If created by a plugin/component (other than module), the full frankenstyle name of a component
176 * @property string $modulename If added by a module this will be the module name
177 * @property int $instance If added by a module this will be the module instance
178 * @property string $eventtype The event type
179 * @property int $timestart The start time as a timestamp
180 * @property int $timeduration The duration of the event in seconds
181 * @property int $visible 1 if the event is visible
182 * @property int $uuid ?
183 * @property int $sequence ?
184 * @property int $timemodified The time last modified as a timestamp
186 class calendar_event {
188 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
189 protected $properties = null;
191 /** @var string The converted event discription with file paths resolved.
192 * This gets populated when someone requests description for the first time */
193 protected $_description = null;
195 /** @var array The options to use with this description editor */
196 protected $editoroptions = array(
197 'subdirs' => false,
198 'forcehttps' => false,
199 'maxfiles' => -1,
200 'maxbytes' => null,
201 'trusttext' => false);
203 /** @var object The context to use with the description editor */
204 protected $editorcontext = null;
207 * Instantiates a new event and optionally populates its properties with the data provided.
209 * @param \stdClass $data Optional. An object containing the properties to for
210 * an event
212 public function __construct($data = null) {
213 global $CFG, $USER;
215 // First convert to object if it is not already (should either be object or assoc array).
216 if (!is_object($data)) {
217 $data = (object) $data;
220 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
222 $data->eventrepeats = 0;
224 if (empty($data->id)) {
225 $data->id = null;
228 if (!empty($data->subscriptionid)) {
229 $data->subscription = calendar_get_subscription($data->subscriptionid);
232 // Default to a user event.
233 if (empty($data->eventtype)) {
234 $data->eventtype = 'user';
237 // Default to the current user.
238 if (empty($data->userid)) {
239 $data->userid = $USER->id;
242 if (!empty($data->timeduration) && is_array($data->timeduration)) {
243 $data->timeduration = make_timestamp(
244 $data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'],
245 $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
248 if (!empty($data->description) && is_array($data->description)) {
249 $data->format = $data->description['format'];
250 $data->description = $data->description['text'];
251 } else if (empty($data->description)) {
252 $data->description = '';
253 $data->format = editors_get_preferred_format();
256 // Ensure form is defaulted correctly.
257 if (empty($data->format)) {
258 $data->format = editors_get_preferred_format();
261 if (empty($data->component)) {
262 $data->component = null;
265 $this->properties = $data;
269 * Magic set method.
271 * Attempts to call a set_$key method if one exists otherwise falls back
272 * to simply set the property.
274 * @param string $key property name
275 * @param mixed $value value of the property
277 public function __set($key, $value) {
278 if (method_exists($this, 'set_'.$key)) {
279 $this->{'set_'.$key}($value);
281 $this->properties->{$key} = $value;
285 * Magic get method.
287 * Attempts to call a get_$key method to return the property and ralls over
288 * to return the raw property.
290 * @param string $key property name
291 * @return mixed property value
292 * @throws \coding_exception
294 public function __get($key) {
295 if (method_exists($this, 'get_'.$key)) {
296 return $this->{'get_'.$key}();
298 if (!property_exists($this->properties, $key)) {
299 throw new \coding_exception('Undefined property requested');
301 return $this->properties->{$key};
305 * Magic isset method.
307 * PHP needs an isset magic method if you use the get magic method and
308 * still want empty calls to work.
310 * @param string $key $key property name
311 * @return bool|mixed property value, false if property is not exist
313 public function __isset($key) {
314 return !empty($this->properties->{$key});
318 * Calculate the context value needed for an event.
320 * Event's type can be determine by the available value store in $data
321 * It is important to check for the existence of course/courseid to determine
322 * the course event.
323 * Default value is set to CONTEXT_USER
325 * @return \stdClass The context object.
327 protected function calculate_context() {
328 global $USER, $DB;
330 $context = null;
331 if (isset($this->properties->categoryid) && $this->properties->categoryid > 0) {
332 $context = \context_coursecat::instance($this->properties->categoryid);
333 } else if (isset($this->properties->courseid) && $this->properties->courseid > 0) {
334 $context = \context_course::instance($this->properties->courseid);
335 } else if (isset($this->properties->course) && $this->properties->course > 0) {
336 $context = \context_course::instance($this->properties->course);
337 } else if (isset($this->properties->groupid) && $this->properties->groupid > 0) {
338 $group = $DB->get_record('groups', array('id' => $this->properties->groupid));
339 $context = \context_course::instance($group->courseid);
340 } else if (isset($this->properties->userid) && $this->properties->userid > 0
341 && $this->properties->userid == $USER->id) {
342 $context = \context_user::instance($this->properties->userid);
343 } else if (isset($this->properties->userid) && $this->properties->userid > 0
344 && $this->properties->userid != $USER->id &&
345 !empty($this->properties->modulename) &&
346 isset($this->properties->instance) && $this->properties->instance > 0) {
347 $cm = get_coursemodule_from_instance($this->properties->modulename, $this->properties->instance, 0,
348 false, MUST_EXIST);
349 $context = \context_course::instance($cm->course);
350 } else {
351 $context = \context_user::instance($this->properties->userid);
354 return $context;
358 * Returns the context for this event. The context is calculated
359 * the first time is is requested and then stored in a member
360 * variable to be returned each subsequent time.
362 * This is a magical getter function that will be called when
363 * ever the context property is accessed, e.g. $event->context.
365 * @return context
367 protected function get_context() {
368 if (!isset($this->properties->context)) {
369 $this->properties->context = $this->calculate_context();
372 return $this->properties->context;
376 * Returns an array of editoroptions for this event.
378 * @return array event editor options
380 protected function get_editoroptions() {
381 return $this->editoroptions;
385 * Returns an event description: Called by __get
386 * Please use $blah = $event->description;
388 * @return string event description
390 protected function get_description() {
391 global $CFG;
393 require_once($CFG->libdir . '/filelib.php');
395 if ($this->_description === null) {
396 // Check if we have already resolved the context for this event.
397 if ($this->editorcontext === null) {
398 // Switch on the event type to decide upon the appropriate context to use for this event.
399 $this->editorcontext = $this->get_context();
400 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
401 return clean_text($this->properties->description, $this->properties->format);
405 // Work out the item id for the editor, if this is a repeated event
406 // then the files will be associated with the original.
407 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
408 $itemid = $this->properties->repeatid;
409 } else {
410 $itemid = $this->properties->id;
413 // Convert file paths in the description so that things display correctly.
414 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php',
415 $this->editorcontext->id, 'calendar', 'event_description', $itemid);
416 // Clean the text so no nasties get through.
417 $this->_description = clean_text($this->_description, $this->properties->format);
420 // Finally return the description.
421 return $this->_description;
425 * Return the number of repeat events there are in this events series.
427 * @return int number of event repeated
429 public function count_repeats() {
430 global $DB;
431 if (!empty($this->properties->repeatid)) {
432 $this->properties->eventrepeats = $DB->count_records('event',
433 array('repeatid' => $this->properties->repeatid));
434 // We don't want to count ourselves.
435 $this->properties->eventrepeats--;
437 return $this->properties->eventrepeats;
441 * Update or create an event within the database
443 * Pass in a object containing the event properties and this function will
444 * insert it into the database and deal with any associated files
446 * Capability checking should be performed if the user is directly manipulating the event
447 * and no other capability has been tested. However if the event is not being manipulated
448 * directly by the user and another capability has been checked for them to do this then
449 * capabilites should not be checked.
451 * For example if a user is editing an event in the calendar the check should be true,
452 * but if you are updating an event in an activities settings are changed then the calendar
453 * capabilites should not be checked.
455 * @see self::create()
456 * @see self::update()
458 * @param \stdClass $data object of event
459 * @param bool $checkcapability If Moodle should check the user can manage the calendar events for this call or not.
460 * @return bool event updated
462 public function update($data, $checkcapability=true) {
463 global $DB, $USER;
465 foreach ($data as $key => $value) {
466 $this->properties->$key = $value;
469 $this->properties->timemodified = time();
470 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
472 // Prepare event data.
473 $eventargs = array(
474 'context' => $this->get_context(),
475 'objectid' => $this->properties->id,
476 'other' => array(
477 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
478 'timestart' => $this->properties->timestart,
479 'name' => $this->properties->name
483 if (empty($this->properties->id) || $this->properties->id < 1) {
484 if ($checkcapability) {
485 if (!calendar_add_event_allowed($this->properties)) {
486 print_error('nopermissiontoupdatecalendar');
490 if ($usingeditor) {
491 switch ($this->properties->eventtype) {
492 case 'user':
493 $this->properties->courseid = 0;
494 $this->properties->course = 0;
495 $this->properties->groupid = 0;
496 $this->properties->userid = $USER->id;
497 break;
498 case 'site':
499 $this->properties->courseid = SITEID;
500 $this->properties->course = SITEID;
501 $this->properties->groupid = 0;
502 $this->properties->userid = $USER->id;
503 break;
504 case 'course':
505 $this->properties->groupid = 0;
506 $this->properties->userid = $USER->id;
507 break;
508 case 'category':
509 $this->properties->groupid = 0;
510 $this->properties->category = 0;
511 $this->properties->userid = $USER->id;
512 break;
513 case 'group':
514 $this->properties->userid = $USER->id;
515 break;
516 default:
517 // We should NEVER get here, but just incase we do lets fail gracefully.
518 $usingeditor = false;
519 break;
522 // If we are actually using the editor, we recalculate the context because some default values
523 // were set when calculate_context() was called from the constructor.
524 if ($usingeditor) {
525 $this->properties->context = $this->calculate_context();
526 $this->editorcontext = $this->get_context();
529 $editor = $this->properties->description;
530 $this->properties->format = $this->properties->description['format'];
531 $this->properties->description = $this->properties->description['text'];
534 // Insert the event into the database.
535 $this->properties->id = $DB->insert_record('event', $this->properties);
537 if ($usingeditor) {
538 $this->properties->description = file_save_draft_area_files(
539 $editor['itemid'],
540 $this->editorcontext->id,
541 'calendar',
542 'event_description',
543 $this->properties->id,
544 $this->editoroptions,
545 $editor['text'],
546 $this->editoroptions['forcehttps']);
547 $DB->set_field('event', 'description', $this->properties->description,
548 array('id' => $this->properties->id));
551 // Log the event entry.
552 $eventargs['objectid'] = $this->properties->id;
553 $eventargs['context'] = $this->get_context();
554 $event = \core\event\calendar_event_created::create($eventargs);
555 $event->trigger();
557 $repeatedids = array();
559 if (!empty($this->properties->repeat)) {
560 $this->properties->repeatid = $this->properties->id;
561 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id' => $this->properties->id));
563 $eventcopy = clone($this->properties);
564 unset($eventcopy->id);
566 $timestart = new \DateTime('@' . $eventcopy->timestart);
567 $timestart->setTimezone(\core_date::get_user_timezone_object());
569 for ($i = 1; $i < $eventcopy->repeats; $i++) {
571 $timestart->add(new \DateInterval('P7D'));
572 $eventcopy->timestart = $timestart->getTimestamp();
574 // Get the event id for the log record.
575 $eventcopyid = $DB->insert_record('event', $eventcopy);
577 // If the context has been set delete all associated files.
578 if ($usingeditor) {
579 $fs = get_file_storage();
580 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description',
581 $this->properties->id);
582 foreach ($files as $file) {
583 $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
587 $repeatedids[] = $eventcopyid;
589 // Trigger an event.
590 $eventargs['objectid'] = $eventcopyid;
591 $eventargs['other']['timestart'] = $eventcopy->timestart;
592 $event = \core\event\calendar_event_created::create($eventargs);
593 $event->trigger();
597 return true;
598 } else {
600 if ($checkcapability) {
601 if (!calendar_edit_event_allowed($this->properties)) {
602 print_error('nopermissiontoupdatecalendar');
606 if ($usingeditor) {
607 if ($this->editorcontext !== null) {
608 $this->properties->description = file_save_draft_area_files(
609 $this->properties->description['itemid'],
610 $this->editorcontext->id,
611 'calendar',
612 'event_description',
613 $this->properties->id,
614 $this->editoroptions,
615 $this->properties->description['text'],
616 $this->editoroptions['forcehttps']);
617 } else {
618 $this->properties->format = $this->properties->description['format'];
619 $this->properties->description = $this->properties->description['text'];
623 $event = $DB->get_record('event', array('id' => $this->properties->id));
625 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
627 if ($updaterepeated) {
629 $sqlset = 'name = ?,
630 description = ?,
631 timeduration = ?,
632 timemodified = ?,
633 groupid = ?,
634 courseid = ?';
636 // Note: Group and course id may not be set. If not, keep their current values.
637 $params = [
638 $this->properties->name,
639 $this->properties->description,
640 $this->properties->timeduration,
641 time(),
642 isset($this->properties->groupid) ? $this->properties->groupid : $event->groupid,
643 isset($this->properties->courseid) ? $this->properties->courseid : $event->courseid,
646 // Note: Only update start date, if it was changed by the user.
647 if ($this->properties->timestart != $event->timestart) {
648 $timestartoffset = $this->properties->timestart - $event->timestart;
649 $sqlset .= ', timestart = timestart + ?';
650 $params[] = $timestartoffset;
653 // Note: Only update location, if it was changed by the user.
654 $updatelocation = (!empty($this->properties->location) && $this->properties->location !== $event->location);
655 if ($updatelocation) {
656 $sqlset .= ', location = ?';
657 $params[] = $this->properties->location;
660 // Update all.
661 $sql = "UPDATE {event}
662 SET $sqlset
663 WHERE repeatid = ?";
665 $params[] = $event->repeatid;
666 $DB->execute($sql, $params);
668 // Trigger an update event for each of the calendar event.
669 $events = $DB->get_records('event', array('repeatid' => $event->repeatid), '', '*');
670 foreach ($events as $calendarevent) {
671 $eventargs['objectid'] = $calendarevent->id;
672 $eventargs['other']['timestart'] = $calendarevent->timestart;
673 $event = \core\event\calendar_event_updated::create($eventargs);
674 $event->add_record_snapshot('event', $calendarevent);
675 $event->trigger();
677 } else {
678 $DB->update_record('event', $this->properties);
679 $event = self::load($this->properties->id);
680 $this->properties = $event->properties();
682 // Trigger an update event.
683 $event = \core\event\calendar_event_updated::create($eventargs);
684 $event->add_record_snapshot('event', $this->properties);
685 $event->trigger();
688 return true;
693 * Deletes an event and if selected an repeated events in the same series
695 * This function deletes an event, any associated events if $deleterepeated=true,
696 * and cleans up any files associated with the events.
698 * @see self::delete()
700 * @param bool $deleterepeated delete event repeatedly
701 * @return bool succession of deleting event
703 public function delete($deleterepeated = false) {
704 global $DB;
706 // If $this->properties->id is not set then something is wrong.
707 if (empty($this->properties->id)) {
708 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
709 return false;
711 $calevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
712 // Delete the event.
713 $DB->delete_records('event', array('id' => $this->properties->id));
715 // Trigger an event for the delete action.
716 $eventargs = array(
717 'context' => $this->get_context(),
718 'objectid' => $this->properties->id,
719 'other' => array(
720 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
721 'timestart' => $this->properties->timestart,
722 'name' => $this->properties->name
724 $event = \core\event\calendar_event_deleted::create($eventargs);
725 $event->add_record_snapshot('event', $calevent);
726 $event->trigger();
728 // If we are deleting parent of a repeated event series, promote the next event in the series as parent.
729 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
730 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC",
731 array($this->properties->id), IGNORE_MULTIPLE);
732 if (!empty($newparent)) {
733 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?",
734 array($newparent, $this->properties->id));
735 // Get all records where the repeatid is the same as the event being removed.
736 $events = $DB->get_records('event', array('repeatid' => $newparent));
737 // For each of the returned events trigger an update event.
738 foreach ($events as $calendarevent) {
739 // Trigger an event for the update.
740 $eventargs['objectid'] = $calendarevent->id;
741 $eventargs['other']['timestart'] = $calendarevent->timestart;
742 $event = \core\event\calendar_event_updated::create($eventargs);
743 $event->add_record_snapshot('event', $calendarevent);
744 $event->trigger();
749 // If the editor context hasn't already been set then set it now.
750 if ($this->editorcontext === null) {
751 $this->editorcontext = $this->get_context();
754 // If the context has been set delete all associated files.
755 if ($this->editorcontext !== null) {
756 $fs = get_file_storage();
757 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
758 foreach ($files as $file) {
759 $file->delete();
763 // If we need to delete repeated events then we will fetch them all and delete one by one.
764 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
765 // Get all records where the repeatid is the same as the event being removed.
766 $events = $DB->get_records('event', array('repeatid' => $this->properties->repeatid));
767 // For each of the returned events populate an event object and call delete.
768 // make sure the arg passed is false as we are already deleting all repeats.
769 foreach ($events as $event) {
770 $event = new calendar_event($event);
771 $event->delete(false);
775 return true;
779 * Fetch all event properties.
781 * This function returns all of the events properties as an object and optionally
782 * can prepare an editor for the description field at the same time. This is
783 * designed to work when the properties are going to be used to set the default
784 * values of a moodle forms form.
786 * @param bool $prepareeditor If set to true a editor is prepared for use with
787 * the mforms editor element. (for description)
788 * @return \stdClass Object containing event properties
790 public function properties($prepareeditor = false) {
791 global $DB;
793 // First take a copy of the properties. We don't want to actually change the
794 // properties or we'd forever be converting back and forwards between an
795 // editor formatted description and not.
796 $properties = clone($this->properties);
797 // Clean the description here.
798 $properties->description = clean_text($properties->description, $properties->format);
800 // If set to true we need to prepare the properties for use with an editor
801 // and prepare the file area.
802 if ($prepareeditor) {
804 // We may or may not have a property id. If we do then we need to work
805 // out the context so we can copy the existing files to the draft area.
806 if (!empty($properties->id)) {
808 if ($properties->eventtype === 'site') {
809 // Site context.
810 $this->editorcontext = $this->get_context();
811 } else if ($properties->eventtype === 'user') {
812 // User context.
813 $this->editorcontext = $this->get_context();
814 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
815 // First check the course is valid.
816 $course = $DB->get_record('course', array('id' => $properties->courseid));
817 if (!$course) {
818 print_error('invalidcourse');
820 // Course context.
821 $this->editorcontext = $this->get_context();
822 // We have a course and are within the course context so we had
823 // better use the courses max bytes value.
824 $this->editoroptions['maxbytes'] = $course->maxbytes;
825 } else if ($properties->eventtype === 'category') {
826 // First check the course is valid.
827 \core_course_category::get($properties->categoryid, MUST_EXIST, true);
828 // Course context.
829 $this->editorcontext = $this->get_context();
830 } else {
831 // If we get here we have a custom event type as used by some
832 // modules. In this case the event will have been added by
833 // code and we won't need the editor.
834 $this->editoroptions['maxbytes'] = 0;
835 $this->editoroptions['maxfiles'] = 0;
838 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
839 $contextid = false;
840 } else {
841 // Get the context id that is what we really want.
842 $contextid = $this->editorcontext->id;
844 } else {
846 // If we get here then this is a new event in which case we don't need a
847 // context as there is no existing files to copy to the draft area.
848 $contextid = null;
851 // If the contextid === false we don't support files so no preparing
852 // a draft area.
853 if ($contextid !== false) {
854 // Just encase it has already been submitted.
855 $draftiddescription = file_get_submitted_draft_itemid('description');
856 // Prepare the draft area, this copies existing files to the draft area as well.
857 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar',
858 'event_description', $properties->id, $this->editoroptions, $properties->description);
859 } else {
860 $draftiddescription = 0;
863 // Structure the description field as the editor requires.
864 $properties->description = array('text' => $properties->description, 'format' => $properties->format,
865 'itemid' => $draftiddescription);
868 // Finally return the properties.
869 return $properties;
873 * Toggles the visibility of an event
875 * @param null|bool $force If it is left null the events visibility is flipped,
876 * If it is false the event is made hidden, if it is true it
877 * is made visible.
878 * @return bool if event is successfully updated, toggle will be visible
880 public function toggle_visibility($force = null) {
881 global $DB;
883 // Set visible to the default if it is not already set.
884 if (empty($this->properties->visible)) {
885 $this->properties->visible = 1;
888 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
889 // Make this event visible.
890 $this->properties->visible = 1;
891 } else {
892 // Make this event hidden.
893 $this->properties->visible = 0;
896 // Update the database to reflect this change.
897 $success = $DB->set_field('event', 'visible', $this->properties->visible, array('id' => $this->properties->id));
898 $calendarevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
900 // Prepare event data.
901 $eventargs = array(
902 'context' => $this->get_context(),
903 'objectid' => $this->properties->id,
904 'other' => array(
905 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
906 'timestart' => $this->properties->timestart,
907 'name' => $this->properties->name
910 $event = \core\event\calendar_event_updated::create($eventargs);
911 $event->add_record_snapshot('event', $calendarevent);
912 $event->trigger();
914 return $success;
918 * Returns an event object when provided with an event id.
920 * This function makes use of MUST_EXIST, if the event id passed in is invalid
921 * it will result in an exception being thrown.
923 * @param int|object $param event object or event id
924 * @return calendar_event
926 public static function load($param) {
927 global $DB;
928 if (is_object($param)) {
929 $event = new calendar_event($param);
930 } else {
931 $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST);
932 $event = new calendar_event($event);
934 return $event;
938 * Creates a new event and returns an event object.
940 * Capability checking should be performed if the user is directly creating the event
941 * and no other capability has been tested. However if the event is not being created
942 * directly by the user and another capability has been checked for them to do this then
943 * capabilites should not be checked.
945 * For example if a user is creating an event in the calendar the check should be true,
946 * but if you are creating an event in an activity when it is created then the calendar
947 * capabilites should not be checked.
949 * @param \stdClass|array $properties An object containing event properties
950 * @param bool $checkcapability If Moodle should check the user can manage the calendar events for this call or not.
951 * @throws \coding_exception
953 * @return calendar_event|bool The event object or false if it failed
955 public static function create($properties, $checkcapability = true) {
956 if (is_array($properties)) {
957 $properties = (object)$properties;
959 if (!is_object($properties)) {
960 throw new \coding_exception('When creating an event properties should be either an object or an assoc array');
962 $event = new calendar_event($properties);
963 if ($event->update($properties, $checkcapability)) {
964 return $event;
965 } else {
966 return false;
971 * Format the event name using the external API.
973 * This function should we used when text formatting is required in external functions.
975 * @return string Formatted name.
977 public function format_external_name() {
978 if ($this->editorcontext === null) {
979 // Switch on the event type to decide upon the appropriate context to use for this event.
980 $this->editorcontext = $this->get_context();
983 return external_format_string($this->properties->name, $this->editorcontext->id);
987 * Format the text using the external API.
989 * This function should we used when text formatting is required in external functions.
991 * @return array an array containing the text formatted and the text format
993 public function format_external_text() {
995 if ($this->editorcontext === null) {
996 // Switch on the event type to decide upon the appropriate context to use for this event.
997 $this->editorcontext = $this->get_context();
999 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
1000 // We don't have a context here, do a normal format_text.
1001 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id);
1005 // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
1006 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
1007 $itemid = $this->properties->repeatid;
1008 } else {
1009 $itemid = $this->properties->id;
1012 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id,
1013 'calendar', 'event_description', $itemid);
1018 * Calendar information class
1020 * This class is used simply to organise the information pertaining to a calendar
1021 * and is used primarily to make information easily available.
1023 * @package core_calendar
1024 * @category calendar
1025 * @copyright 2010 Sam Hemelryk
1026 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1028 class calendar_information {
1031 * @var int The timestamp
1033 * Rather than setting the day, month and year we will set a timestamp which will be able
1034 * to be used by multiple calendars.
1036 public $time;
1038 /** @var int A course id */
1039 public $courseid = null;
1041 /** @var array An array of categories */
1042 public $categories = array();
1044 /** @var int The current category */
1045 public $categoryid = null;
1047 /** @var array An array of courses */
1048 public $courses = array();
1050 /** @var array An array of groups */
1051 public $groups = array();
1053 /** @var array An array of users */
1054 public $users = array();
1056 /** @var context The anticipated context that the calendar is viewed in */
1057 public $context = null;
1060 * Creates a new instance
1062 * @param int $day the number of the day
1063 * @param int $month the number of the month
1064 * @param int $year the number of the year
1065 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
1066 * and $calyear to support multiple calendars
1068 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
1069 // If a day, month and year were passed then convert it to a timestamp. If these were passed
1070 // then we can assume the day, month and year are passed as Gregorian, as no where in core
1071 // should we be passing these values rather than the time. This is done for BC.
1072 if (!empty($day) || !empty($month) || !empty($year)) {
1073 $date = usergetdate(time());
1074 if (empty($day)) {
1075 $day = $date['mday'];
1077 if (empty($month)) {
1078 $month = $date['mon'];
1080 if (empty($year)) {
1081 $year = $date['year'];
1083 if (checkdate($month, $day, $year)) {
1084 $time = make_timestamp($year, $month, $day);
1085 } else {
1086 $time = time();
1090 $this->set_time($time);
1094 * Creates and set up a instance.
1096 * @param int $time the unixtimestamp representing the date we want to view.
1097 * @param int $courseid The ID of the course the user wishes to view.
1098 * @param int $categoryid The ID of the category the user wishes to view
1099 * If a courseid is specified, this value is ignored.
1100 * @return calendar_information
1102 public static function create($time, int $courseid, int $categoryid = null) : calendar_information {
1103 $calendar = new static(0, 0, 0, $time);
1104 if ($courseid != SITEID && !empty($courseid)) {
1105 // Course ID must be valid and existing.
1106 $course = get_course($courseid);
1107 $calendar->context = context_course::instance($course->id);
1109 if (!$course->visible && !is_role_switched($course->id)) {
1110 require_capability('moodle/course:viewhiddencourses', $calendar->context);
1113 $courses = [$course->id => $course];
1114 $category = (\core_course_category::get($course->category, MUST_EXIST, true))->get_db_record();
1115 } else if (!empty($categoryid)) {
1116 $course = get_site();
1117 $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1119 // Filter available courses to those within this category or it's children.
1120 $ids = [$categoryid];
1121 $category = \core_course_category::get($categoryid);
1122 $ids = array_merge($ids, array_keys($category->get_children()));
1123 $courses = array_filter($courses, function($course) use ($ids) {
1124 return array_search($course->category, $ids) !== false;
1126 $category = $category->get_db_record();
1128 $calendar->context = context_coursecat::instance($categoryid);
1129 } else {
1130 $course = get_site();
1131 $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1132 $category = null;
1134 $calendar->context = context_system::instance();
1137 $calendar->set_sources($course, $courses, $category);
1139 return $calendar;
1143 * Set the time period of this instance.
1145 * @param int $time the unixtimestamp representing the date we want to view.
1146 * @return $this
1148 public function set_time($time = null) {
1149 if (empty($time)) {
1150 $this->time = time();
1151 } else {
1152 $this->time = $time;
1155 return $this;
1159 * Initialize calendar information
1161 * @deprecated 3.4
1162 * @param stdClass $course object
1163 * @param array $coursestoload An array of courses [$course->id => $course]
1164 * @param bool $ignorefilters options to use filter
1166 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
1167 debugging('The prepare_for_view() function has been deprecated. Please update your code to use set_sources()',
1168 DEBUG_DEVELOPER);
1169 $this->set_sources($course, $coursestoload);
1173 * Set the sources for events within the calendar.
1175 * If no category is provided, then the category path for the current
1176 * course will be used.
1178 * @param stdClass $course The current course being viewed.
1179 * @param stdClass[] $courses The list of all courses currently accessible.
1180 * @param stdClass $category The current category to show.
1182 public function set_sources(stdClass $course, array $courses, stdClass $category = null) {
1183 global $USER;
1185 // A cousre must always be specified.
1186 $this->course = $course;
1187 $this->courseid = $course->id;
1189 list($courseids, $group, $user) = calendar_set_filters($courses);
1190 $this->courses = $courseids;
1191 $this->groups = $group;
1192 $this->users = $user;
1194 // Do not show category events by default.
1195 $this->categoryid = null;
1196 $this->categories = null;
1198 // Determine the correct category information to show.
1199 // When called with a course, the category of that course is usually included too.
1200 // When a category was specifically requested, it should be requested with the site id.
1201 if (SITEID !== $this->courseid) {
1202 // A specific course was requested.
1203 // Fetch the category that this course is in, along with all parents.
1204 // Do not include child categories of this category, as the user many not have enrolments in those siblings or children.
1205 $category = \core_course_category::get($course->category, MUST_EXIST, true);
1206 $this->categoryid = $category->id;
1208 $this->categories = $category->get_parents();
1209 $this->categories[] = $category->id;
1210 } else if (null !== $category && $category->id > 0) {
1211 // A specific category was requested.
1212 // Fetch all parents of this category, along with all children too.
1213 $category = \core_course_category::get($category->id);
1214 $this->categoryid = $category->id;
1216 // Build the category list.
1217 // This includes the current category.
1218 $this->categories = $category->get_parents();
1219 $this->categories[] = $category->id;
1220 $this->categories = array_merge($this->categories, $category->get_all_children_ids());
1221 } else if (SITEID === $this->courseid) {
1222 // The site was requested.
1223 // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
1225 // Grab the list of categories that this user has courses in.
1226 $coursecategories = array_flip(array_map(function($course) {
1227 return $course->category;
1228 }, $courses));
1230 $calcatcache = cache::make('core', 'calendar_categories');
1231 $this->categories = $calcatcache->get('site');
1232 if ($this->categories === false) {
1233 // Use the category id as the key in the following array. That way we do not have to remove duplicates.
1234 $categories = [];
1235 foreach (\core_course_category::get_all() as $category) {
1236 if (isset($coursecategories[$category->id]) ||
1237 has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
1238 // If the user has access to a course in this category or can manage the category,
1239 // then they can see all parent categories too.
1240 $categories[$category->id] = true;
1241 foreach ($category->get_parents() as $catid) {
1242 $categories[$catid] = true;
1246 $this->categories = array_keys($categories);
1247 $calcatcache->set('site', $this->categories);
1253 * Ensures the date for the calendar is correct and either sets it to now
1254 * or throws a moodle_exception if not
1256 * @param bool $defaultonow use current time
1257 * @throws moodle_exception
1258 * @return bool validation of checkdate
1260 public function checkdate($defaultonow = true) {
1261 if (!checkdate($this->month, $this->day, $this->year)) {
1262 if ($defaultonow) {
1263 $now = usergetdate(time());
1264 $this->day = intval($now['mday']);
1265 $this->month = intval($now['mon']);
1266 $this->year = intval($now['year']);
1267 return true;
1268 } else {
1269 throw new moodle_exception('invaliddate');
1272 return true;
1276 * Gets todays timestamp for the calendar
1278 * @return int today timestamp
1280 public function timestamp_today() {
1281 return $this->time;
1284 * Gets tomorrows timestamp for the calendar
1286 * @return int tomorrow timestamp
1288 public function timestamp_tomorrow() {
1289 return strtotime('+1 day', $this->time);
1292 * Adds the pretend blocks for the calendar
1294 * @param core_calendar_renderer $renderer
1295 * @param bool $showfilters display filters, false is set as default
1296 * @param string|null $view preference view options (eg: day, month, upcoming)
1298 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
1299 global $PAGE;
1301 if (!has_capability('moodle/block:view', $PAGE->context) ) {
1302 return;
1305 if ($showfilters) {
1306 $filters = new block_contents();
1307 $filters->content = $renderer->event_filter();
1308 $filters->footer = '';
1309 $filters->title = get_string('eventskey', 'calendar');
1310 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
1312 $block = new block_contents;
1313 $block->content = $renderer->fake_block_threemonths($this);
1314 $block->footer = '';
1315 $block->title = get_string('monthlyview', 'calendar');
1316 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
1321 * Get calendar events.
1323 * @param int $tstart Start time of time range for events
1324 * @param int $tend End time of time range for events
1325 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
1326 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
1327 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
1328 * @param boolean $withduration whether only events starting within time range selected
1329 * or events in progress/already started selected as well
1330 * @param boolean $ignorehidden whether to select only visible events or all events
1331 * @param array|int|boolean $categories array of categories, category id or boolean for all/no course events
1332 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
1334 function calendar_get_events($tstart, $tend, $users, $groups, $courses,
1335 $withduration = true, $ignorehidden = true, $categories = []) {
1336 global $DB;
1338 $whereclause = '';
1339 $params = array();
1340 // Quick test.
1341 if (empty($users) && empty($groups) && empty($courses) && empty($categories)) {
1342 return array();
1345 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
1346 // Events from a number of users
1347 if(!empty($whereclause)) $whereclause .= ' OR';
1348 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED);
1349 $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)";
1350 $params = array_merge($params, $inparamsusers);
1351 } else if($users === true) {
1352 // Events from ALL users
1353 if(!empty($whereclause)) $whereclause .= ' OR';
1354 $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)';
1355 } else if($users === false) {
1356 // No user at all, do nothing
1359 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
1360 // Events from a number of groups
1361 if(!empty($whereclause)) $whereclause .= ' OR';
1362 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED);
1363 $whereclause .= " e.groupid $insqlgroups ";
1364 $params = array_merge($params, $inparamsgroups);
1365 } else if($groups === true) {
1366 // Events from ALL groups
1367 if(!empty($whereclause)) $whereclause .= ' OR ';
1368 $whereclause .= ' e.groupid != 0';
1370 // boolean false (no groups at all): we don't need to do anything
1372 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
1373 if(!empty($whereclause)) $whereclause .= ' OR';
1374 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED);
1375 $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
1376 $params = array_merge($params, $inparamscourses);
1377 } else if ($courses === true) {
1378 // Events from ALL courses
1379 if(!empty($whereclause)) $whereclause .= ' OR';
1380 $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
1383 if ((is_array($categories) && !empty($categories)) || is_numeric($categories)) {
1384 if (!empty($whereclause)) {
1385 $whereclause .= ' OR';
1387 list($insqlcategories, $inparamscategories) = $DB->get_in_or_equal($categories, SQL_PARAMS_NAMED);
1388 $whereclause .= " (e.groupid = 0 AND e.courseid = 0 AND e.categoryid $insqlcategories)";
1389 $params = array_merge($params, $inparamscategories);
1390 } else if ($categories === true) {
1391 // Events from ALL categories.
1392 if (!empty($whereclause)) {
1393 $whereclause .= ' OR';
1395 $whereclause .= ' (e.groupid = 0 AND e.courseid = 0 AND e.categoryid != 0)';
1398 // Security check: if, by now, we have NOTHING in $whereclause, then it means
1399 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
1400 // events no matter what. Allowing the code to proceed might return a completely
1401 // valid query with only time constraints, thus selecting ALL events in that time frame!
1402 if(empty($whereclause)) {
1403 return array();
1406 if($withduration) {
1407 $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1409 else {
1410 $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1412 if(!empty($whereclause)) {
1413 // We have additional constraints
1414 $whereclause = $timeclause.' AND ('.$whereclause.')';
1416 else {
1417 // Just basic time filtering
1418 $whereclause = $timeclause;
1421 if ($ignorehidden) {
1422 $whereclause .= ' AND e.visible = 1';
1425 $sql = "SELECT e.*
1426 FROM {event} e
1427 LEFT JOIN {modules} m ON e.modulename = m.name
1428 -- Non visible modules will have a value of 0.
1429 WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
1430 ORDER BY e.timestart";
1431 $events = $DB->get_records_sql($sql, $params);
1433 if ($events === false) {
1434 $events = array();
1436 return $events;
1440 * Return the days of the week.
1442 * @return array array of days
1444 function calendar_get_days() {
1445 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1446 return $calendartype->get_weekdays();
1450 * Get the subscription from a given id.
1452 * @since Moodle 2.5
1453 * @param int $id id of the subscription
1454 * @return stdClass Subscription record from DB
1455 * @throws moodle_exception for an invalid id
1457 function calendar_get_subscription($id) {
1458 global $DB;
1460 $cache = \cache::make('core', 'calendar_subscriptions');
1461 $subscription = $cache->get($id);
1462 if (empty($subscription)) {
1463 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
1464 $cache->set($id, $subscription);
1467 return $subscription;
1471 * Gets the first day of the week.
1473 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
1475 * @return int
1477 function calendar_get_starting_weekday() {
1478 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1479 return $calendartype->get_starting_weekday();
1483 * Get a HTML link to a course.
1485 * @param int|stdClass $course the course id or course object
1486 * @return string a link to the course (as HTML); empty if the course id is invalid
1488 function calendar_get_courselink($course) {
1489 if (!$course) {
1490 return '';
1493 if (!is_object($course)) {
1494 $course = calendar_get_course_cached($coursecache, $course);
1496 $context = \context_course::instance($course->id);
1497 $fullname = format_string($course->fullname, true, array('context' => $context));
1498 $url = new \moodle_url('/course/view.php', array('id' => $course->id));
1499 $link = \html_writer::link($url, $fullname);
1501 return $link;
1505 * Get current module cache.
1507 * Only use this method if you do not know courseid. Otherwise use:
1508 * get_fast_modinfo($courseid)->instances[$modulename][$instance]
1510 * @param array $modulecache in memory module cache
1511 * @param string $modulename name of the module
1512 * @param int $instance module instance number
1513 * @return stdClass|bool $module information
1515 function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
1516 if (!isset($modulecache[$modulename . '_' . $instance])) {
1517 $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
1520 return $modulecache[$modulename . '_' . $instance];
1524 * Get current course cache.
1526 * @param array $coursecache list of course cache
1527 * @param int $courseid id of the course
1528 * @return stdClass $coursecache[$courseid] return the specific course cache
1530 function calendar_get_course_cached(&$coursecache, $courseid) {
1531 if (!isset($coursecache[$courseid])) {
1532 $coursecache[$courseid] = get_course($courseid);
1534 return $coursecache[$courseid];
1538 * Get group from groupid for calendar display
1540 * @param int $groupid
1541 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1543 function calendar_get_group_cached($groupid) {
1544 static $groupscache = array();
1545 if (!isset($groupscache[$groupid])) {
1546 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1548 return $groupscache[$groupid];
1552 * Add calendar event metadata
1554 * @deprecated since 3.9
1556 * @param stdClass $event event info
1557 * @return stdClass $event metadata
1559 function calendar_add_event_metadata($event) {
1560 debugging('This function is no longer used', DEBUG_DEVELOPER);
1561 global $CFG, $OUTPUT;
1563 // Support multilang in event->name.
1564 $event->name = format_string($event->name, true);
1566 if (!empty($event->modulename)) { // Activity event.
1567 // The module name is set. I will assume that it has to be displayed, and
1568 // also that it is an automatically-generated event. And of course that the
1569 // instace id and modulename are set correctly.
1570 $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
1571 if (!array_key_exists($event->instance, $instances)) {
1572 return;
1574 $module = $instances[$event->instance];
1576 $modulename = $module->get_module_type_name(false);
1577 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
1578 // Will be used as alt text if the event icon.
1579 $eventtype = get_string($event->eventtype, $event->modulename);
1580 } else {
1581 $eventtype = '';
1584 $event->icon = '<img src="' . s($module->get_icon_url()) . '" alt="' . s($eventtype) .
1585 '" title="' . s($modulename) . '" class="icon" />';
1586 $event->referer = html_writer::link($module->url, $event->name);
1587 $event->courselink = calendar_get_courselink($module->get_course());
1588 $event->cmid = $module->id;
1589 } else if ($event->courseid == SITEID) { // Site event.
1590 $event->icon = '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
1591 get_string('siteevent', 'calendar') . '" class="icon" />';
1592 $event->cssclass = 'calendar_event_site';
1593 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event.
1594 $event->icon = '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
1595 get_string('courseevent', 'calendar') . '" class="icon" />';
1596 $event->courselink = calendar_get_courselink($event->courseid);
1597 $event->cssclass = 'calendar_event_course';
1598 } else if ($event->groupid) { // Group event.
1599 if ($group = calendar_get_group_cached($event->groupid)) {
1600 $groupname = format_string($group->name, true, \context_course::instance($group->courseid));
1601 } else {
1602 $groupname = '';
1604 $event->icon = \html_writer::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
1605 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
1606 $event->courselink = calendar_get_courselink($event->courseid) . ', ' . $groupname;
1607 $event->cssclass = 'calendar_event_group';
1608 } else if ($event->userid) { // User event.
1609 $event->icon = '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
1610 get_string('userevent', 'calendar') . '" class="icon" />';
1611 $event->cssclass = 'calendar_event_user';
1614 return $event;
1618 * Get calendar events by id.
1620 * @since Moodle 2.5
1621 * @param array $eventids list of event ids
1622 * @return array Array of event entries, empty array if nothing found
1624 function calendar_get_events_by_id($eventids) {
1625 global $DB;
1627 if (!is_array($eventids) || empty($eventids)) {
1628 return array();
1631 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
1632 $wheresql = "id $wheresql";
1634 return $DB->get_records_select('event', $wheresql, $params);
1638 * Get control options for calendar.
1640 * @param string $type of calendar
1641 * @param array $data calendar information
1642 * @return string $content return available control for the calender in html
1644 function calendar_top_controls($type, $data) {
1645 global $PAGE, $OUTPUT;
1647 // Get the calendar type we are using.
1648 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1650 $content = '';
1652 // Ensure course id passed if relevant.
1653 $courseid = '';
1654 if (!empty($data['id'])) {
1655 $courseid = '&amp;course=' . $data['id'];
1658 // If we are passing a month and year then we need to convert this to a timestamp to
1659 // support multiple calendars. No where in core should these be passed, this logic
1660 // here is for third party plugins that may use this function.
1661 if (!empty($data['m']) && !empty($date['y'])) {
1662 if (!isset($data['d'])) {
1663 $data['d'] = 1;
1665 if (!checkdate($data['m'], $data['d'], $data['y'])) {
1666 $time = time();
1667 } else {
1668 $time = make_timestamp($data['y'], $data['m'], $data['d']);
1670 } else if (!empty($data['time'])) {
1671 $time = $data['time'];
1672 } else {
1673 $time = time();
1676 // Get the date for the calendar type.
1677 $date = $calendartype->timestamp_to_date_array($time);
1679 $urlbase = $PAGE->url;
1681 // We need to get the previous and next months in certain cases.
1682 if ($type == 'frontpage' || $type == 'course' || $type == 'month') {
1683 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1684 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
1685 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
1686 $prevmonthtime['hour'], $prevmonthtime['minute']);
1688 $nextmonth = calendar_add_month($date['mon'], $date['year']);
1689 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
1690 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
1691 $nextmonthtime['hour'], $nextmonthtime['minute']);
1694 switch ($type) {
1695 case 'frontpage':
1696 $prevlink = calendar_get_link_previous(get_string('monthprev', 'calendar'), $urlbase, false, false, false,
1697 true, $prevmonthtime);
1698 $nextlink = calendar_get_link_next(get_string('monthnext', 'calendar'), $urlbase, false, false, false, true,
1699 $nextmonthtime);
1700 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1701 false, false, false, $time);
1703 if (!empty($data['id'])) {
1704 $calendarlink->param('course', $data['id']);
1707 $right = $nextlink;
1709 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1710 $content .= $prevlink . '<span class="hide"> | </span>';
1711 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1712 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1713 ), array('class' => 'current'));
1714 $content .= '<span class="hide"> | </span>' . $right;
1715 $content .= "<span class=\"clearer\"><!-- --></span>\n";
1716 $content .= \html_writer::end_tag('div');
1718 break;
1719 case 'course':
1720 $prevlink = calendar_get_link_previous(get_string('monthprev', 'calendar'), $urlbase, false, false, false,
1721 true, $prevmonthtime);
1722 $nextlink = calendar_get_link_next(get_string('monthnext', 'calendar'), $urlbase, false, false, false,
1723 true, $nextmonthtime);
1724 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1725 false, false, false, $time);
1727 if (!empty($data['id'])) {
1728 $calendarlink->param('course', $data['id']);
1731 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1732 $content .= $prevlink . '<span class="hide"> | </span>';
1733 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1734 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1735 ), array('class' => 'current'));
1736 $content .= '<span class="hide"> | </span>' . $nextlink;
1737 $content .= "<span class=\"clearer\"><!-- --></span>";
1738 $content .= \html_writer::end_tag('div');
1739 break;
1740 case 'upcoming':
1741 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'upcoming')),
1742 false, false, false, $time);
1743 if (!empty($data['id'])) {
1744 $calendarlink->param('course', $data['id']);
1746 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1747 $content .= \html_writer::tag('div', $calendarlink, array('class' => 'centered'));
1748 break;
1749 case 'display':
1750 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1751 false, false, false, $time);
1752 if (!empty($data['id'])) {
1753 $calendarlink->param('course', $data['id']);
1755 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1756 $content .= \html_writer::tag('h3', $calendarlink);
1757 break;
1758 case 'month':
1759 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1760 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $prevmonthtime);
1761 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1762 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $nextmonthtime);
1764 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1765 $content .= $prevlink . '<span class="hide"> | </span>';
1766 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1767 $content .= '<span class="hide"> | </span>' . $nextlink;
1768 $content .= '<span class="clearer"><!-- --></span>';
1769 $content .= \html_writer::end_tag('div')."\n";
1770 break;
1771 case 'day':
1772 $days = calendar_get_days();
1774 $prevtimestamp = strtotime('-1 day', $time);
1775 $nexttimestamp = strtotime('+1 day', $time);
1777 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1778 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1780 $prevname = $days[$prevdate['wday']]['fullname'];
1781 $nextname = $days[$nextdate['wday']]['fullname'];
1782 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&amp;', false, false,
1783 false, false, $prevtimestamp);
1784 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&amp;', false, false, false,
1785 false, $nexttimestamp);
1787 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1788 $content .= $prevlink;
1789 $content .= '<span class="hide"> | </span><span class="current">' .userdate($time,
1790 get_string('strftimedaydate')) . '</span>';
1791 $content .= '<span class="hide"> | </span>' . $nextlink;
1792 $content .= "<span class=\"clearer\"><!-- --></span>";
1793 $content .= \html_writer::end_tag('div') . "\n";
1795 break;
1798 return $content;
1802 * Return the representation day.
1804 * @param int $tstamp Timestamp in GMT
1805 * @param int|bool $now current Unix timestamp
1806 * @param bool $usecommonwords
1807 * @return string the formatted date/time
1809 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1810 static $shortformat;
1812 if (empty($shortformat)) {
1813 $shortformat = get_string('strftimedayshort');
1816 if ($now === false) {
1817 $now = time();
1820 // To have it in one place, if a change is needed.
1821 $formal = userdate($tstamp, $shortformat);
1823 $datestamp = usergetdate($tstamp);
1824 $datenow = usergetdate($now);
1826 if ($usecommonwords == false) {
1827 // We don't want words, just a date.
1828 return $formal;
1829 } else if ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1830 return get_string('today', 'calendar');
1831 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1832 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12
1833 && $datenow['yday'] == 1)) {
1834 return get_string('yesterday', 'calendar');
1835 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1836 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12
1837 && $datestamp['yday'] == 1)) {
1838 return get_string('tomorrow', 'calendar');
1839 } else {
1840 return $formal;
1845 * return the formatted representation time.
1848 * @param int $time the timestamp in UTC, as obtained from the database
1849 * @return string the formatted date/time
1851 function calendar_time_representation($time) {
1852 static $langtimeformat = null;
1854 if ($langtimeformat === null) {
1855 $langtimeformat = get_string('strftimetime');
1858 $timeformat = get_user_preferences('calendar_timeformat');
1859 if (empty($timeformat)) {
1860 $timeformat = get_config(null, 'calendar_site_timeformat');
1863 // Allow language customization of selected time format.
1864 if ($timeformat === CALENDAR_TF_12) {
1865 $timeformat = get_string('strftimetime12', 'langconfig');
1866 } else if ($timeformat === CALENDAR_TF_24) {
1867 $timeformat = get_string('strftimetime24', 'langconfig');
1870 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
1874 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1876 * @param string|moodle_url $linkbase
1877 * @param int $d The number of the day.
1878 * @param int $m The number of the month.
1879 * @param int $y The number of the year.
1880 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1881 * $m and $y are kept for backwards compatibility.
1882 * @return moodle_url|null $linkbase
1884 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1885 if (empty($linkbase)) {
1886 return null;
1889 if (!($linkbase instanceof \moodle_url)) {
1890 $linkbase = new \moodle_url($linkbase);
1893 $linkbase->param('time', calendar_get_timestamp($d, $m, $y, $time));
1895 return $linkbase;
1899 * Build and return a previous month HTML link, with an arrow.
1901 * @param string $text The text label.
1902 * @param string|moodle_url $linkbase The URL stub.
1903 * @param int $d The number of the date.
1904 * @param int $m The number of the month.
1905 * @param int $y year The number of the year.
1906 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1907 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1908 * $m and $y are kept for backwards compatibility.
1909 * @return string HTML string.
1911 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1912 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1914 if (empty($href)) {
1915 return $text;
1918 $attrs = [
1919 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1920 'data-drop-zone' => 'nav-link',
1923 return link_arrow_left($text, $href->out(false), $accesshide, 'previous', $attrs);
1927 * Build and return a next month HTML link, with an arrow.
1929 * @param string $text The text label.
1930 * @param string|moodle_url $linkbase The URL stub.
1931 * @param int $d the number of the Day
1932 * @param int $m The number of the month.
1933 * @param int $y The number of the year.
1934 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1935 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1936 * $m and $y are kept for backwards compatibility.
1937 * @return string HTML string.
1939 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1940 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1942 if (empty($href)) {
1943 return $text;
1946 $attrs = [
1947 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1948 'data-drop-zone' => 'nav-link',
1951 return link_arrow_right($text, $href->out(false), $accesshide, 'next', $attrs);
1955 * Return the number of days in month.
1957 * @param int $month the number of the month.
1958 * @param int $year the number of the year
1959 * @return int
1961 function calendar_days_in_month($month, $year) {
1962 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1963 return $calendartype->get_num_days_in_month($year, $month);
1967 * Get the next following month.
1969 * @param int $month the number of the month.
1970 * @param int $year the number of the year.
1971 * @return array the following month
1973 function calendar_add_month($month, $year) {
1974 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1975 return $calendartype->get_next_month($year, $month);
1979 * Get the previous month.
1981 * @param int $month the number of the month.
1982 * @param int $year the number of the year.
1983 * @return array previous month
1985 function calendar_sub_month($month, $year) {
1986 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1987 return $calendartype->get_prev_month($year, $month);
1991 * Get per-day basis events
1993 * @param array $events list of events
1994 * @param int $month the number of the month
1995 * @param int $year the number of the year
1996 * @param array $eventsbyday event on specific day
1997 * @param array $durationbyday duration of the event in days
1998 * @param array $typesbyday event type (eg: site, course, user, or group)
1999 * @param array $courses list of courses
2000 * @return void
2002 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
2003 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2005 $eventsbyday = array();
2006 $typesbyday = array();
2007 $durationbyday = array();
2009 if ($events === false) {
2010 return;
2013 foreach ($events as $event) {
2014 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
2015 if ($event->timeduration) {
2016 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
2017 } else {
2018 $enddate = $startdate;
2021 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair.
2022 if (!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) &&
2023 ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
2024 continue;
2027 $eventdaystart = intval($startdate['mday']);
2029 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2030 // Give the event to its day.
2031 $eventsbyday[$eventdaystart][] = $event->id;
2033 // Mark the day as having such an event.
2034 if ($event->courseid == SITEID && $event->groupid == 0) {
2035 $typesbyday[$eventdaystart]['startsite'] = true;
2036 // Set event class for site event.
2037 $events[$event->id]->class = 'calendar_event_site';
2038 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
2039 $typesbyday[$eventdaystart]['startcourse'] = true;
2040 // Set event class for course event.
2041 $events[$event->id]->class = 'calendar_event_course';
2042 } else if ($event->groupid) {
2043 $typesbyday[$eventdaystart]['startgroup'] = true;
2044 // Set event class for group event.
2045 $events[$event->id]->class = 'calendar_event_group';
2046 } else if ($event->userid) {
2047 $typesbyday[$eventdaystart]['startuser'] = true;
2048 // Set event class for user event.
2049 $events[$event->id]->class = 'calendar_event_user';
2053 if ($event->timeduration == 0) {
2054 // Proceed with the next.
2055 continue;
2058 // The event starts on $month $year or before.
2059 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2060 $lowerbound = intval($startdate['mday']);
2061 } else {
2062 $lowerbound = 0;
2065 // Also, it ends on $month $year or later.
2066 if ($enddate['mon'] == $month && $enddate['year'] == $year) {
2067 $upperbound = intval($enddate['mday']);
2068 } else {
2069 $upperbound = calendar_days_in_month($month, $year);
2072 // Mark all days between $lowerbound and $upperbound (inclusive) as duration.
2073 for ($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
2074 $durationbyday[$i][] = $event->id;
2075 if ($event->courseid == SITEID && $event->groupid == 0) {
2076 $typesbyday[$i]['durationsite'] = true;
2077 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
2078 $typesbyday[$i]['durationcourse'] = true;
2079 } else if ($event->groupid) {
2080 $typesbyday[$i]['durationgroup'] = true;
2081 } else if ($event->userid) {
2082 $typesbyday[$i]['durationuser'] = true;
2087 return;
2091 * Returns the courses to load events for.
2093 * @param array $courseeventsfrom An array of courses to load calendar events for
2094 * @param bool $ignorefilters specify the use of filters, false is set as default
2095 * @param stdClass $user The user object. This defaults to the global $USER object.
2096 * @return array An array of courses, groups, and user to load calendar events for based upon filters
2098 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false, stdClass $user = null) {
2099 global $CFG, $USER;
2101 if (is_null($user)) {
2102 $user = $USER;
2105 $courses = array();
2106 $userid = false;
2107 $group = false;
2109 // Get the capabilities that allow seeing group events from all groups.
2110 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
2112 $isvaliduser = !empty($user->id);
2114 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE, $user)) {
2115 $courses = array_keys($courseeventsfrom);
2117 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_SITE, $user)) {
2118 $courses[] = SITEID;
2120 $courses = array_unique($courses);
2121 sort($courses);
2123 if (!empty($courses) && in_array(SITEID, $courses)) {
2124 // Sort courses for consistent colour highlighting.
2125 // Effectively ignoring SITEID as setting as last course id.
2126 $key = array_search(SITEID, $courses);
2127 unset($courses[$key]);
2128 $courses[] = SITEID;
2131 if ($ignorefilters || ($isvaliduser && calendar_show_event_type(CALENDAR_EVENT_USER, $user))) {
2132 $userid = $user->id;
2135 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP, $user) || $ignorefilters)) {
2137 if (count($courseeventsfrom) == 1) {
2138 $course = reset($courseeventsfrom);
2139 if (has_any_capability($allgroupscaps, \context_course::instance($course->id))) {
2140 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
2141 $group = array_keys($coursegroups);
2144 if ($group === false) {
2145 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, \context_system::instance())) {
2146 $group = true;
2147 } else if ($isvaliduser) {
2148 $groupids = array();
2149 foreach ($courseeventsfrom as $courseid => $course) {
2150 // If the user is an editing teacher in there.
2151 if (!empty($user->groupmember[$course->id])) {
2152 // We've already cached the users groups for this course so we can just use that.
2153 $groupids = array_merge($groupids, $user->groupmember[$course->id]);
2154 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2155 // If this course has groups, show events from all of those related to the current user.
2156 $coursegroups = groups_get_user_groups($course->id, $user->id);
2157 $groupids = array_merge($groupids, $coursegroups['0']);
2160 if (!empty($groupids)) {
2161 $group = $groupids;
2166 if (empty($courses)) {
2167 $courses = false;
2170 return array($courses, $group, $userid);
2174 * Return the capability for viewing a calendar event.
2176 * @param calendar_event $event event object
2177 * @return boolean
2179 function calendar_view_event_allowed(calendar_event $event) {
2180 global $USER;
2182 // Anyone can see site events.
2183 if ($event->courseid && $event->courseid == SITEID) {
2184 return true;
2187 // If a user can manage events at the site level they can see any event.
2188 $sitecontext = \context_system::instance();
2189 // If user has manageentries at site level, return true.
2190 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2191 return true;
2194 if (!empty($event->groupid)) {
2195 // If it is a group event we need to be able to manage events in the course, or be in the group.
2196 if (has_capability('moodle/calendar:manageentries', $event->context) ||
2197 has_capability('moodle/calendar:managegroupentries', $event->context)) {
2198 return true;
2201 $mycourses = enrol_get_my_courses('id');
2202 return isset($mycourses[$event->courseid]) && groups_is_member($event->groupid);
2203 } else if ($event->modulename) {
2204 // If this is a module event we need to be able to see the module.
2205 $coursemodules = [];
2206 $courseid = 0;
2207 // Override events do not have the courseid set.
2208 if ($event->courseid) {
2209 $courseid = $event->courseid;
2210 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2211 } else {
2212 $cmraw = get_coursemodule_from_instance($event->modulename, $event->instance, 0, false, MUST_EXIST);
2213 $courseid = $cmraw->course;
2214 $coursemodules = get_fast_modinfo($cmraw->course)->instances;
2216 $hasmodule = isset($coursemodules[$event->modulename]);
2217 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2219 // If modinfo doesn't know about the module, return false to be safe.
2220 if (!$hasmodule || !$hasinstance) {
2221 return false;
2224 // Must be able to see the course and the module - MDL-59304.
2225 $cm = $coursemodules[$event->modulename][$event->instance];
2226 if (!$cm->uservisible) {
2227 return false;
2229 $mycourses = enrol_get_my_courses('id');
2230 return isset($mycourses[$courseid]);
2231 } else if ($event->categoryid) {
2232 // If this is a category we need to be able to see the category.
2233 $cat = \core_course_category::get($event->categoryid, IGNORE_MISSING);
2234 if (!$cat) {
2235 return false;
2237 return true;
2238 } else if (!empty($event->courseid)) {
2239 // If it is a course event we need to be able to manage events in the course, or be in the course.
2240 if (has_capability('moodle/calendar:manageentries', $event->context)) {
2241 return true;
2244 return can_access_course(get_course($event->courseid));
2245 } else if ($event->userid) {
2246 if ($event->userid != $USER->id) {
2247 // No-one can ever see another users events.
2248 return false;
2250 return true;
2251 } else {
2252 throw new moodle_exception('unknown event type');
2255 return false;
2259 * Return the capability for editing calendar event.
2261 * @param calendar_event $event event object
2262 * @param bool $manualedit is the event being edited manually by the user
2263 * @return bool capability to edit event
2265 function calendar_edit_event_allowed($event, $manualedit = false) {
2266 global $USER, $DB;
2268 // Must be logged in.
2269 if (!isloggedin()) {
2270 return false;
2273 // Can not be using guest account.
2274 if (isguestuser()) {
2275 return false;
2278 if ($manualedit && !empty($event->modulename)) {
2279 $hascallback = component_callback_exists(
2280 'mod_' . $event->modulename,
2281 'core_calendar_event_timestart_updated'
2284 if (!$hascallback) {
2285 // If the activity hasn't implemented the correct callback
2286 // to handle changes to it's events then don't allow any
2287 // manual changes to them.
2288 return false;
2291 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2292 $hasmodule = isset($coursemodules[$event->modulename]);
2293 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2295 // If modinfo doesn't know about the module, return false to be safe.
2296 if (!$hasmodule || !$hasinstance) {
2297 return false;
2300 $coursemodule = $coursemodules[$event->modulename][$event->instance];
2301 $context = context_module::instance($coursemodule->id);
2302 // This is the capability that allows a user to modify the activity
2303 // settings. Since the activity generated this event we need to check
2304 // that the current user has the same capability before allowing them
2305 // to update the event because the changes to the event will be
2306 // reflected within the activity.
2307 return has_capability('moodle/course:manageactivities', $context);
2310 if ($manualedit && !empty($event->component)) {
2311 // TODO possibly we can later add a callback similar to core_calendar_event_timestart_updated in the modules.
2312 return false;
2315 // You cannot edit URL based calendar subscription events presently.
2316 if (!empty($event->subscriptionid)) {
2317 if (!empty($event->subscription->url)) {
2318 // This event can be updated externally, so it cannot be edited.
2319 return false;
2323 $sitecontext = \context_system::instance();
2325 // If user has manageentries at site level, return true.
2326 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2327 return true;
2330 // If groupid is set, it's definitely a group event.
2331 if (!empty($event->groupid)) {
2332 // Allow users to add/edit group events if -
2333 // 1) They have manageentries for the course OR
2334 // 2) They have managegroupentries AND are in the group.
2335 $group = $DB->get_record('groups', array('id' => $event->groupid));
2336 return $group && (
2337 has_capability('moodle/calendar:manageentries', $event->context) ||
2338 (has_capability('moodle/calendar:managegroupentries', $event->context)
2339 && groups_is_member($event->groupid)));
2340 } else if (!empty($event->courseid)) {
2341 // If groupid is not set, but course is set, it's definitely a course event.
2342 return has_capability('moodle/calendar:manageentries', $event->context);
2343 } else if (!empty($event->categoryid)) {
2344 // If groupid is not set, but category is set, it's definitely a category event.
2345 return has_capability('moodle/calendar:manageentries', $event->context);
2346 } else if (!empty($event->userid) && $event->userid == $USER->id) {
2347 // If course is not set, but userid id set, it's a user event.
2348 return (has_capability('moodle/calendar:manageownentries', $event->context));
2349 } else if (!empty($event->userid)) {
2350 return (has_capability('moodle/calendar:manageentries', $event->context));
2353 return false;
2357 * Return the capability for deleting a calendar event.
2359 * @param calendar_event $event The event object
2360 * @return bool Whether the user has permission to delete the event or not.
2362 function calendar_delete_event_allowed($event) {
2363 // Only allow delete if you have capabilities and it is not an module or component event.
2364 return (calendar_edit_event_allowed($event) && empty($event->modulename) && empty($event->component));
2368 * Returns the default courses to display on the calendar when there isn't a specific
2369 * course to display.
2371 * @param int $courseid (optional) If passed, an additional course can be returned for admins (the current course).
2372 * @param string $fields Comma separated list of course fields to return.
2373 * @param bool $canmanage If true, this will return the list of courses the user can create events in, rather
2374 * than the list of courses they see events from (an admin can always add events in a course
2375 * calendar, even if they are not enrolled in the course).
2376 * @param int $userid (optional) The user which this function returns the default courses for.
2377 * By default the current user.
2378 * @return array $courses Array of courses to display
2380 function calendar_get_default_courses($courseid = null, $fields = '*', $canmanage = false, int $userid = null) {
2381 global $CFG, $USER;
2383 if (!$userid) {
2384 if (!isloggedin()) {
2385 return array();
2387 $userid = $USER->id;
2390 if ((!empty($CFG->calendar_adminseesall) || $canmanage) &&
2391 has_capability('moodle/calendar:manageentries', context_system::instance(), $userid)) {
2393 // Add a c. prefix to every field as expected by get_courses function.
2394 $fieldlist = explode(',', $fields);
2396 $prefixedfields = array_map(function($value) {
2397 return 'c.' . trim(strtolower($value));
2398 }, $fieldlist);
2399 if (!in_array('c.visible', $prefixedfields) && !in_array('c.*', $prefixedfields)) {
2400 $prefixedfields[] = 'c.visible';
2402 $courses = get_courses('all', 'c.shortname', implode(',', $prefixedfields));
2403 } else {
2404 $courses = enrol_get_users_courses($userid, true, $fields);
2407 if ($courseid && $courseid != SITEID) {
2408 if (empty($courses[$courseid]) && has_capability('moodle/calendar:manageentries', context_system::instance(), $userid)) {
2409 // Allow a site admin to see calendars from courses he is not enrolled in.
2410 // This will come from $COURSE.
2411 $courses[$courseid] = get_course($courseid);
2415 return $courses;
2419 * Get event format time.
2421 * @param calendar_event $event event object
2422 * @param int $now current time in gmt
2423 * @param array $linkparams list of params for event link
2424 * @param bool $usecommonwords the words as formatted date/time.
2425 * @param int $showtime determine the show time GMT timestamp
2426 * @return string $eventtime link/string for event time
2428 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
2429 $starttime = $event->timestart;
2430 $endtime = $event->timestart + $event->timeduration;
2432 if (empty($linkparams) || !is_array($linkparams)) {
2433 $linkparams = array();
2436 $linkparams['view'] = 'day';
2438 // OK, now to get a meaningful display.
2439 // Check if there is a duration for this event.
2440 if ($event->timeduration) {
2441 // Get the midnight of the day the event will start.
2442 $usermidnightstart = usergetmidnight($starttime);
2443 // Get the midnight of the day the event will end.
2444 $usermidnightend = usergetmidnight($endtime);
2445 // Check if we will still be on the same day.
2446 if ($usermidnightstart == $usermidnightend) {
2447 // Check if we are running all day.
2448 if ($event->timeduration == DAYSECS) {
2449 $time = get_string('allday', 'calendar');
2450 } else { // Specify the time we will be running this from.
2451 $datestart = calendar_time_representation($starttime);
2452 $dateend = calendar_time_representation($endtime);
2453 $time = $datestart . ' <strong>&raquo;</strong> ' . $dateend;
2456 // Set printable representation.
2457 if (!$showtime) {
2458 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2459 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2460 $eventtime = \html_writer::link($url, $day) . ', ' . $time;
2461 } else {
2462 $eventtime = $time;
2464 } else { // It must spans two or more days.
2465 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
2466 if ($showtime == $usermidnightstart) {
2467 $daystart = '';
2469 $timestart = calendar_time_representation($event->timestart);
2470 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
2471 if ($showtime == $usermidnightend) {
2472 $dayend = '';
2474 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
2476 // Set printable representation.
2477 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2478 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2479 $eventtime = $timestart . ' <strong>&raquo;</strong> ' . \html_writer::link($url, $dayend) . $timeend;
2480 } else {
2481 // The event is in the future, print start and end links.
2482 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2483 $eventtime = \html_writer::link($url, $daystart) . $timestart . ' <strong>&raquo;</strong> ';
2485 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2486 $eventtime .= \html_writer::link($url, $dayend) . $timeend;
2489 } else { // There is no time duration.
2490 $time = calendar_time_representation($event->timestart);
2491 // Set printable representation.
2492 if (!$showtime) {
2493 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2494 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2495 $eventtime = \html_writer::link($url, $day) . ', ' . trim($time);
2496 } else {
2497 $eventtime = $time;
2501 // Check if It has expired.
2502 if ($event->timestart + $event->timeduration < $now) {
2503 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2506 return $eventtime;
2510 * Checks to see if the requested type of event should be shown for the given user.
2512 * @param int $type The type to check the display for (default is to display all)
2513 * @param stdClass|int|null $user The user to check for - by default the current user
2514 * @return bool True if the tyep should be displayed false otherwise
2516 function calendar_show_event_type($type, $user = null) {
2517 $default = CALENDAR_EVENT_SITE + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
2519 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2520 global $SESSION;
2521 if (!isset($SESSION->calendarshoweventtype)) {
2522 $SESSION->calendarshoweventtype = $default;
2524 return $SESSION->calendarshoweventtype & $type;
2525 } else {
2526 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2531 * Sets the display of the event type given $display.
2533 * If $display = true the event type will be shown.
2534 * If $display = false the event type will NOT be shown.
2535 * If $display = null the current value will be toggled and saved.
2537 * @param int $type object of CALENDAR_EVENT_XXX
2538 * @param bool $display option to display event type
2539 * @param stdClass|int $user moodle user object or id, null means current user
2541 function calendar_set_event_type_display($type, $display = null, $user = null) {
2542 $persist = get_user_preferences('calendar_persistflt', 0, $user);
2543 $default = CALENDAR_EVENT_SITE + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP
2544 + CALENDAR_EVENT_USER + CALENDAR_EVENT_COURSECAT;
2545 if ($persist === 0) {
2546 global $SESSION;
2547 if (!isset($SESSION->calendarshoweventtype)) {
2548 $SESSION->calendarshoweventtype = $default;
2550 $preference = $SESSION->calendarshoweventtype;
2551 } else {
2552 $preference = get_user_preferences('calendar_savedflt', $default, $user);
2554 $current = $preference & $type;
2555 if ($display === null) {
2556 $display = !$current;
2558 if ($display && !$current) {
2559 $preference += $type;
2560 } else if (!$display && $current) {
2561 $preference -= $type;
2563 if ($persist === 0) {
2564 $SESSION->calendarshoweventtype = $preference;
2565 } else {
2566 if ($preference == $default) {
2567 unset_user_preference('calendar_savedflt', $user);
2568 } else {
2569 set_user_preference('calendar_savedflt', $preference, $user);
2575 * Get calendar's allowed types.
2577 * @param stdClass $allowed list of allowed edit for event type
2578 * @param stdClass|int $course object of a course or course id
2579 * @param array $groups array of groups for the given course
2580 * @param stdClass|int $category object of a category
2582 function calendar_get_allowed_types(&$allowed, $course = null, $groups = null, $category = null) {
2583 global $USER, $DB;
2585 $allowed = new \stdClass();
2586 $allowed->user = has_capability('moodle/calendar:manageownentries', \context_system::instance());
2587 $allowed->groups = false;
2588 $allowed->courses = false;
2589 $allowed->categories = false;
2590 $allowed->site = has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID));
2591 $getgroupsfunc = function($course, $context, $user) use ($groups) {
2592 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2593 if (has_capability('moodle/site:accessallgroups', $context)) {
2594 return is_null($groups) ? groups_get_all_groups($course->id) : $groups;
2595 } else {
2596 if (is_null($groups)) {
2597 return groups_get_all_groups($course->id, $user->id);
2598 } else {
2599 return array_filter($groups, function($group) use ($user) {
2600 return isset($group->members[$user->id]);
2606 return false;
2609 if (!empty($course)) {
2610 if (!is_object($course)) {
2611 $course = $DB->get_record('course', array('id' => $course), 'id, groupmode, groupmodeforce', MUST_EXIST);
2613 if ($course->id != SITEID) {
2614 $coursecontext = \context_course::instance($course->id);
2615 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
2617 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2618 $allowed->courses = array($course->id => 1);
2619 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2620 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
2621 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2626 if (!empty($category)) {
2627 $catcontext = \context_coursecat::instance($category->id);
2628 if (has_capability('moodle/category:manage', $catcontext)) {
2629 $allowed->categories = [$category->id => 1];
2635 * See if user can add calendar entries at all used to print the "New Event" button.
2637 * @param stdClass $course object of a course or course id
2638 * @return bool has the capability to add at least one event type
2640 function calendar_user_can_add_event($course) {
2641 if (!isloggedin() || isguestuser()) {
2642 return false;
2645 calendar_get_allowed_types($allowed, $course);
2647 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->categories || $allowed->site);
2651 * Check wether the current user is permitted to add events.
2653 * @param stdClass $event object of event
2654 * @return bool has the capability to add event
2656 function calendar_add_event_allowed($event) {
2657 global $USER, $DB;
2659 // Can not be using guest account.
2660 if (!isloggedin() or isguestuser()) {
2661 return false;
2664 $sitecontext = \context_system::instance();
2666 // If user has manageentries at site level, always return true.
2667 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2668 return true;
2671 switch ($event->eventtype) {
2672 case 'category':
2673 return has_capability('moodle/category:manage', $event->context);
2674 case 'course':
2675 return has_capability('moodle/calendar:manageentries', $event->context);
2676 case 'group':
2677 // Allow users to add/edit group events if -
2678 // 1) They have manageentries (= entries for whole course).
2679 // 2) They have managegroupentries AND are in the group.
2680 $group = $DB->get_record('groups', array('id' => $event->groupid));
2681 return $group && (
2682 has_capability('moodle/calendar:manageentries', $event->context) ||
2683 (has_capability('moodle/calendar:managegroupentries', $event->context)
2684 && groups_is_member($event->groupid)));
2685 case 'user':
2686 if ($event->userid == $USER->id) {
2687 return (has_capability('moodle/calendar:manageownentries', $event->context));
2689 // There is intentionally no 'break'.
2690 case 'site':
2691 return has_capability('moodle/calendar:manageentries', $event->context);
2692 default:
2693 return has_capability('moodle/calendar:manageentries', $event->context);
2698 * Returns option list for the poll interval setting.
2700 * @return array An array of poll interval options. Interval => description.
2702 function calendar_get_pollinterval_choices() {
2703 return array(
2704 '0' => new \lang_string('never', 'calendar'),
2705 HOURSECS => new \lang_string('hourly', 'calendar'),
2706 DAYSECS => new \lang_string('daily', 'calendar'),
2707 WEEKSECS => new \lang_string('weekly', 'calendar'),
2708 '2628000' => new \lang_string('monthly', 'calendar'),
2709 YEARSECS => new \lang_string('annually', 'calendar')
2714 * Returns option list of available options for the calendar event type, given the current user and course.
2716 * @param int $courseid The id of the course
2717 * @return array An array containing the event types the user can create.
2719 function calendar_get_eventtype_choices($courseid) {
2720 $choices = array();
2721 $allowed = new \stdClass;
2722 calendar_get_allowed_types($allowed, $courseid);
2724 if ($allowed->user) {
2725 $choices['user'] = get_string('userevents', 'calendar');
2727 if ($allowed->site) {
2728 $choices['site'] = get_string('siteevents', 'calendar');
2730 if (!empty($allowed->courses)) {
2731 $choices['course'] = get_string('courseevents', 'calendar');
2733 if (!empty($allowed->categories)) {
2734 $choices['category'] = get_string('categoryevents', 'calendar');
2736 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2737 $choices['group'] = get_string('group');
2740 return array($choices, $allowed->groups);
2744 * Add an iCalendar subscription to the database.
2746 * @param stdClass $sub The subscription object (e.g. from the form)
2747 * @return int The insert ID, if any.
2749 function calendar_add_subscription($sub) {
2750 global $DB, $USER, $SITE;
2752 // Undo the form definition work around to allow us to have two different
2753 // course selectors present depending on which event type the user selects.
2754 if (!empty($sub->groupcourseid)) {
2755 $sub->courseid = $sub->groupcourseid;
2756 unset($sub->groupcourseid);
2759 // Default course id if none is set.
2760 if (empty($sub->courseid)) {
2761 if ($sub->eventtype === 'site') {
2762 $sub->courseid = SITEID;
2763 } else {
2764 $sub->courseid = 0;
2768 if ($sub->eventtype === 'site') {
2769 $sub->courseid = $SITE->id;
2770 } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
2771 $sub->courseid = $sub->courseid;
2772 } else if ($sub->eventtype === 'category') {
2773 $sub->categoryid = $sub->categoryid;
2774 } else {
2775 // User events.
2776 $sub->courseid = 0;
2778 $sub->userid = $USER->id;
2780 // File subscriptions never update.
2781 if (empty($sub->url)) {
2782 $sub->pollinterval = 0;
2785 if (!empty($sub->name)) {
2786 if (empty($sub->id)) {
2787 $id = $DB->insert_record('event_subscriptions', $sub);
2788 // We cannot cache the data here because $sub is not complete.
2789 $sub->id = $id;
2790 // Trigger event, calendar subscription added.
2791 $eventparams = array('objectid' => $sub->id,
2792 'context' => calendar_get_calendar_context($sub),
2793 'other' => array(
2794 'eventtype' => $sub->eventtype,
2797 switch ($sub->eventtype) {
2798 case 'category':
2799 $eventparams['other']['categoryid'] = $sub->categoryid;
2800 break;
2801 case 'course':
2802 $eventparams['other']['courseid'] = $sub->courseid;
2803 break;
2804 case 'group':
2805 $eventparams['other']['courseid'] = $sub->courseid;
2806 $eventparams['other']['groupid'] = $sub->groupid;
2807 break;
2808 default:
2809 $eventparams['other']['courseid'] = $sub->courseid;
2812 $event = \core\event\calendar_subscription_created::create($eventparams);
2813 $event->trigger();
2814 return $id;
2815 } else {
2816 // Why are we doing an update here?
2817 calendar_update_subscription($sub);
2818 return $sub->id;
2820 } else {
2821 print_error('errorbadsubscription', 'importcalendar');
2826 * Add an iCalendar event to the Moodle calendar.
2828 * @param stdClass $event The RFC-2445 iCalendar event
2829 * @param int $unused Deprecated
2830 * @param int $subscriptionid The iCalendar subscription ID
2831 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2832 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2833 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2835 function calendar_add_icalendar_event($event, $unused = null, $subscriptionid, $timezone='UTC') {
2836 global $DB;
2838 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2839 if (empty($event->properties['SUMMARY'])) {
2840 return 0;
2843 $name = $event->properties['SUMMARY'][0]->value;
2844 $name = str_replace('\n', '<br />', $name);
2845 $name = str_replace('\\', '', $name);
2846 $name = preg_replace('/\s+/u', ' ', $name);
2848 $eventrecord = new \stdClass;
2849 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
2851 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2852 $description = '';
2853 } else {
2854 $description = $event->properties['DESCRIPTION'][0]->value;
2855 $description = clean_param($description, PARAM_NOTAGS);
2856 $description = str_replace('\n', '<br />', $description);
2857 $description = str_replace('\\', '', $description);
2858 $description = preg_replace('/\s+/u', ' ', $description);
2860 $eventrecord->description = $description;
2862 // Probably a repeating event with RRULE etc. TODO: skip for now.
2863 if (empty($event->properties['DTSTART'][0]->value)) {
2864 return 0;
2867 if (isset($event->properties['DTSTART'][0]->parameters['TZID'])) {
2868 $tz = $event->properties['DTSTART'][0]->parameters['TZID'];
2869 } else {
2870 $tz = $timezone;
2872 $tz = \core_date::normalise_timezone($tz);
2873 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value . ' ' . $tz);
2874 if (empty($event->properties['DTEND'])) {
2875 $eventrecord->timeduration = 0; // No duration if no end time specified.
2876 } else {
2877 if (isset($event->properties['DTEND'][0]->parameters['TZID'])) {
2878 $endtz = $event->properties['DTEND'][0]->parameters['TZID'];
2879 } else {
2880 $endtz = $timezone;
2882 $endtz = \core_date::normalise_timezone($endtz);
2883 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value . ' ' . $endtz) - $eventrecord->timestart;
2886 // Check to see if it should be treated as an all day event.
2887 if ($eventrecord->timeduration == DAYSECS) {
2888 // Check to see if the event started at Midnight on the imported calendar.
2889 date_default_timezone_set($timezone);
2890 if (date('H:i:s', $eventrecord->timestart) === "00:00:00") {
2891 // This event should be an all day event. This is not correct, we don't do anything differently for all day events.
2892 // See MDL-56227.
2893 $eventrecord->timeduration = 0;
2895 \core_date::set_default_server_timezone();
2898 $eventrecord->location = empty($event->properties['LOCATION'][0]->value) ? '' :
2899 trim(str_replace('\\', '', $event->properties['LOCATION'][0]->value));
2900 $eventrecord->uuid = $event->properties['UID'][0]->value;
2901 $eventrecord->timemodified = time();
2903 // Add the iCal subscription details if required.
2904 // We should never do anything with an event without a subscription reference.
2905 $sub = calendar_get_subscription($subscriptionid);
2906 $eventrecord->subscriptionid = $subscriptionid;
2907 $eventrecord->userid = $sub->userid;
2908 $eventrecord->groupid = $sub->groupid;
2909 $eventrecord->courseid = $sub->courseid;
2910 $eventrecord->categoryid = $sub->categoryid;
2911 $eventrecord->eventtype = $sub->eventtype;
2913 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid,
2914 'subscriptionid' => $eventrecord->subscriptionid))) {
2916 // Compare iCal event data against the moodle event to see if something has changed.
2917 $result = array_diff((array) $eventrecord, (array) $updaterecord);
2919 // Unset timemodified field because it's always going to be different.
2920 unset($result['timemodified']);
2922 if (count($result)) {
2923 $eventrecord->id = $updaterecord->id;
2924 $return = CALENDAR_IMPORT_EVENT_UPDATED; // Update.
2925 } else {
2926 return CALENDAR_IMPORT_EVENT_SKIPPED;
2928 } else {
2929 $return = CALENDAR_IMPORT_EVENT_INSERTED; // Insert.
2932 if ($createdevent = \calendar_event::create($eventrecord, false)) {
2933 if (!empty($event->properties['RRULE'])) {
2934 // Repeating events.
2935 date_default_timezone_set($tz); // Change time zone to parse all events.
2936 $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
2937 $rrule->parse_rrule();
2938 $rrule->create_events($createdevent);
2939 \core_date::set_default_server_timezone(); // Change time zone back to what it was.
2941 return $return;
2942 } else {
2943 return 0;
2948 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2950 * @param int $subscriptionid The ID of the subscription we are acting upon.
2951 * @param int $pollinterval The poll interval to use.
2952 * @param int $action The action to be performed. One of update or remove.
2953 * @throws dml_exception if invalid subscriptionid is provided
2954 * @return string A log of the import progress, including errors
2956 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2957 // Fetch the subscription from the database making sure it exists.
2958 $sub = calendar_get_subscription($subscriptionid);
2960 // Update or remove the subscription, based on action.
2961 switch ($action) {
2962 case CALENDAR_SUBSCRIPTION_UPDATE:
2963 // Skip updating file subscriptions.
2964 if (empty($sub->url)) {
2965 break;
2967 $sub->pollinterval = $pollinterval;
2968 calendar_update_subscription($sub);
2970 // Update the events.
2971 return "<p>" . get_string('subscriptionupdated', 'calendar', $sub->name) . "</p>" .
2972 calendar_update_subscription_events($subscriptionid);
2973 case CALENDAR_SUBSCRIPTION_REMOVE:
2974 calendar_delete_subscription($subscriptionid);
2975 return get_string('subscriptionremoved', 'calendar', $sub->name);
2976 break;
2977 default:
2978 break;
2980 return '';
2984 * Delete subscription and all related events.
2986 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
2988 function calendar_delete_subscription($subscription) {
2989 global $DB;
2991 if (!is_object($subscription)) {
2992 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST);
2995 // Delete subscription and related events.
2996 $DB->delete_records('event', array('subscriptionid' => $subscription->id));
2997 $DB->delete_records('event_subscriptions', array('id' => $subscription->id));
2998 \cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id));
3000 // Trigger event, calendar subscription deleted.
3001 $eventparams = array('objectid' => $subscription->id,
3002 'context' => calendar_get_calendar_context($subscription),
3003 'other' => array(
3004 'eventtype' => $subscription->eventtype,
3007 switch ($subscription->eventtype) {
3008 case 'category':
3009 $eventparams['other']['categoryid'] = $subscription->categoryid;
3010 break;
3011 case 'course':
3012 $eventparams['other']['courseid'] = $subscription->courseid;
3013 break;
3014 case 'group':
3015 $eventparams['other']['courseid'] = $subscription->courseid;
3016 $eventparams['other']['groupid'] = $subscription->groupid;
3017 break;
3018 default:
3019 $eventparams['other']['courseid'] = $subscription->courseid;
3021 $event = \core\event\calendar_subscription_deleted::create($eventparams);
3022 $event->trigger();
3026 * From a URL, fetch the calendar and return an iCalendar object.
3028 * @param string $url The iCalendar URL
3029 * @return iCalendar The iCalendar object
3031 function calendar_get_icalendar($url) {
3032 global $CFG;
3034 require_once($CFG->libdir . '/filelib.php');
3036 $curl = new \curl();
3037 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
3038 $calendar = $curl->get($url);
3040 // Http code validation should actually be the job of curl class.
3041 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
3042 throw new \moodle_exception('errorinvalidicalurl', 'calendar');
3045 $ical = new \iCalendar();
3046 $ical->unserialize($calendar);
3048 return $ical;
3052 * Import events from an iCalendar object into a course calendar.
3054 * @param iCalendar $ical The iCalendar object.
3055 * @param int $unused Deprecated
3056 * @param int $subscriptionid The subscription ID.
3057 * @return string A log of the import progress, including errors.
3059 function calendar_import_icalendar_events($ical, $unused = null, $subscriptionid = null) {
3060 global $DB;
3062 $return = '';
3063 $eventcount = 0;
3064 $updatecount = 0;
3065 $skippedcount = 0;
3067 // Large calendars take a while...
3068 if (!CLI_SCRIPT) {
3069 \core_php_time_limit::raise(300);
3072 // Grab the timezone from the iCalendar file to be used later.
3073 if (isset($ical->properties['X-WR-TIMEZONE'][0]->value)) {
3074 $timezone = $ical->properties['X-WR-TIMEZONE'][0]->value;
3075 } else {
3076 $timezone = 'UTC';
3079 $icaluuids = [];
3080 foreach ($ical->components['VEVENT'] as $event) {
3081 $icaluuids[] = $event->properties['UID'][0]->value;
3082 $res = calendar_add_icalendar_event($event, null, $subscriptionid, $timezone);
3083 switch ($res) {
3084 case CALENDAR_IMPORT_EVENT_UPDATED:
3085 $updatecount++;
3086 break;
3087 case CALENDAR_IMPORT_EVENT_INSERTED:
3088 $eventcount++;
3089 break;
3090 case CALENDAR_IMPORT_EVENT_SKIPPED:
3091 $skippedcount++;
3092 break;
3093 case 0:
3094 $return .= '<p>' . get_string('erroraddingevent', 'calendar') . ': ';
3095 if (empty($event->properties['SUMMARY'])) {
3096 $return .= '(' . get_string('notitle', 'calendar') . ')';
3097 } else {
3098 $return .= $event->properties['SUMMARY'][0]->value;
3100 $return .= "</p>\n";
3101 break;
3105 $existing = $DB->get_field('event_subscriptions', 'lastupdated', ['id' => $subscriptionid]);
3106 if (!empty($existing)) {
3107 $eventsuuids = $DB->get_records_menu('event', ['subscriptionid' => $subscriptionid], '', 'id, uuid');
3109 $icaleventscount = count($icaluuids);
3110 $tobedeleted = [];
3111 if (count($eventsuuids) > $icaleventscount) {
3112 foreach ($eventsuuids as $eventid => $eventuuid) {
3113 if (!in_array($eventuuid, $icaluuids)) {
3114 $tobedeleted[] = $eventid;
3117 if (!empty($tobedeleted)) {
3118 $DB->delete_records_list('event', 'id', $tobedeleted);
3119 $return .= "<p> " . get_string('eventsdeleted', 'calendar') . ": " . count($tobedeleted) . "</p> ";
3124 $return .= "<p>" . get_string('eventsimported', 'calendar', $eventcount) . "</p> ";
3125 $return .= "<p>" . get_string('eventsskipped', 'calendar', $skippedcount) . "</p> ";
3126 $return .= "<p>" . get_string('eventsupdated', 'calendar', $updatecount) . "</p>";
3127 return $return;
3131 * Fetch a calendar subscription and update the events in the calendar.
3133 * @param int $subscriptionid The course ID for the calendar.
3134 * @return string A log of the import progress, including errors.
3136 function calendar_update_subscription_events($subscriptionid) {
3137 $sub = calendar_get_subscription($subscriptionid);
3139 // Don't update a file subscription.
3140 if (empty($sub->url)) {
3141 return 'File subscription not updated.';
3144 $ical = calendar_get_icalendar($sub->url);
3145 $return = calendar_import_icalendar_events($ical, null, $subscriptionid);
3146 $sub->lastupdated = time();
3148 calendar_update_subscription($sub);
3150 return $return;
3154 * Update a calendar subscription. Also updates the associated cache.
3156 * @param stdClass|array $subscription Subscription record.
3157 * @throws coding_exception If something goes wrong
3158 * @since Moodle 2.5
3160 function calendar_update_subscription($subscription) {
3161 global $DB;
3163 if (is_array($subscription)) {
3164 $subscription = (object)$subscription;
3166 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
3167 throw new \coding_exception('Cannot update a subscription without a valid id');
3170 $DB->update_record('event_subscriptions', $subscription);
3172 // Update cache.
3173 $cache = \cache::make('core', 'calendar_subscriptions');
3174 $cache->set($subscription->id, $subscription);
3176 // Trigger event, calendar subscription updated.
3177 $eventparams = array('userid' => $subscription->userid,
3178 'objectid' => $subscription->id,
3179 'context' => calendar_get_calendar_context($subscription),
3180 'other' => array(
3181 'eventtype' => $subscription->eventtype,
3184 switch ($subscription->eventtype) {
3185 case 'category':
3186 $eventparams['other']['categoryid'] = $subscription->categoryid;
3187 break;
3188 case 'course':
3189 $eventparams['other']['courseid'] = $subscription->courseid;
3190 break;
3191 case 'group':
3192 $eventparams['other']['courseid'] = $subscription->courseid;
3193 $eventparams['other']['groupid'] = $subscription->groupid;
3194 break;
3195 default:
3196 $eventparams['other']['courseid'] = $subscription->courseid;
3198 $event = \core\event\calendar_subscription_updated::create($eventparams);
3199 $event->trigger();
3203 * Checks to see if the user can edit a given subscription feed.
3205 * @param mixed $subscriptionorid Subscription object or id
3206 * @return bool true if current user can edit the subscription else false
3208 function calendar_can_edit_subscription($subscriptionorid) {
3209 if (is_array($subscriptionorid)) {
3210 $subscription = (object)$subscriptionorid;
3211 } else if (is_object($subscriptionorid)) {
3212 $subscription = $subscriptionorid;
3213 } else {
3214 $subscription = calendar_get_subscription($subscriptionorid);
3217 $allowed = new \stdClass;
3218 $courseid = $subscription->courseid;
3219 $categoryid = $subscription->categoryid;
3220 $groupid = $subscription->groupid;
3221 $category = null;
3223 if (!empty($categoryid)) {
3224 $category = \core_course_category::get($categoryid);
3226 calendar_get_allowed_types($allowed, $courseid, null, $category);
3227 switch ($subscription->eventtype) {
3228 case 'user':
3229 return $allowed->user;
3230 case 'course':
3231 if (isset($allowed->courses[$courseid])) {
3232 return $allowed->courses[$courseid];
3233 } else {
3234 return false;
3236 case 'category':
3237 if (isset($allowed->categories[$categoryid])) {
3238 return $allowed->categories[$categoryid];
3239 } else {
3240 return false;
3242 case 'site':
3243 return $allowed->site;
3244 case 'group':
3245 if (isset($allowed->groups[$groupid])) {
3246 return $allowed->groups[$groupid];
3247 } else {
3248 return false;
3250 default:
3251 return false;
3256 * Helper function to determine the context of a calendar subscription.
3257 * Subscriptions can be created in two contexts COURSE, or USER.
3259 * @param stdClass $subscription
3260 * @return context instance
3262 function calendar_get_calendar_context($subscription) {
3263 // Determine context based on calendar type.
3264 if ($subscription->eventtype === 'site') {
3265 $context = \context_course::instance(SITEID);
3266 } else if ($subscription->eventtype === 'group' || $subscription->eventtype === 'course') {
3267 $context = \context_course::instance($subscription->courseid);
3268 } else {
3269 $context = \context_user::instance($subscription->userid);
3271 return $context;
3275 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
3277 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3279 * @return array
3281 function core_calendar_user_preferences() {
3282 $preferences = [];
3283 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED, 'default' => '0',
3284 'choices' => array('0', CALENDAR_TF_12, CALENDAR_TF_24)
3286 $preferences['calendar_startwday'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3287 'choices' => array(0, 1, 2, 3, 4, 5, 6));
3288 $preferences['calendar_maxevents'] = array('type' => PARAM_INT, 'choices' => range(1, 20));
3289 $preferences['calendar_lookahead'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 365,
3290 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3291 $preferences['calendar_persistflt'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3292 'choices' => array(0, 1));
3293 return $preferences;
3297 * Get legacy calendar events
3299 * @param int $tstart Start time of time range for events
3300 * @param int $tend End time of time range for events
3301 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3302 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3303 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3304 * @param boolean $withduration whether only events starting within time range selected
3305 * or events in progress/already started selected as well
3306 * @param boolean $ignorehidden whether to select only visible events or all events
3307 * @param array $categories array of category ids and/or objects.
3308 * @param int $limitnum Number of events to fetch or zero to fetch all.
3310 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3312 function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses,
3313 $withduration = true, $ignorehidden = true, $categories = [], $limitnum = 0) {
3314 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3315 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3316 // parameters, but with the new API method, only null and arrays are accepted.
3317 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3318 // If parameter is true, return null.
3319 if ($param === true) {
3320 return null;
3323 // If parameter is false, return an empty array.
3324 if ($param === false) {
3325 return [];
3328 // If the parameter is a scalar value, enclose it in an array.
3329 if (!is_array($param)) {
3330 return [$param];
3333 // No normalisation required.
3334 return $param;
3335 }, [$users, $groups, $courses, $categories]);
3337 // If a single user is provided, we can use that for capability checks.
3338 // Otherwise current logged in user is used - See MDL-58768.
3339 if (is_array($userparam) && count($userparam) == 1) {
3340 \core_calendar\local\event\container::set_requesting_user($userparam[0]);
3342 $mapper = \core_calendar\local\event\container::get_event_mapper();
3343 $events = \core_calendar\local\api::get_events(
3344 $tstart,
3345 $tend,
3346 null,
3347 null,
3348 null,
3349 null,
3350 $limitnum,
3351 null,
3352 $userparam,
3353 $groupparam,
3354 $courseparam,
3355 $categoryparam,
3356 $withduration,
3357 $ignorehidden
3360 return array_reduce($events, function($carry, $event) use ($mapper) {
3361 return $carry + [$event->get_id() => $mapper->from_event_to_stdclass($event)];
3362 }, []);
3367 * Get the calendar view output.
3369 * @param \calendar_information $calendar The calendar being represented
3370 * @param string $view The type of calendar to have displayed
3371 * @param bool $includenavigation Whether to include navigation
3372 * @param bool $skipevents Whether to load the events or not
3373 * @param int $lookahead Overwrites site and users's lookahead setting.
3374 * @return array[array, string]
3376 function calendar_get_view(\calendar_information $calendar, $view, $includenavigation = true, bool $skipevents = false,
3377 ?int $lookahead = null) {
3378 global $PAGE, $CFG;
3380 $renderer = $PAGE->get_renderer('core_calendar');
3381 $type = \core_calendar\type_factory::get_calendar_instance();
3383 // Calculate the bounds of the month.
3384 $calendardate = $type->timestamp_to_date_array($calendar->time);
3386 $date = new \DateTime('now', core_date::get_user_timezone_object(99));
3387 $eventlimit = 0;
3389 if ($view === 'day') {
3390 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday']);
3391 $date->setTimestamp($tstart);
3392 $date->modify('+1 day');
3393 } else if ($view === 'upcoming' || $view === 'upcoming_mini') {
3394 // Number of days in the future that will be used to fetch events.
3395 if (!$lookahead) {
3396 if (isset($CFG->calendar_lookahead)) {
3397 $defaultlookahead = intval($CFG->calendar_lookahead);
3398 } else {
3399 $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD;
3401 $lookahead = get_user_preferences('calendar_lookahead', $defaultlookahead);
3404 // Maximum number of events to be displayed on upcoming view.
3405 $defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS;
3406 if (isset($CFG->calendar_maxevents)) {
3407 $defaultmaxevents = intval($CFG->calendar_maxevents);
3409 $eventlimit = get_user_preferences('calendar_maxevents', $defaultmaxevents);
3411 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday'],
3412 $calendardate['hours']);
3413 $date->setTimestamp($tstart);
3414 $date->modify('+' . $lookahead . ' days');
3415 } else {
3416 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], 1);
3417 $monthdays = $type->get_num_days_in_month($calendardate['year'], $calendardate['mon']);
3418 $date->setTimestamp($tstart);
3419 $date->modify('+' . $monthdays . ' days');
3421 if ($view === 'mini' || $view === 'minithree') {
3422 $template = 'core_calendar/calendar_mini';
3423 } else {
3424 $template = 'core_calendar/calendar_month';
3428 // We need to extract 1 second to ensure that we don't get into the next day.
3429 $date->modify('-1 second');
3430 $tend = $date->getTimestamp();
3432 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3433 // If parameter is true, return null.
3434 if ($param === true) {
3435 return null;
3438 // If parameter is false, return an empty array.
3439 if ($param === false) {
3440 return [];
3443 // If the parameter is a scalar value, enclose it in an array.
3444 if (!is_array($param)) {
3445 return [$param];
3448 // No normalisation required.
3449 return $param;
3450 }, [$calendar->users, $calendar->groups, $calendar->courses, $calendar->categories]);
3452 if ($skipevents) {
3453 $events = [];
3454 } else {
3455 $events = \core_calendar\local\api::get_events(
3456 $tstart,
3457 $tend,
3458 null,
3459 null,
3460 null,
3461 null,
3462 $eventlimit,
3463 null,
3464 $userparam,
3465 $groupparam,
3466 $courseparam,
3467 $categoryparam,
3468 true,
3469 true,
3470 function ($event) {
3471 if ($proxy = $event->get_course_module()) {
3472 $cminfo = $proxy->get_proxied_instance();
3473 return $cminfo->uservisible;
3476 if ($proxy = $event->get_category()) {
3477 $category = $proxy->get_proxied_instance();
3479 return $category->is_uservisible();
3482 return true;
3487 $related = [
3488 'events' => $events,
3489 'cache' => new \core_calendar\external\events_related_objects_cache($events),
3490 'type' => $type,
3493 $data = [];
3494 if ($view == "month" || $view == "mini" || $view == "minithree") {
3495 $month = new \core_calendar\external\month_exporter($calendar, $type, $related);
3496 $month->set_includenavigation($includenavigation);
3497 $month->set_initialeventsloaded(!$skipevents);
3498 $month->set_showcoursefilter($view == "month");
3499 $data = $month->export($renderer);
3500 $data->viewingmonth = true;
3501 } else if ($view == "day") {
3502 $day = new \core_calendar\external\calendar_day_exporter($calendar, $related);
3503 $data = $day->export($renderer);
3504 $data->viewingday = true;
3505 $template = 'core_calendar/calendar_day';
3506 } else if ($view == "upcoming" || $view == "upcoming_mini") {
3507 $upcoming = new \core_calendar\external\calendar_upcoming_exporter($calendar, $related);
3508 $data = $upcoming->export($renderer);
3510 if ($view == "upcoming") {
3511 $template = 'core_calendar/calendar_upcoming';
3512 $data->viewingupcoming = true;
3513 } else if ($view == "upcoming_mini") {
3514 $template = 'core_calendar/calendar_upcoming_mini';
3518 return [$data, $template];
3522 * Request and render event form fragment.
3524 * @param array $args The fragment arguments.
3525 * @return string The rendered mform fragment.
3527 function calendar_output_fragment_event_form($args) {
3528 global $CFG, $OUTPUT, $USER;
3529 require_once($CFG->libdir . '/grouplib.php');
3530 $html = '';
3531 $data = [];
3532 $eventid = isset($args['eventid']) ? clean_param($args['eventid'], PARAM_INT) : null;
3533 $starttime = isset($args['starttime']) ? clean_param($args['starttime'], PARAM_INT) : null;
3534 $courseid = (isset($args['courseid']) && $args['courseid'] != SITEID) ? clean_param($args['courseid'], PARAM_INT) : null;
3535 $categoryid = isset($args['categoryid']) ? clean_param($args['categoryid'], PARAM_INT) : null;
3536 $event = null;
3537 $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
3538 $context = \context_user::instance($USER->id);
3539 $editoroptions = \core_calendar\local\event\forms\create::build_editor_options($context);
3540 $formoptions = ['editoroptions' => $editoroptions, 'courseid' => $courseid];
3541 $draftitemid = 0;
3543 if ($hasformdata) {
3544 parse_str(clean_param($args['formdata'], PARAM_TEXT), $data);
3545 if (isset($data['description']['itemid'])) {
3546 $draftitemid = $data['description']['itemid'];
3550 if ($starttime) {
3551 $formoptions['starttime'] = $starttime;
3553 // Let's check first which event types user can add.
3554 $eventtypes = calendar_get_allowed_event_types($courseid);
3555 $formoptions['eventtypes'] = $eventtypes;
3557 if (is_null($eventid)) {
3558 if (!empty($courseid)) {
3559 $groupcoursedata = groups_get_course_data($courseid);
3560 $formoptions['groups'] = [];
3561 foreach ($groupcoursedata->groups as $groupid => $groupdata) {
3562 $formoptions['groups'][$groupid] = $groupdata->name;
3566 $mform = new \core_calendar\local\event\forms\create(
3567 null,
3568 $formoptions,
3569 'post',
3571 null,
3572 true,
3573 $data
3576 // If the user is on course context and is allowed to add course events set the event type default to course.
3577 if (!empty($courseid) && !empty($eventtypes['course'])) {
3578 $data['eventtype'] = 'course';
3579 $data['courseid'] = $courseid;
3580 $data['groupcourseid'] = $courseid;
3581 } else if (!empty($categoryid) && !empty($eventtypes['category'])) {
3582 $data['eventtype'] = 'category';
3583 $data['categoryid'] = $categoryid;
3584 } else if (!empty($groupcoursedata) && !empty($eventtypes['group'])) {
3585 $data['groupcourseid'] = $courseid;
3586 $data['groups'] = $groupcoursedata->groups;
3588 $mform->set_data($data);
3589 } else {
3590 $event = calendar_event::load($eventid);
3592 if (!calendar_edit_event_allowed($event)) {
3593 print_error('nopermissiontoupdatecalendar');
3596 $mapper = new \core_calendar\local\event\mappers\create_update_form_mapper();
3597 $eventdata = $mapper->from_legacy_event_to_data($event);
3598 $data = array_merge((array) $eventdata, $data);
3599 $event->count_repeats();
3600 $formoptions['event'] = $event;
3602 if (!empty($event->courseid)) {
3603 $groupcoursedata = groups_get_course_data($event->courseid);
3604 $formoptions['groups'] = [];
3605 foreach ($groupcoursedata->groups as $groupid => $groupdata) {
3606 $formoptions['groups'][$groupid] = $groupdata->name;
3610 $data['description']['text'] = file_prepare_draft_area(
3611 $draftitemid,
3612 $event->context->id,
3613 'calendar',
3614 'event_description',
3615 $event->id,
3616 null,
3617 $data['description']['text']
3619 $data['description']['itemid'] = $draftitemid;
3621 $mform = new \core_calendar\local\event\forms\update(
3622 null,
3623 $formoptions,
3624 'post',
3626 null,
3627 true,
3628 $data
3630 $mform->set_data($data);
3632 // Check to see if this event is part of a subscription or import.
3633 // If so display a warning on edit.
3634 if (isset($event->subscriptionid) && ($event->subscriptionid != null)) {
3635 $renderable = new \core\output\notification(
3636 get_string('eventsubscriptioneditwarning', 'calendar'),
3637 \core\output\notification::NOTIFY_INFO
3640 $html .= $OUTPUT->render($renderable);
3644 if ($hasformdata) {
3645 $mform->is_validated();
3648 $html .= $mform->render();
3649 return $html;
3653 * Calculate the timestamp from the supplied Gregorian Year, Month, and Day.
3655 * @param int $d The day
3656 * @param int $m The month
3657 * @param int $y The year
3658 * @param int $time The timestamp to use instead of a separate y/m/d.
3659 * @return int The timestamp
3661 function calendar_get_timestamp($d, $m, $y, $time = 0) {
3662 // If a day, month and year were passed then convert it to a timestamp. If these were passed
3663 // then we can assume the day, month and year are passed as Gregorian, as no where in core
3664 // should we be passing these values rather than the time.
3665 if (!empty($d) && !empty($m) && !empty($y)) {
3666 if (checkdate($m, $d, $y)) {
3667 $time = make_timestamp($y, $m, $d);
3668 } else {
3669 $time = time();
3671 } else if (empty($time)) {
3672 $time = time();
3675 return $time;
3679 * Get the calendar footer options.
3681 * @param calendar_information $calendar The calendar information object.
3682 * @return array The data for template and template name.
3684 function calendar_get_footer_options($calendar) {
3685 global $CFG, $USER, $DB, $PAGE;
3687 // Generate hash for iCal link.
3688 $rawhash = $USER->id . $DB->get_field('user', 'password', ['id' => $USER->id]) . $CFG->calendar_exportsalt;
3689 $authtoken = sha1($rawhash);
3691 $renderer = $PAGE->get_renderer('core_calendar');
3692 $footer = new \core_calendar\external\footer_options_exporter($calendar, $USER->id, $authtoken);
3693 $data = $footer->export($renderer);
3694 $template = 'core_calendar/footer_options';
3696 return [$data, $template];
3700 * Get the list of potential calendar filter types as a type => name
3701 * combination.
3703 * @return array
3705 function calendar_get_filter_types() {
3706 $types = [
3707 'site',
3708 'category',
3709 'course',
3710 'group',
3711 'user',
3712 'other'
3715 return array_map(function($type) {
3716 return [
3717 'eventtype' => $type,
3718 'name' => get_string("eventtype{$type}", "calendar"),
3719 'icon' => true,
3720 'key' => 'i/' . $type . 'event',
3721 'component' => 'core'
3723 }, $types);
3727 * Check whether the specified event type is valid.
3729 * @param string $type
3730 * @return bool
3732 function calendar_is_valid_eventtype($type) {
3733 $validtypes = [
3734 'user',
3735 'group',
3736 'course',
3737 'category',
3738 'site',
3740 return in_array($type, $validtypes);
3744 * Get event types the user can create event based on categories, courses and groups
3745 * the logged in user belongs to.
3747 * @param int|null $courseid The course id.
3748 * @return array The array of allowed types.
3750 function calendar_get_allowed_event_types(int $courseid = null) {
3751 global $DB, $CFG, $USER;
3753 $types = [
3754 'user' => false,
3755 'site' => false,
3756 'course' => false,
3757 'group' => false,
3758 'category' => false
3761 if (!empty($courseid) && $courseid != SITEID) {
3762 $context = \context_course::instance($courseid);
3763 $types['user'] = has_capability('moodle/calendar:manageownentries', $context);
3764 calendar_internal_update_course_and_group_permission($courseid, $context, $types);
3767 if (has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID))) {
3768 $types['site'] = true;
3771 if (has_capability('moodle/calendar:manageownentries', \context_system::instance())) {
3772 $types['user'] = true;
3774 if (core_course_category::has_manage_capability_on_any()) {
3775 $types['category'] = true;
3778 // We still don't know if the user can create group and course events, so iterate over the courses to find out
3779 // if the user has capabilities in one of the courses.
3780 if ($types['course'] == false || $types['group'] == false) {
3781 if ($CFG->calendar_adminseesall && has_capability('moodle/calendar:manageentries', context_system::instance())) {
3782 $sql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3783 FROM {course} c
3784 JOIN {context} ctx ON ctx.contextlevel = ? AND ctx.instanceid = c.id
3785 WHERE c.id IN (
3786 SELECT DISTINCT courseid FROM {groups}
3788 $courseswithgroups = $DB->get_recordset_sql($sql, [CONTEXT_COURSE]);
3789 foreach ($courseswithgroups as $course) {
3790 context_helper::preload_from_record($course);
3791 $context = context_course::instance($course->id);
3793 if (has_capability('moodle/calendar:manageentries', $context)) {
3794 if (has_any_capability(['moodle/site:accessallgroups', 'moodle/calendar:managegroupentries'], $context)) {
3795 // The user can manage group entries or access any group.
3796 $types['group'] = true;
3797 $types['course'] = true;
3798 break;
3802 $courseswithgroups->close();
3804 if (false === $types['course']) {
3805 // Course is still not confirmed. There may have been no courses with a group in them.
3806 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
3807 $sql = "SELECT
3808 c.id, c.visible, {$ctxfields}
3809 FROM {course} c
3810 JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
3811 $params = [
3812 'contextlevel' => CONTEXT_COURSE,
3814 $courses = $DB->get_recordset_sql($sql, $params);
3815 foreach ($courses as $course) {
3816 context_helper::preload_from_record($course);
3817 $context = context_course::instance($course->id);
3818 if (has_capability('moodle/calendar:manageentries', $context)) {
3819 $types['course'] = true;
3820 break;
3823 $courses->close();
3826 } else {
3827 $courses = calendar_get_default_courses(null, 'id');
3828 if (empty($courses)) {
3829 return $types;
3832 $courseids = array_map(function($c) {
3833 return $c->id;
3834 }, $courses);
3836 // Check whether the user has access to create events within courses which have groups.
3837 list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
3838 $sql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3839 FROM {course} c
3840 JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3841 WHERE c.id $insql
3842 AND c.id IN (SELECT DISTINCT courseid FROM {groups})";
3843 $params['contextlevel'] = CONTEXT_COURSE;
3844 $courseswithgroups = $DB->get_recordset_sql($sql, $params);
3845 foreach ($courseswithgroups as $coursewithgroup) {
3846 context_helper::preload_from_record($coursewithgroup);
3847 $context = context_course::instance($coursewithgroup->id);
3849 calendar_internal_update_course_and_group_permission($coursewithgroup->id, $context, $types);
3851 // Okay, course and group event types are allowed, no need to keep the loop iteration.
3852 if ($types['course'] == true && $types['group'] == true) {
3853 break;
3856 $courseswithgroups->close();
3858 if (false === $types['course']) {
3859 list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
3860 $contextsql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3861 FROM {course} c
3862 JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3863 WHERE c.id $insql";
3864 $params['contextlevel'] = CONTEXT_COURSE;
3865 $contextrecords = $DB->get_recordset_sql($contextsql, $params);
3866 foreach ($contextrecords as $course) {
3867 context_helper::preload_from_record($course);
3868 $coursecontext = context_course::instance($course->id);
3869 if (has_capability('moodle/calendar:manageentries', $coursecontext)
3870 && ($courseid == $course->id || empty($courseid))) {
3871 $types['course'] = true;
3872 break;
3875 $contextrecords->close();
3881 return $types;
3885 * Given a course id, and context, updates the permission types array to add the 'course' or 'group'
3886 * permission if it is relevant for that course.
3888 * For efficiency, if they already have 'course' or 'group' then it skips checks.
3890 * Do not call this function directly, it is only for use by calendar_get_allowed_event_types().
3892 * @param int $courseid Course id
3893 * @param context $context Context for that course
3894 * @param array $types Current permissions
3896 function calendar_internal_update_course_and_group_permission(int $courseid, context $context, array &$types) {
3897 if (!$types['course']) {
3898 // If they have manageentries permission on the course, then they can update this course.
3899 if (has_capability('moodle/calendar:manageentries', $context)) {
3900 $types['course'] = true;
3903 // To update group events they must have EITHER manageentries OR managegroupentries.
3904 if (!$types['group'] && (has_capability('moodle/calendar:manageentries', $context) ||
3905 has_capability('moodle/calendar:managegroupentries', $context))) {
3906 // And they also need for a group to exist on the course.
3907 $groups = groups_get_all_groups($courseid);
3908 if (!empty($groups)) {
3909 // And either accessallgroups, or belong to one of the groups.
3910 if (has_capability('moodle/site:accessallgroups', $context)) {
3911 $types['group'] = true;
3912 } else {
3913 foreach ($groups as $group) {
3914 if (groups_is_member($group->id)) {
3915 $types['group'] = true;
3916 break;