2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * @package core_calendar
21 * @copyright 2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 if (!defined('MOODLE_INTERNAL')) {
27 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
30 require_once($CFG->libdir . '/coursecatlib.php');
33 * These are read by the administration component to provide default values
37 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
39 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
42 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
44 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
47 * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
49 define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
51 // This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
52 // Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
55 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
57 define('CALENDAR_DEFAULT_WEEKEND', 65);
60 * CALENDAR_URL - path to calendar's folder
62 define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
65 * CALENDAR_TF_24 - Calendar time in 24 hours format
67 define('CALENDAR_TF_24', '%H:%M');
70 * CALENDAR_TF_12 - Calendar time in 12 hours format
72 define('CALENDAR_TF_12', '%I:%M %p');
75 * CALENDAR_EVENT_GLOBAL - Global calendar event types
77 define('CALENDAR_EVENT_GLOBAL', 1);
80 * CALENDAR_EVENT_COURSE - Course calendar event types
82 define('CALENDAR_EVENT_COURSE', 2);
85 * CALENDAR_EVENT_GROUP - group calendar event types
87 define('CALENDAR_EVENT_GROUP', 4);
90 * CALENDAR_EVENT_USER - user calendar event types
92 define('CALENDAR_EVENT_USER', 8);
95 * CALENDAR_EVENT_COURSECAT - Course category calendar event types
97 define('CALENDAR_EVENT_COURSECAT', 16);
100 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
102 define('CALENDAR_IMPORT_FROM_FILE', 0);
105 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
107 define('CALENDAR_IMPORT_FROM_URL', 1);
110 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
112 define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
115 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
117 define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
120 * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
122 define('CALENDAR_SUBSCRIPTION_UPDATE', 1);
125 * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
127 define('CALENDAR_SUBSCRIPTION_REMOVE', 2);
130 * CALENDAR_EVENT_USER_OVERRIDE_PRIORITY - Constant for the user override priority.
132 define('CALENDAR_EVENT_USER_OVERRIDE_PRIORITY', 0);
135 * CALENDAR_EVENT_TYPE_STANDARD - Standard events.
137 define('CALENDAR_EVENT_TYPE_STANDARD', 0);
140 * CALENDAR_EVENT_TYPE_ACTION - Action events.
142 define('CALENDAR_EVENT_TYPE_ACTION', 1);
145 * Manage calendar events.
147 * This class provides the required functionality in order to manage calendar events.
148 * It was introduced as part of Moodle 2.0 and was created in order to provide a
149 * better framework for dealing with calendar events in particular regard to file
150 * handling through the new file API.
152 * @package core_calendar
154 * @copyright 2009 Sam Hemelryk
155 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
157 * @property int $id The id within the event table
158 * @property string $name The name of the event
159 * @property string $description The description of the event
160 * @property int $format The format of the description FORMAT_?
161 * @property int $courseid The course the event is associated with (0 if none)
162 * @property int $groupid The group the event is associated with (0 if none)
163 * @property int $userid The user the event is associated with (0 if none)
164 * @property int $repeatid If this is a repeated event this will be set to the
166 * @property string $modulename If added by a module this will be the module name
167 * @property int $instance If added by a module this will be the module instance
168 * @property string $eventtype The event type
169 * @property int $timestart The start time as a timestamp
170 * @property int $timeduration The duration of the event in seconds
171 * @property int $visible 1 if the event is visible
172 * @property int $uuid ?
173 * @property int $sequence ?
174 * @property int $timemodified The time last modified as a timestamp
176 class calendar_event {
178 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
179 protected $properties = null;
181 /** @var string The converted event discription with file paths resolved.
182 * This gets populated when someone requests description for the first time */
183 protected $_description = null;
185 /** @var array The options to use with this description editor */
186 protected $editoroptions = array(
188 'forcehttps' => false,
191 'trusttext' => false);
193 /** @var object The context to use with the description editor */
194 protected $editorcontext = null;
197 * Instantiates a new event and optionally populates its properties with the data provided.
199 * @param \stdClass $data Optional. An object containing the properties to for
202 public function __construct($data = null) {
205 // First convert to object if it is not already (should either be object or assoc array).
206 if (!is_object($data)) {
207 $data = (object) $data;
210 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
212 $data->eventrepeats = 0;
214 if (empty($data->id)) {
218 if (!empty($data->subscriptionid)) {
219 $data->subscription = calendar_get_subscription($data->subscriptionid);
222 // Default to a user event.
223 if (empty($data->eventtype)) {
224 $data->eventtype = 'user';
227 // Default to the current user.
228 if (empty($data->userid)) {
229 $data->userid = $USER->id;
232 if (!empty($data->timeduration) && is_array($data->timeduration)) {
233 $data->timeduration = make_timestamp(
234 $data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'],
235 $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
238 if (!empty($data->description) && is_array($data->description)) {
239 $data->format = $data->description['format'];
240 $data->description = $data->description['text'];
241 } else if (empty($data->description)) {
242 $data->description = '';
243 $data->format = editors_get_preferred_format();
246 // Ensure form is defaulted correctly.
247 if (empty($data->format)) {
248 $data->format = editors_get_preferred_format();
251 $this->properties = $data;
257 * Attempts to call a set_$key method if one exists otherwise falls back
258 * to simply set the property.
260 * @param string $key property name
261 * @param mixed $value value of the property
263 public function __set($key, $value) {
264 if (method_exists($this, 'set_'.$key)) {
265 $this->{'set_'.$key}($value);
267 $this->properties->{$key} = $value;
273 * Attempts to call a get_$key method to return the property and ralls over
274 * to return the raw property.
276 * @param string $key property name
277 * @return mixed property value
278 * @throws \coding_exception
280 public function __get($key) {
281 if (method_exists($this, 'get_'.$key)) {
282 return $this->{'get_'.$key}();
284 if (!property_exists($this->properties, $key)) {
285 throw new \coding_exception('Undefined property requested');
287 return $this->properties->{$key};
291 * Magic isset method.
293 * PHP needs an isset magic method if you use the get magic method and
294 * still want empty calls to work.
296 * @param string $key $key property name
297 * @return bool|mixed property value, false if property is not exist
299 public function __isset($key) {
300 return !empty($this->properties->{$key});
304 * Calculate the context value needed for an event.
306 * Event's type can be determine by the available value store in $data
307 * It is important to check for the existence of course/courseid to determine
309 * Default value is set to CONTEXT_USER
311 * @return \stdClass The context object.
313 protected function calculate_context() {
317 if (isset($this->properties->categoryid) && $this->properties->categoryid > 0) {
318 $context = \context_coursecat::instance($this->properties->categoryid);
319 } else if (isset($this->properties->courseid) && $this->properties->courseid > 0) {
320 $context = \context_course::instance($this->properties->courseid);
321 } else if (isset($this->properties->course) && $this->properties->course > 0) {
322 $context = \context_course::instance($this->properties->course);
323 } else if (isset($this->properties->groupid) && $this->properties->groupid > 0) {
324 $group = $DB->get_record('groups', array('id' => $this->properties->groupid));
325 $context = \context_course::instance($group->courseid);
326 } else if (isset($this->properties->userid) && $this->properties->userid > 0
327 && $this->properties->userid == $USER->id) {
328 $context = \context_user::instance($this->properties->userid);
329 } else if (isset($this->properties->userid) && $this->properties->userid > 0
330 && $this->properties->userid != $USER->id &&
331 isset($this->properties->instance) && $this->properties->instance > 0) {
332 $cm = get_coursemodule_from_instance($this->properties->modulename, $this->properties->instance, 0,
334 $context = \context_course::instance($cm->course);
336 $context = \context_user::instance($this->properties->userid);
343 * Returns the context for this event. The context is calculated
344 * the first time is is requested and then stored in a member
345 * variable to be returned each subsequent time.
347 * This is a magical getter function that will be called when
348 * ever the context property is accessed, e.g. $event->context.
352 protected function get_context() {
353 if (!isset($this->properties->context)) {
354 $this->properties->context = $this->calculate_context();
357 return $this->properties->context;
361 * Returns an array of editoroptions for this event.
363 * @return array event editor options
365 protected function get_editoroptions() {
366 return $this->editoroptions;
370 * Returns an event description: Called by __get
371 * Please use $blah = $event->description;
373 * @return string event description
375 protected function get_description() {
378 require_once($CFG->libdir . '/filelib.php');
380 if ($this->_description === null) {
381 // Check if we have already resolved the context for this event.
382 if ($this->editorcontext === null) {
383 // Switch on the event type to decide upon the appropriate context to use for this event.
384 $this->editorcontext = $this->get_context();
385 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
386 return clean_text($this->properties->description, $this->properties->format);
390 // Work out the item id for the editor, if this is a repeated event
391 // then the files will be associated with the original.
392 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
393 $itemid = $this->properties->repeatid;
395 $itemid = $this->properties->id;
398 // Convert file paths in the description so that things display correctly.
399 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php',
400 $this->editorcontext->id, 'calendar', 'event_description', $itemid);
401 // Clean the text so no nasties get through.
402 $this->_description = clean_text($this->_description, $this->properties->format);
405 // Finally return the description.
406 return $this->_description;
410 * Return the number of repeat events there are in this events series.
412 * @return int number of event repeated
414 public function count_repeats() {
416 if (!empty($this->properties->repeatid)) {
417 $this->properties->eventrepeats = $DB->count_records('event',
418 array('repeatid' => $this->properties->repeatid));
419 // We don't want to count ourselves.
420 $this->properties->eventrepeats--;
422 return $this->properties->eventrepeats;
426 * Update or create an event within the database
428 * Pass in a object containing the event properties and this function will
429 * insert it into the database and deal with any associated files
431 * @see self::create()
432 * @see self::update()
434 * @param \stdClass $data object of event
435 * @param bool $checkcapability if moodle should check calendar managing capability or not
436 * @return bool event updated
438 public function update($data, $checkcapability=true) {
441 foreach ($data as $key => $value) {
442 $this->properties->$key = $value;
445 $this->properties->timemodified = time();
446 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
448 // Prepare event data.
450 'context' => $this->get_context(),
451 'objectid' => $this->properties->id,
453 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
454 'timestart' => $this->properties->timestart,
455 'name' => $this->properties->name
459 if (empty($this->properties->id) || $this->properties->id < 1) {
460 if ($checkcapability) {
461 if (!calendar_add_event_allowed($this->properties)) {
462 print_error('nopermissiontoupdatecalendar');
467 switch ($this->properties->eventtype) {
469 $this->properties->courseid = 0;
470 $this->properties->course = 0;
471 $this->properties->groupid = 0;
472 $this->properties->userid = $USER->id;
475 $this->properties->courseid = SITEID;
476 $this->properties->course = SITEID;
477 $this->properties->groupid = 0;
478 $this->properties->userid = $USER->id;
481 $this->properties->groupid = 0;
482 $this->properties->userid = $USER->id;
485 $this->properties->groupid = 0;
486 $this->properties->category = 0;
487 $this->properties->userid = $USER->id;
490 $this->properties->userid = $USER->id;
493 // We should NEVER get here, but just incase we do lets fail gracefully.
494 $usingeditor = false;
498 // If we are actually using the editor, we recalculate the context because some default values
499 // were set when calculate_context() was called from the constructor.
501 $this->properties->context = $this->calculate_context();
502 $this->editorcontext = $this->get_context();
505 $editor = $this->properties->description;
506 $this->properties->format = $this->properties->description['format'];
507 $this->properties->description = $this->properties->description['text'];
510 // Insert the event into the database.
511 $this->properties->id = $DB->insert_record('event', $this->properties);
514 $this->properties->description = file_save_draft_area_files(
516 $this->editorcontext->id,
519 $this->properties->id,
520 $this->editoroptions,
522 $this->editoroptions['forcehttps']);
523 $DB->set_field('event', 'description', $this->properties->description,
524 array('id' => $this->properties->id));
527 // Log the event entry.
528 $eventargs['objectid'] = $this->properties->id;
529 $eventargs['context'] = $this->get_context();
530 $event = \core\event\calendar_event_created::create($eventargs);
533 $repeatedids = array();
535 if (!empty($this->properties->repeat)) {
536 $this->properties->repeatid = $this->properties->id;
537 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id' => $this->properties->id));
539 $eventcopy = clone($this->properties);
540 unset($eventcopy->id);
542 $timestart = new \DateTime('@' . $eventcopy->timestart);
543 $timestart->setTimezone(\core_date::get_user_timezone_object());
545 for ($i = 1; $i < $eventcopy->repeats; $i++) {
547 $timestart->add(new \DateInterval('P7D'));
548 $eventcopy->timestart = $timestart->getTimestamp();
550 // Get the event id for the log record.
551 $eventcopyid = $DB->insert_record('event', $eventcopy);
553 // If the context has been set delete all associated files.
555 $fs = get_file_storage();
556 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description',
557 $this->properties->id);
558 foreach ($files as $file) {
559 $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
563 $repeatedids[] = $eventcopyid;
566 $eventargs['objectid'] = $eventcopyid;
567 $eventargs['other']['timestart'] = $eventcopy->timestart;
568 $event = \core\event\calendar_event_created::create($eventargs);
576 if ($checkcapability) {
577 if (!calendar_edit_event_allowed($this->properties)) {
578 print_error('nopermissiontoupdatecalendar');
583 if ($this->editorcontext !== null) {
584 $this->properties->description = file_save_draft_area_files(
585 $this->properties->description['itemid'],
586 $this->editorcontext->id,
589 $this->properties->id,
590 $this->editoroptions,
591 $this->properties->description['text'],
592 $this->editoroptions['forcehttps']);
594 $this->properties->format = $this->properties->description['format'];
595 $this->properties->description = $this->properties->description['text'];
599 $event = $DB->get_record('event', array('id' => $this->properties->id));
601 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
603 if ($updaterepeated) {
605 if ($this->properties->timestart != $event->timestart) {
606 $timestartoffset = $this->properties->timestart - $event->timestart;
607 $sql = "UPDATE {event}
610 timestart = timestart + ?,
616 // Note: Group and course id may not be set. If not, keep their current values.
618 $this->properties->name,
619 $this->properties->description,
621 $this->properties->timeduration,
623 isset($this->properties->groupid) ? $this->properties->groupid : $event->groupid,
624 isset($this->properties->courseid) ? $this->properties->courseid : $event->courseid,
628 $sql = "UPDATE {event}
636 // Note: Group and course id may not be set. If not, keep their current values.
638 $this->properties->name,
639 $this->properties->description,
640 $this->properties->timeduration,
642 isset($this->properties->groupid) ? $this->properties->groupid : $event->groupid,
643 isset($this->properties->courseid) ? $this->properties->courseid : $event->courseid,
647 $DB->execute($sql, $params);
649 // Trigger an update event for each of the calendar event.
650 $events = $DB->get_records('event', array('repeatid' => $event->repeatid), '', '*');
651 foreach ($events as $calendarevent) {
652 $eventargs['objectid'] = $calendarevent->id;
653 $eventargs['other']['timestart'] = $calendarevent->timestart;
654 $event = \core\event\calendar_event_updated::create($eventargs);
655 $event->add_record_snapshot('event', $calendarevent);
659 $DB->update_record('event', $this->properties);
660 $event = self::load($this->properties->id);
661 $this->properties = $event->properties();
663 // Trigger an update event.
664 $event = \core\event\calendar_event_updated::create($eventargs);
665 $event->add_record_snapshot('event', $this->properties);
674 * Deletes an event and if selected an repeated events in the same series
676 * This function deletes an event, any associated events if $deleterepeated=true,
677 * and cleans up any files associated with the events.
679 * @see self::delete()
681 * @param bool $deleterepeated delete event repeatedly
682 * @return bool succession of deleting event
684 public function delete($deleterepeated = false) {
687 // If $this->properties->id is not set then something is wrong.
688 if (empty($this->properties->id)) {
689 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
692 $calevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
694 $DB->delete_records('event', array('id' => $this->properties->id));
696 // Trigger an event for the delete action.
698 'context' => $this->get_context(),
699 'objectid' => $this->properties->id,
701 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
702 'timestart' => $this->properties->timestart,
703 'name' => $this->properties->name
705 $event = \core\event\calendar_event_deleted::create($eventargs);
706 $event->add_record_snapshot('event', $calevent);
709 // If we are deleting parent of a repeated event series, promote the next event in the series as parent.
710 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
711 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC",
712 array($this->properties->id), IGNORE_MULTIPLE);
713 if (!empty($newparent)) {
714 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?",
715 array($newparent, $this->properties->id));
716 // Get all records where the repeatid is the same as the event being removed.
717 $events = $DB->get_records('event', array('repeatid' => $newparent));
718 // For each of the returned events trigger an update event.
719 foreach ($events as $calendarevent) {
720 // Trigger an event for the update.
721 $eventargs['objectid'] = $calendarevent->id;
722 $eventargs['other']['timestart'] = $calendarevent->timestart;
723 $event = \core\event\calendar_event_updated::create($eventargs);
724 $event->add_record_snapshot('event', $calendarevent);
730 // If the editor context hasn't already been set then set it now.
731 if ($this->editorcontext === null) {
732 $this->editorcontext = $this->get_context();
735 // If the context has been set delete all associated files.
736 if ($this->editorcontext !== null) {
737 $fs = get_file_storage();
738 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
739 foreach ($files as $file) {
744 // If we need to delete repeated events then we will fetch them all and delete one by one.
745 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
746 // Get all records where the repeatid is the same as the event being removed.
747 $events = $DB->get_records('event', array('repeatid' => $this->properties->repeatid));
748 // For each of the returned events populate an event object and call delete.
749 // make sure the arg passed is false as we are already deleting all repeats.
750 foreach ($events as $event) {
751 $event = new calendar_event($event);
752 $event->delete(false);
760 * Fetch all event properties.
762 * This function returns all of the events properties as an object and optionally
763 * can prepare an editor for the description field at the same time. This is
764 * designed to work when the properties are going to be used to set the default
765 * values of a moodle forms form.
767 * @param bool $prepareeditor If set to true a editor is prepared for use with
768 * the mforms editor element. (for description)
769 * @return \stdClass Object containing event properties
771 public function properties($prepareeditor = false) {
774 // First take a copy of the properties. We don't want to actually change the
775 // properties or we'd forever be converting back and forwards between an
776 // editor formatted description and not.
777 $properties = clone($this->properties);
778 // Clean the description here.
779 $properties->description = clean_text($properties->description, $properties->format);
781 // If set to true we need to prepare the properties for use with an editor
782 // and prepare the file area.
783 if ($prepareeditor) {
785 // We may or may not have a property id. If we do then we need to work
786 // out the context so we can copy the existing files to the draft area.
787 if (!empty($properties->id)) {
789 if ($properties->eventtype === 'site') {
791 $this->editorcontext = $this->get_context();
792 } else if ($properties->eventtype === 'user') {
794 $this->editorcontext = $this->get_context();
795 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
796 // First check the course is valid.
797 $course = $DB->get_record('course', array('id' => $properties->courseid));
799 print_error('invalidcourse');
802 $this->editorcontext = $this->get_context();
803 // We have a course and are within the course context so we had
804 // better use the courses max bytes value.
805 $this->editoroptions['maxbytes'] = $course->maxbytes;
806 } else if ($properties->eventtype === 'category') {
807 // First check the course is valid.
808 \coursecat::get($properties->categoryid, MUST_EXIST, true);
810 $this->editorcontext = $this->get_context();
811 // We have a course and are within the course context so we had
812 // better use the courses max bytes value.
813 $this->editoroptions['maxbytes'] = $course->maxbytes;
815 // If we get here we have a custom event type as used by some
816 // modules. In this case the event will have been added by
817 // code and we won't need the editor.
818 $this->editoroptions['maxbytes'] = 0;
819 $this->editoroptions['maxfiles'] = 0;
822 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
825 // Get the context id that is what we really want.
826 $contextid = $this->editorcontext->id;
830 // If we get here then this is a new event in which case we don't need a
831 // context as there is no existing files to copy to the draft area.
835 // If the contextid === false we don't support files so no preparing
837 if ($contextid !== false) {
838 // Just encase it has already been submitted.
839 $draftiddescription = file_get_submitted_draft_itemid('description');
840 // Prepare the draft area, this copies existing files to the draft area as well.
841 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar',
842 'event_description', $properties->id, $this->editoroptions, $properties->description);
844 $draftiddescription = 0;
847 // Structure the description field as the editor requires.
848 $properties->description = array('text' => $properties->description, 'format' => $properties->format,
849 'itemid' => $draftiddescription);
852 // Finally return the properties.
857 * Toggles the visibility of an event
859 * @param null|bool $force If it is left null the events visibility is flipped,
860 * If it is false the event is made hidden, if it is true it
862 * @return bool if event is successfully updated, toggle will be visible
864 public function toggle_visibility($force = null) {
867 // Set visible to the default if it is not already set.
868 if (empty($this->properties->visible)) {
869 $this->properties->visible = 1;
872 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
873 // Make this event visible.
874 $this->properties->visible = 1;
876 // Make this event hidden.
877 $this->properties->visible = 0;
880 // Update the database to reflect this change.
881 $success = $DB->set_field('event', 'visible', $this->properties->visible, array('id' => $this->properties->id));
882 $calendarevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
884 // Prepare event data.
886 'context' => $this->get_context(),
887 'objectid' => $this->properties->id,
889 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
890 'timestart' => $this->properties->timestart,
891 'name' => $this->properties->name
894 $event = \core\event\calendar_event_updated::create($eventargs);
895 $event->add_record_snapshot('event', $calendarevent);
902 * Returns an event object when provided with an event id.
904 * This function makes use of MUST_EXIST, if the event id passed in is invalid
905 * it will result in an exception being thrown.
907 * @param int|object $param event object or event id
908 * @return calendar_event
910 public static function load($param) {
912 if (is_object($param)) {
913 $event = new calendar_event($param);
915 $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST);
916 $event = new calendar_event($event);
922 * Creates a new event and returns an event object
924 * @param \stdClass|array $properties An object containing event properties
925 * @param bool $checkcapability Check caps or not
926 * @throws \coding_exception
928 * @return calendar_event|bool The event object or false if it failed
930 public static function create($properties, $checkcapability = true) {
931 if (is_array($properties)) {
932 $properties = (object)$properties;
934 if (!is_object($properties)) {
935 throw new \coding_exception('When creating an event properties should be either an object or an assoc array');
937 $event = new calendar_event($properties);
938 if ($event->update($properties, $checkcapability)) {
946 * Format the text using the external API.
948 * This function should we used when text formatting is required in external functions.
950 * @return array an array containing the text formatted and the text format
952 public function format_external_text() {
954 if ($this->editorcontext === null) {
955 // Switch on the event type to decide upon the appropriate context to use for this event.
956 $this->editorcontext = $this->get_context();
958 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
959 // We don't have a context here, do a normal format_text.
960 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id);
964 // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
965 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
966 $itemid = $this->properties->repeatid;
968 $itemid = $this->properties->id;
971 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id,
972 'calendar', 'event_description', $itemid);
977 * Calendar information class
979 * This class is used simply to organise the information pertaining to a calendar
980 * and is used primarily to make information easily available.
982 * @package core_calendar
984 * @copyright 2010 Sam Hemelryk
985 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
987 class calendar_information {
990 * @var int The timestamp
992 * Rather than setting the day, month and year we will set a timestamp which will be able
993 * to be used by multiple calendars.
997 /** @var int A course id */
998 public $courseid = null;
1000 /** @var array An array of categories */
1001 public $categories = array();
1003 /** @var int The current category */
1004 public $categoryid = null;
1006 /** @var array An array of courses */
1007 public $courses = array();
1009 /** @var array An array of groups */
1010 public $groups = array();
1012 /** @var array An array of users */
1013 public $users = array();
1015 /** @var context The anticipated context that the calendar is viewed in */
1016 public $context = null;
1019 * Creates a new instance
1021 * @param int $day the number of the day
1022 * @param int $month the number of the month
1023 * @param int $year the number of the year
1024 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
1025 * and $calyear to support multiple calendars
1027 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
1028 // If a day, month and year were passed then convert it to a timestamp. If these were passed
1029 // then we can assume the day, month and year are passed as Gregorian, as no where in core
1030 // should we be passing these values rather than the time. This is done for BC.
1031 if (!empty($day) || !empty($month) || !empty($year)) {
1032 $date = usergetdate(time());
1034 $day = $date['mday'];
1036 if (empty($month)) {
1037 $month = $date['mon'];
1040 $year = $date['year'];
1042 if (checkdate($month, $day, $year)) {
1043 $time = make_timestamp($year, $month, $day);
1049 $this->set_time($time);
1053 * Creates and set up a instance.
1055 * @param int $time the unixtimestamp representing the date we want to view.
1056 * @param int $courseid The ID of the course the user wishes to view.
1057 * @param int $categoryid The ID of the category the user wishes to view
1058 * If a courseid is specified, this value is ignored.
1059 * @return calendar_information
1061 public static function create($time, int $courseid, int $categoryid = null) : calendar_information {
1062 $calendar = new static(0, 0, 0, $time);
1063 if ($courseid != SITEID && !empty($courseid)) {
1064 // Course ID must be valid and existing.
1065 $course = get_course($courseid);
1066 $calendar->context = context_course::instance($course->id);
1068 if (!$course->visible) {
1069 require_capability('moodle/course:viewhiddencourses', $calendar->context);
1072 $courses = [$course->id => $course];
1073 $category = (\coursecat::get($course->category, MUST_EXIST, true))->get_db_record();
1074 } else if (!empty($categoryid)) {
1075 $course = get_site();
1076 $courses = calendar_get_default_courses();
1078 // Filter available courses to those within this category or it's children.
1079 $ids = [$categoryid];
1080 $category = \coursecat::get($categoryid);
1081 $ids = array_merge($ids, array_keys($category->get_children()));
1082 $courses = array_filter($courses, function($course) use ($ids) {
1083 return array_search($course->category, $ids) !== false;
1085 $category = $category->get_db_record();
1087 $calendar->context = context_coursecat::instance($categoryid);
1089 $course = get_site();
1090 $courses = calendar_get_default_courses();
1093 $calendar->context = context_system::instance();
1096 $calendar->set_sources($course, $courses, $category);
1102 * Set the time period of this instance.
1104 * @param int $time the unixtimestamp representing the date we want to view.
1107 public function set_time($time = null) {
1109 $this->time = time();
1111 $this->time = $time;
1118 * Initialize calendar information
1121 * @param stdClass $course object
1122 * @param array $coursestoload An array of courses [$course->id => $course]
1123 * @param bool $ignorefilters options to use filter
1125 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
1126 debugging('The prepare_for_view() function has been deprecated. Please update your code to use set_sources()',
1128 $this->set_sources($course, $coursestoload);
1132 * Set the sources for events within the calendar.
1134 * If no category is provided, then the category path for the current
1135 * course will be used.
1137 * @param stdClass $course The current course being viewed.
1138 * @param int[] $courses The list of all courses currently accessible.
1139 * @param stdClass $category The current category to show.
1141 public function set_sources(stdClass $course, array $courses, stdClass $category = null) {
1144 // A cousre must always be specified.
1145 $this->course = $course;
1146 $this->courseid = $course->id;
1148 list($courseids, $group, $user) = calendar_set_filters($courses);
1149 $this->courses = $courseids;
1150 $this->groups = $group;
1151 $this->users = $user;
1153 // Do not show category events by default.
1154 $this->categoryid = null;
1155 $this->categories = null;
1157 // Determine the correct category information to show.
1158 // When called with a course, the category of that course is usually included too.
1159 // When a category was specifically requested, it should be requested with the site id.
1160 if (SITEID !== $this->courseid) {
1161 // A specific course was requested.
1162 // Fetch the category that this course is in, along with all parents.
1163 // Do not include child categories of this category, as the user many not have enrolments in those siblings or children.
1164 $category = \coursecat::get($course->category, MUST_EXIST, true);
1165 $this->categoryid = $category->id;
1167 $this->categories = $category->get_parents();
1168 $this->categories[] = $category->id;
1169 } else if (null !== $category && $category->id > 0) {
1170 // A specific category was requested.
1171 // Fetch all parents of this category, along with all children too.
1172 $category = \coursecat::get($category->id);
1173 $this->categoryid = $category->id;
1175 // Build the category list.
1176 // This includes the current category.
1177 $this->categories = [$category->id];
1179 // All of its descendants.
1180 foreach (\coursecat::get_all() as $cat) {
1181 if (array_search($category->id, $cat->get_parents()) !== false) {
1182 $this->categories[] = $cat->id;
1186 // And all of its parents.
1187 $this->categories = array_merge($this->categories, $category->get_parents());
1188 } else if (SITEID === $this->courseid) {
1189 // The site was requested.
1190 // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
1192 // Grab the list of categories that this user has courses in.
1193 $coursecategories = array_flip(array_map(function($course) {
1194 return $course->category;
1198 foreach (\coursecat::get_all() as $category) {
1199 if (has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
1200 // If a user can manage a category, then they can see all child categories. as well as all parent categories.
1201 $categories[] = $category->id;
1202 foreach (\coursecat::get_all() as $cat) {
1203 if (array_search($category->id, $cat->get_parents()) !== false) {
1204 $categories[] = $cat->id;
1207 $categories = array_merge($categories, $category->get_parents());
1208 } else if (isset($coursecategories[$category->id])) {
1209 // The user has access to a course in this category.
1210 // Fetch all of the parents too.
1211 $categories = array_merge($categories, [$category->id], $category->get_parents());
1212 $categories[] = $category->id;
1216 $this->categories = array_unique($categories);
1221 * Ensures the date for the calendar is correct and either sets it to now
1222 * or throws a moodle_exception if not
1224 * @param bool $defaultonow use current time
1225 * @throws moodle_exception
1226 * @return bool validation of checkdate
1228 public function checkdate($defaultonow = true) {
1229 if (!checkdate($this->month, $this->day, $this->year)) {
1231 $now = usergetdate(time());
1232 $this->day = intval($now['mday']);
1233 $this->month = intval($now['mon']);
1234 $this->year = intval($now['year']);
1237 throw new moodle_exception('invaliddate');
1244 * Gets todays timestamp for the calendar
1246 * @return int today timestamp
1248 public function timestamp_today() {
1252 * Gets tomorrows timestamp for the calendar
1254 * @return int tomorrow timestamp
1256 public function timestamp_tomorrow() {
1257 return strtotime('+1 day', $this->time);
1260 * Adds the pretend blocks for the calendar
1262 * @param core_calendar_renderer $renderer
1263 * @param bool $showfilters display filters, false is set as default
1264 * @param string|null $view preference view options (eg: day, month, upcoming)
1266 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
1268 $filters = new block_contents();
1269 $filters->content = $renderer->event_filter();
1270 $filters->footer = '';
1271 $filters->title = get_string('eventskey', 'calendar');
1272 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
1274 $block = new block_contents;
1275 $block->content = $renderer->fake_block_threemonths($this);
1276 $block->footer = '';
1277 $block->title = get_string('monthlyview', 'calendar');
1278 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
1283 * Get calendar events.
1285 * @param int $tstart Start time of time range for events
1286 * @param int $tend End time of time range for events
1287 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
1288 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
1289 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
1290 * @param boolean $withduration whether only events starting within time range selected
1291 * or events in progress/already started selected as well
1292 * @param boolean $ignorehidden whether to select only visible events or all events
1293 * @param array|int|boolean $categories array of categories, category id or boolean for all/no course events
1294 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
1296 function calendar_get_events($tstart, $tend, $users, $groups, $courses,
1297 $withduration = true, $ignorehidden = true, $categories = []) {
1303 if (empty($users) && empty($groups) && empty($courses) && empty($categories)) {
1307 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
1308 // Events from a number of users
1309 if(!empty($whereclause)) $whereclause .= ' OR';
1310 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED);
1311 $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)";
1312 $params = array_merge($params, $inparamsusers);
1313 } else if($users === true) {
1314 // Events from ALL users
1315 if(!empty($whereclause)) $whereclause .= ' OR';
1316 $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)';
1317 } else if($users === false) {
1318 // No user at all, do nothing
1321 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
1322 // Events from a number of groups
1323 if(!empty($whereclause)) $whereclause .= ' OR';
1324 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED);
1325 $whereclause .= " e.groupid $insqlgroups ";
1326 $params = array_merge($params, $inparamsgroups);
1327 } else if($groups === true) {
1328 // Events from ALL groups
1329 if(!empty($whereclause)) $whereclause .= ' OR ';
1330 $whereclause .= ' e.groupid != 0';
1332 // boolean false (no groups at all): we don't need to do anything
1334 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
1335 if(!empty($whereclause)) $whereclause .= ' OR';
1336 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED);
1337 $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
1338 $params = array_merge($params, $inparamscourses);
1339 } else if ($courses === true) {
1340 // Events from ALL courses
1341 if(!empty($whereclause)) $whereclause .= ' OR';
1342 $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
1345 if ((is_array($categories) && !empty($categories)) || is_numeric($categories)) {
1346 if (!empty($whereclause)) {
1347 $whereclause .= ' OR';
1349 list($insqlcategories, $inparamscategories) = $DB->get_in_or_equal($categories, SQL_PARAMS_NAMED);
1350 $whereclause .= " (e.groupid = 0 AND e.courseid = 0 AND e.categoryid $insqlcategories)";
1351 $params = array_merge($params, $inparamscategories);
1352 } else if ($categories === true) {
1353 // Events from ALL categories.
1354 if (!empty($whereclause)) {
1355 $whereclause .= ' OR';
1357 $whereclause .= ' (e.groupid = 0 AND e.courseid = 0 AND e.categoryid != 0)';
1360 // Security check: if, by now, we have NOTHING in $whereclause, then it means
1361 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
1362 // events no matter what. Allowing the code to proceed might return a completely
1363 // valid query with only time constraints, thus selecting ALL events in that time frame!
1364 if(empty($whereclause)) {
1369 $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1372 $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1374 if(!empty($whereclause)) {
1375 // We have additional constraints
1376 $whereclause = $timeclause.' AND ('.$whereclause.')';
1379 // Just basic time filtering
1380 $whereclause = $timeclause;
1383 if ($ignorehidden) {
1384 $whereclause .= ' AND e.visible = 1';
1389 LEFT JOIN {modules} m ON e.modulename = m.name
1390 -- Non visible modules will have a value of 0.
1391 WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
1392 ORDER BY e.timestart";
1393 $events = $DB->get_records_sql($sql, $params);
1395 if ($events === false) {
1402 * Return the days of the week.
1404 * @return array array of days
1406 function calendar_get_days() {
1407 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1408 return $calendartype->get_weekdays();
1412 * Get the subscription from a given id.
1415 * @param int $id id of the subscription
1416 * @return stdClass Subscription record from DB
1417 * @throws moodle_exception for an invalid id
1419 function calendar_get_subscription($id) {
1422 $cache = \cache::make('core', 'calendar_subscriptions');
1423 $subscription = $cache->get($id);
1424 if (empty($subscription)) {
1425 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
1426 $cache->set($id, $subscription);
1429 return $subscription;
1433 * Gets the first day of the week.
1435 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
1439 function calendar_get_starting_weekday() {
1440 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1441 return $calendartype->get_starting_weekday();
1445 * Get a HTML link to a course.
1447 * @param int|stdClass $course the course id or course object
1448 * @return string a link to the course (as HTML); empty if the course id is invalid
1450 function calendar_get_courselink($course) {
1455 if (!is_object($course)) {
1456 $course = calendar_get_course_cached($coursecache, $course);
1458 $context = \context_course::instance($course->id);
1459 $fullname = format_string($course->fullname, true, array('context' => $context));
1460 $url = new \moodle_url('/course/view.php', array('id' => $course->id));
1461 $link = \html_writer::link($url, $fullname);
1467 * Get current module cache.
1469 * Only use this method if you do not know courseid. Otherwise use:
1470 * get_fast_modinfo($courseid)->instances[$modulename][$instance]
1472 * @param array $modulecache in memory module cache
1473 * @param string $modulename name of the module
1474 * @param int $instance module instance number
1475 * @return stdClass|bool $module information
1477 function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
1478 if (!isset($modulecache[$modulename . '_' . $instance])) {
1479 $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
1482 return $modulecache[$modulename . '_' . $instance];
1486 * Get current course cache.
1488 * @param array $coursecache list of course cache
1489 * @param int $courseid id of the course
1490 * @return stdClass $coursecache[$courseid] return the specific course cache
1492 function calendar_get_course_cached(&$coursecache, $courseid) {
1493 if (!isset($coursecache[$courseid])) {
1494 $coursecache[$courseid] = get_course($courseid);
1496 return $coursecache[$courseid];
1500 * Get group from groupid for calendar display
1502 * @param int $groupid
1503 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1505 function calendar_get_group_cached($groupid) {
1506 static $groupscache = array();
1507 if (!isset($groupscache[$groupid])) {
1508 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1510 return $groupscache[$groupid];
1514 * Add calendar event metadata
1516 * @param stdClass $event event info
1517 * @return stdClass $event metadata
1519 function calendar_add_event_metadata($event) {
1520 global $CFG, $OUTPUT;
1522 // Support multilang in event->name.
1523 $event->name = format_string($event->name, true);
1525 if (!empty($event->modulename)) { // Activity event.
1526 // The module name is set. I will assume that it has to be displayed, and
1527 // also that it is an automatically-generated event. And of course that the
1528 // instace id and modulename are set correctly.
1529 $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
1530 if (!array_key_exists($event->instance, $instances)) {
1533 $module = $instances[$event->instance];
1535 $modulename = $module->get_module_type_name(false);
1536 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
1537 // Will be used as alt text if the event icon.
1538 $eventtype = get_string($event->eventtype, $event->modulename);
1543 $event->icon = '<img src="' . s($module->get_icon_url()) . '" alt="' . s($eventtype) .
1544 '" title="' . s($modulename) . '" class="icon" />';
1545 $event->referer = html_writer::link($module->url, $event->name);
1546 $event->courselink = calendar_get_courselink($module->get_course());
1547 $event->cmid = $module->id;
1548 } else if ($event->courseid == SITEID) { // Site event.
1549 $event->icon = '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
1550 get_string('globalevent', 'calendar') . '" class="icon" />';
1551 $event->cssclass = 'calendar_event_global';
1552 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event.
1553 $event->icon = '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
1554 get_string('courseevent', 'calendar') . '" class="icon" />';
1555 $event->courselink = calendar_get_courselink($event->courseid);
1556 $event->cssclass = 'calendar_event_course';
1557 } else if ($event->groupid) { // Group event.
1558 if ($group = calendar_get_group_cached($event->groupid)) {
1559 $groupname = format_string($group->name, true, \context_course::instance($group->courseid));
1563 $event->icon = \html_writer::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
1564 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
1565 $event->courselink = calendar_get_courselink($event->courseid) . ', ' . $groupname;
1566 $event->cssclass = 'calendar_event_group';
1567 } else if ($event->userid) { // User event.
1568 $event->icon = '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
1569 get_string('userevent', 'calendar') . '" class="icon" />';
1570 $event->cssclass = 'calendar_event_user';
1577 * Get calendar events by id.
1580 * @param array $eventids list of event ids
1581 * @return array Array of event entries, empty array if nothing found
1583 function calendar_get_events_by_id($eventids) {
1586 if (!is_array($eventids) || empty($eventids)) {
1590 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
1591 $wheresql = "id $wheresql";
1593 return $DB->get_records_select('event', $wheresql, $params);
1597 * Get control options for calendar.
1599 * @param string $type of calendar
1600 * @param array $data calendar information
1601 * @return string $content return available control for the calender in html
1603 function calendar_top_controls($type, $data) {
1604 global $PAGE, $OUTPUT;
1606 // Get the calendar type we are using.
1607 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1611 // Ensure course id passed if relevant.
1613 if (!empty($data['id'])) {
1614 $courseid = '&course=' . $data['id'];
1617 // If we are passing a month and year then we need to convert this to a timestamp to
1618 // support multiple calendars. No where in core should these be passed, this logic
1619 // here is for third party plugins that may use this function.
1620 if (!empty($data['m']) && !empty($date['y'])) {
1621 if (!isset($data['d'])) {
1624 if (!checkdate($data['m'], $data['d'], $data['y'])) {
1627 $time = make_timestamp($data['y'], $data['m'], $data['d']);
1629 } else if (!empty($data['time'])) {
1630 $time = $data['time'];
1635 // Get the date for the calendar type.
1636 $date = $calendartype->timestamp_to_date_array($time);
1638 $urlbase = $PAGE->url;
1640 // We need to get the previous and next months in certain cases.
1641 if ($type == 'frontpage' || $type == 'course' || $type == 'month') {
1642 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1643 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
1644 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
1645 $prevmonthtime['hour'], $prevmonthtime['minute']);
1647 $nextmonth = calendar_add_month($date['mon'], $date['year']);
1648 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
1649 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
1650 $nextmonthtime['hour'], $nextmonthtime['minute']);
1655 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1656 true, $prevmonthtime);
1657 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true,
1659 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1660 false, false, false, $time);
1662 if (!empty($data['id'])) {
1663 $calendarlink->param('course', $data['id']);
1668 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1669 $content .= $prevlink . '<span class="hide"> | </span>';
1670 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1671 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1672 ), array('class' => 'current'));
1673 $content .= '<span class="hide"> | </span>' . $right;
1674 $content .= "<span class=\"clearer\"><!-- --></span>\n";
1675 $content .= \html_writer::end_tag('div');
1679 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1680 true, $prevmonthtime);
1681 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false,
1682 true, $nextmonthtime);
1683 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1684 false, false, false, $time);
1686 if (!empty($data['id'])) {
1687 $calendarlink->param('course', $data['id']);
1690 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1691 $content .= $prevlink . '<span class="hide"> | </span>';
1692 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1693 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1694 ), array('class' => 'current'));
1695 $content .= '<span class="hide"> | </span>' . $nextlink;
1696 $content .= "<span class=\"clearer\"><!-- --></span>";
1697 $content .= \html_writer::end_tag('div');
1700 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'upcoming')),
1701 false, false, false, $time);
1702 if (!empty($data['id'])) {
1703 $calendarlink->param('course', $data['id']);
1705 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1706 $content .= \html_writer::tag('div', $calendarlink, array('class' => 'centered'));
1709 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1710 false, false, false, $time);
1711 if (!empty($data['id'])) {
1712 $calendarlink->param('course', $data['id']);
1714 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1715 $content .= \html_writer::tag('h3', $calendarlink);
1718 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1719 'view.php?view=month' . $courseid . '&', false, false, false, false, $prevmonthtime);
1720 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1721 'view.php?view=month' . $courseid . '&', false, false, false, false, $nextmonthtime);
1723 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1724 $content .= $prevlink . '<span class="hide"> | </span>';
1725 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1726 $content .= '<span class="hide"> | </span>' . $nextlink;
1727 $content .= '<span class="clearer"><!-- --></span>';
1728 $content .= \html_writer::end_tag('div')."\n";
1731 $days = calendar_get_days();
1733 $prevtimestamp = strtotime('-1 day', $time);
1734 $nexttimestamp = strtotime('+1 day', $time);
1736 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1737 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1739 $prevname = $days[$prevdate['wday']]['fullname'];
1740 $nextname = $days[$nextdate['wday']]['fullname'];
1741 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&', false, false,
1742 false, false, $prevtimestamp);
1743 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&', false, false, false,
1744 false, $nexttimestamp);
1746 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1747 $content .= $prevlink;
1748 $content .= '<span class="hide"> | </span><span class="current">' .userdate($time,
1749 get_string('strftimedaydate')) . '</span>';
1750 $content .= '<span class="hide"> | </span>' . $nextlink;
1751 $content .= "<span class=\"clearer\"><!-- --></span>";
1752 $content .= \html_writer::end_tag('div') . "\n";
1761 * Return the representation day.
1763 * @param int $tstamp Timestamp in GMT
1764 * @param int|bool $now current Unix timestamp
1765 * @param bool $usecommonwords
1766 * @return string the formatted date/time
1768 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1769 static $shortformat;
1771 if (empty($shortformat)) {
1772 $shortformat = get_string('strftimedayshort');
1775 if ($now === false) {
1779 // To have it in one place, if a change is needed.
1780 $formal = userdate($tstamp, $shortformat);
1782 $datestamp = usergetdate($tstamp);
1783 $datenow = usergetdate($now);
1785 if ($usecommonwords == false) {
1786 // We don't want words, just a date.
1788 } else if ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1789 return get_string('today', 'calendar');
1790 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1791 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12
1792 && $datenow['yday'] == 1)) {
1793 return get_string('yesterday', 'calendar');
1794 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1795 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12
1796 && $datestamp['yday'] == 1)) {
1797 return get_string('tomorrow', 'calendar');
1804 * return the formatted representation time.
1807 * @param int $time the timestamp in UTC, as obtained from the database
1808 * @return string the formatted date/time
1810 function calendar_time_representation($time) {
1811 static $langtimeformat = null;
1813 if ($langtimeformat === null) {
1814 $langtimeformat = get_string('strftimetime');
1817 $timeformat = get_user_preferences('calendar_timeformat');
1818 if (empty($timeformat)) {
1819 $timeformat = get_config(null, 'calendar_site_timeformat');
1822 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
1826 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1828 * @param string|moodle_url $linkbase
1829 * @param int $d The number of the day.
1830 * @param int $m The number of the month.
1831 * @param int $y The number of the year.
1832 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1833 * $m and $y are kept for backwards compatibility.
1834 * @return moodle_url|null $linkbase
1836 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1837 if (empty($linkbase)) {
1841 if (!($linkbase instanceof \moodle_url)) {
1842 $linkbase = new \moodle_url($linkbase);
1845 $linkbase->param('time', calendar_get_timestamp($d, $m, $y, $time));
1851 * Build and return a previous month HTML link, with an arrow.
1853 * @param string $text The text label.
1854 * @param string|moodle_url $linkbase The URL stub.
1855 * @param int $d The number of the date.
1856 * @param int $m The number of the month.
1857 * @param int $y year The number of the year.
1858 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1859 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1860 * $m and $y are kept for backwards compatibility.
1861 * @return string HTML string.
1863 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1864 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1871 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1872 'data-drop-zone' => 'nav-link',
1875 return link_arrow_left($text, $href->out(false), $accesshide, 'previous', $attrs);
1879 * Build and return a next month HTML link, with an arrow.
1881 * @param string $text The text label.
1882 * @param string|moodle_url $linkbase The URL stub.
1883 * @param int $d the number of the Day
1884 * @param int $m The number of the month.
1885 * @param int $y The number of the year.
1886 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1887 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1888 * $m and $y are kept for backwards compatibility.
1889 * @return string HTML string.
1891 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1892 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1899 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1900 'data-drop-zone' => 'nav-link',
1903 return link_arrow_right($text, $href->out(false), $accesshide, 'next', $attrs);
1907 * Return the number of days in month.
1909 * @param int $month the number of the month.
1910 * @param int $year the number of the year
1913 function calendar_days_in_month($month, $year) {
1914 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1915 return $calendartype->get_num_days_in_month($year, $month);
1919 * Get the next following month.
1921 * @param int $month the number of the month.
1922 * @param int $year the number of the year.
1923 * @return array the following month
1925 function calendar_add_month($month, $year) {
1926 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1927 return $calendartype->get_next_month($year, $month);
1931 * Get the previous month.
1933 * @param int $month the number of the month.
1934 * @param int $year the number of the year.
1935 * @return array previous month
1937 function calendar_sub_month($month, $year) {
1938 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1939 return $calendartype->get_prev_month($year, $month);
1943 * Get per-day basis events
1945 * @param array $events list of events
1946 * @param int $month the number of the month
1947 * @param int $year the number of the year
1948 * @param array $eventsbyday event on specific day
1949 * @param array $durationbyday duration of the event in days
1950 * @param array $typesbyday event type (eg: global, course, user, or group)
1951 * @param array $courses list of courses
1954 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1955 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1957 $eventsbyday = array();
1958 $typesbyday = array();
1959 $durationbyday = array();
1961 if ($events === false) {
1965 foreach ($events as $event) {
1966 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
1967 if ($event->timeduration) {
1968 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
1970 $enddate = $startdate;
1973 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair.
1974 if (!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) &&
1975 ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1979 $eventdaystart = intval($startdate['mday']);
1981 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
1982 // Give the event to its day.
1983 $eventsbyday[$eventdaystart][] = $event->id;
1985 // Mark the day as having such an event.
1986 if ($event->courseid == SITEID && $event->groupid == 0) {
1987 $typesbyday[$eventdaystart]['startglobal'] = true;
1988 // Set event class for global event.
1989 $events[$event->id]->class = 'calendar_event_global';
1990 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1991 $typesbyday[$eventdaystart]['startcourse'] = true;
1992 // Set event class for course event.
1993 $events[$event->id]->class = 'calendar_event_course';
1994 } else if ($event->groupid) {
1995 $typesbyday[$eventdaystart]['startgroup'] = true;
1996 // Set event class for group event.
1997 $events[$event->id]->class = 'calendar_event_group';
1998 } else if ($event->userid) {
1999 $typesbyday[$eventdaystart]['startuser'] = true;
2000 // Set event class for user event.
2001 $events[$event->id]->class = 'calendar_event_user';
2005 if ($event->timeduration == 0) {
2006 // Proceed with the next.
2010 // The event starts on $month $year or before.
2011 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2012 $lowerbound = intval($startdate['mday']);
2017 // Also, it ends on $month $year or later.
2018 if ($enddate['mon'] == $month && $enddate['year'] == $year) {
2019 $upperbound = intval($enddate['mday']);
2021 $upperbound = calendar_days_in_month($month, $year);
2024 // Mark all days between $lowerbound and $upperbound (inclusive) as duration.
2025 for ($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
2026 $durationbyday[$i][] = $event->id;
2027 if ($event->courseid == SITEID && $event->groupid == 0) {
2028 $typesbyday[$i]['durationglobal'] = true;
2029 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
2030 $typesbyday[$i]['durationcourse'] = true;
2031 } else if ($event->groupid) {
2032 $typesbyday[$i]['durationgroup'] = true;
2033 } else if ($event->userid) {
2034 $typesbyday[$i]['durationuser'] = true;
2043 * Returns the courses to load events for.
2045 * @param array $courseeventsfrom An array of courses to load calendar events for
2046 * @param bool $ignorefilters specify the use of filters, false is set as default
2047 * @return array An array of courses, groups, and user to load calendar events for based upon filters
2049 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
2052 // For backwards compatability we have to check whether the courses array contains
2053 // just id's in which case we need to load course objects.
2054 $coursestoload = array();
2055 foreach ($courseeventsfrom as $id => $something) {
2056 if (!is_object($something)) {
2057 $coursestoload[] = $id;
2058 unset($courseeventsfrom[$id]);
2066 // Get the capabilities that allow seeing group events from all groups.
2067 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
2069 $isloggedin = isloggedin();
2071 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
2072 $courses = array_keys($courseeventsfrom);
2074 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
2075 $courses[] = SITEID;
2077 $courses = array_unique($courses);
2080 if (!empty($courses) && in_array(SITEID, $courses)) {
2081 // Sort courses for consistent colour highlighting.
2082 // Effectively ignoring SITEID as setting as last course id.
2083 $key = array_search(SITEID, $courses);
2084 unset($courses[$key]);
2085 $courses[] = SITEID;
2088 if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
2092 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
2094 if (count($courseeventsfrom) == 1) {
2095 $course = reset($courseeventsfrom);
2096 if (has_any_capability($allgroupscaps, \context_course::instance($course->id))) {
2097 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
2098 $group = array_keys($coursegroups);
2101 if ($group === false) {
2102 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, \context_system::instance())) {
2104 } else if ($isloggedin) {
2105 $groupids = array();
2106 foreach ($courseeventsfrom as $courseid => $course) {
2107 // If the user is an editing teacher in there.
2108 if (!empty($USER->groupmember[$course->id])) {
2109 // We've already cached the users groups for this course so we can just use that.
2110 $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
2111 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2112 // If this course has groups, show events from all of those related to the current user.
2113 $coursegroups = groups_get_user_groups($course->id, $USER->id);
2114 $groupids = array_merge($groupids, $coursegroups['0']);
2117 if (!empty($groupids)) {
2123 if (empty($courses)) {
2127 return array($courses, $group, $user);
2131 * Return the capability for viewing a calendar event.
2133 * @param calendar_event $event event object
2136 function calendar_view_event_allowed(calendar_event $event) {
2139 // Anyone can see site events.
2140 if ($event->courseid && $event->courseid == SITEID) {
2144 // If a user can manage events at the site level they can see any event.
2145 $sitecontext = \context_system::instance();
2146 // If user has manageentries at site level, return true.
2147 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2151 if (!empty($event->groupid)) {
2152 // If it is a group event we need to be able to manage events in the course, or be in the group.
2153 if (has_capability('moodle/calendar:manageentries', $event->context) ||
2154 has_capability('moodle/calendar:managegroupentries', $event->context)) {
2158 $mycourses = enrol_get_my_courses('id');
2159 return isset($mycourses[$event->courseid]) && groups_is_member($event->groupid);
2160 } else if ($event->modulename) {
2161 // If this is a module event we need to be able to see the module.
2162 $coursemodules = [];
2164 // Override events do not have the courseid set.
2165 if ($event->courseid) {
2166 $courseid = $event->courseid;
2167 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2169 $cmraw = get_coursemodule_from_instance($event->modulename, $event->instance, 0, false, MUST_EXIST);
2170 $courseid = $cmraw->course;
2171 $coursemodules = get_fast_modinfo($cmraw->course)->instances;
2173 $hasmodule = isset($coursemodules[$event->modulename]);
2174 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2176 // If modinfo doesn't know about the module, return false to be safe.
2177 if (!$hasmodule || !$hasinstance) {
2181 // Must be able to see the course and the module - MDL-59304.
2182 $cm = $coursemodules[$event->modulename][$event->instance];
2183 if (!$cm->uservisible) {
2186 $mycourses = enrol_get_my_courses('id');
2187 return isset($mycourses[$courseid]);
2188 } else if ($event->categoryid) {
2189 // If this is a category we need to be able to see the category.
2190 $cat = \coursecat::get($event->categoryid, IGNORE_MISSING);
2195 } else if (!empty($event->courseid)) {
2196 // If it is a course event we need to be able to manage events in the course, or be in the course.
2197 if (has_capability('moodle/calendar:manageentries', $event->context)) {
2200 $mycourses = enrol_get_my_courses('id');
2201 return isset($mycourses[$event->courseid]);
2202 } else if ($event->userid) {
2203 if ($event->userid != $USER->id) {
2204 // No-one can ever see another users events.
2209 throw new moodle_exception('unknown event type');
2216 * Return the capability for editing calendar event.
2218 * @param calendar_event $event event object
2219 * @param bool $manualedit is the event being edited manually by the user
2220 * @return bool capability to edit event
2222 function calendar_edit_event_allowed($event, $manualedit = false) {
2225 // Must be logged in.
2226 if (!isloggedin()) {
2230 // Can not be using guest account.
2231 if (isguestuser()) {
2235 if ($manualedit && !empty($event->modulename)) {
2236 $hascallback = component_callback_exists(
2237 'mod_' . $event->modulename,
2238 'core_calendar_event_timestart_updated'
2241 if (!$hascallback) {
2242 // If the activity hasn't implemented the correct callback
2243 // to handle changes to it's events then don't allow any
2244 // manual changes to them.
2248 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2249 $hasmodule = isset($coursemodules[$event->modulename]);
2250 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2252 // If modinfo doesn't know about the module, return false to be safe.
2253 if (!$hasmodule || !$hasinstance) {
2257 $coursemodule = $coursemodules[$event->modulename][$event->instance];
2258 $context = context_module::instance($coursemodule->id);
2259 // This is the capability that allows a user to modify the activity
2260 // settings. Since the activity generated this event we need to check
2261 // that the current user has the same capability before allowing them
2262 // to update the event because the changes to the event will be
2263 // reflected within the activity.
2264 return has_capability('moodle/course:manageactivities', $context);
2267 // You cannot edit URL based calendar subscription events presently.
2268 if (!empty($event->subscriptionid)) {
2269 if (!empty($event->subscription->url)) {
2270 // This event can be updated externally, so it cannot be edited.
2275 $sitecontext = \context_system::instance();
2277 // If user has manageentries at site level, return true.
2278 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2282 // If groupid is set, it's definitely a group event.
2283 if (!empty($event->groupid)) {
2284 // Allow users to add/edit group events if -
2285 // 1) They have manageentries for the course OR
2286 // 2) They have managegroupentries AND are in the group.
2287 $group = $DB->get_record('groups', array('id' => $event->groupid));
2289 has_capability('moodle/calendar:manageentries', $event->context) ||
2290 (has_capability('moodle/calendar:managegroupentries', $event->context)
2291 && groups_is_member($event->groupid)));
2292 } else if (!empty($event->courseid)) {
2293 // If groupid is not set, but course is set, it's definitely a course event.
2294 return has_capability('moodle/calendar:manageentries', $event->context);
2295 } else if (!empty($event->categoryid)) {
2296 // If groupid is not set, but category is set, it's definitely a category event.
2297 return has_capability('moodle/calendar:manageentries', $event->context);
2298 } else if (!empty($event->userid) && $event->userid == $USER->id) {
2299 // If course is not set, but userid id set, it's a user event.
2300 return (has_capability('moodle/calendar:manageownentries', $event->context));
2301 } else if (!empty($event->userid)) {
2302 return (has_capability('moodle/calendar:manageentries', $event->context));
2309 * Return the capability for deleting a calendar event.
2311 * @param calendar_event $event The event object
2312 * @return bool Whether the user has permission to delete the event or not.
2314 function calendar_delete_event_allowed($event) {
2315 // Only allow delete if you have capabilities and it is not an module event.
2316 return (calendar_edit_event_allowed($event) && empty($event->modulename));
2320 * Returns the default courses to display on the calendar when there isn't a specific
2321 * course to display.
2323 * @param int $courseid (optional) If passed, an additional course can be returned for admins (the current course).
2324 * @param string $fields Comma separated list of course fields to return.
2325 * @param bool $canmanage If true, this will return the list of courses the current user can create events in, rather
2326 * than the list of courses they see events from (an admin can always add events in a course
2327 * calendar, even if they are not enrolled in the course).
2328 * @return array $courses Array of courses to display
2330 function calendar_get_default_courses($courseid = null, $fields = '*', $canmanage=false) {
2333 if (!isloggedin()) {
2337 if (has_capability('moodle/calendar:manageentries', context_system::instance()) &&
2338 (!empty($CFG->calendar_adminseesall) || $canmanage)) {
2340 // Add a c. prefix to every field as expected by get_courses function.
2341 $fieldlist = explode(',', $fields);
2343 $prefixedfields = array_map(function($value) {
2344 return 'c.' . trim($value);
2346 $courses = get_courses('all', 'c.shortname', implode(',', $prefixedfields));
2348 $courses = enrol_get_my_courses($fields);
2351 if ($courseid && $courseid != SITEID) {
2352 if (empty($courses[$courseid]) && has_capability('moodle/calendar:manageentries', context_system::instance())) {
2353 // Allow a site admin to see calendars from courses he is not enrolled in.
2354 // This will come from $COURSE.
2355 $courses[$courseid] = get_course($courseid);
2363 * Get event format time.
2365 * @param calendar_event $event event object
2366 * @param int $now current time in gmt
2367 * @param array $linkparams list of params for event link
2368 * @param bool $usecommonwords the words as formatted date/time.
2369 * @param int $showtime determine the show time GMT timestamp
2370 * @return string $eventtime link/string for event time
2372 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
2373 $starttime = $event->timestart;
2374 $endtime = $event->timestart + $event->timeduration;
2376 if (empty($linkparams) || !is_array($linkparams)) {
2377 $linkparams = array();
2380 $linkparams['view'] = 'day';
2382 // OK, now to get a meaningful display.
2383 // Check if there is a duration for this event.
2384 if ($event->timeduration) {
2385 // Get the midnight of the day the event will start.
2386 $usermidnightstart = usergetmidnight($starttime);
2387 // Get the midnight of the day the event will end.
2388 $usermidnightend = usergetmidnight($endtime);
2389 // Check if we will still be on the same day.
2390 if ($usermidnightstart == $usermidnightend) {
2391 // Check if we are running all day.
2392 if ($event->timeduration == DAYSECS) {
2393 $time = get_string('allday', 'calendar');
2394 } else { // Specify the time we will be running this from.
2395 $datestart = calendar_time_representation($starttime);
2396 $dateend = calendar_time_representation($endtime);
2397 $time = $datestart . ' <strong>»</strong> ' . $dateend;
2400 // Set printable representation.
2402 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2403 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2404 $eventtime = \html_writer::link($url, $day) . ', ' . $time;
2408 } else { // It must spans two or more days.
2409 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
2410 if ($showtime == $usermidnightstart) {
2413 $timestart = calendar_time_representation($event->timestart);
2414 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
2415 if ($showtime == $usermidnightend) {
2418 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
2420 // Set printable representation.
2421 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2422 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2423 $eventtime = $timestart . ' <strong>»</strong> ' . \html_writer::link($url, $dayend) . $timeend;
2425 // The event is in the future, print start and end links.
2426 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2427 $eventtime = \html_writer::link($url, $daystart) . $timestart . ' <strong>»</strong> ';
2429 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2430 $eventtime .= \html_writer::link($url, $dayend) . $timeend;
2433 } else { // There is no time duration.
2434 $time = calendar_time_representation($event->timestart);
2435 // Set printable representation.
2437 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2438 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2439 $eventtime = \html_writer::link($url, $day) . ', ' . trim($time);
2445 // Check if It has expired.
2446 if ($event->timestart + $event->timeduration < $now) {
2447 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2454 * Checks to see if the requested type of event should be shown for the given user.
2456 * @param int $type The type to check the display for (default is to display all)
2457 * @param stdClass|int|null $user The user to check for - by default the current user
2458 * @return bool True if the tyep should be displayed false otherwise
2460 function calendar_show_event_type($type, $user = null) {
2461 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
2463 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2465 if (!isset($SESSION->calendarshoweventtype)) {
2466 $SESSION->calendarshoweventtype = $default;
2468 return $SESSION->calendarshoweventtype & $type;
2470 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2475 * Sets the display of the event type given $display.
2477 * If $display = true the event type will be shown.
2478 * If $display = false the event type will NOT be shown.
2479 * If $display = null the current value will be toggled and saved.
2481 * @param int $type object of CALENDAR_EVENT_XXX
2482 * @param bool $display option to display event type
2483 * @param stdClass|int $user moodle user object or id, null means current user
2485 function calendar_set_event_type_display($type, $display = null, $user = null) {
2486 $persist = get_user_preferences('calendar_persistflt', 0, $user);
2487 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP
2488 + CALENDAR_EVENT_USER + CALENDAR_EVENT_COURSECAT;
2489 if ($persist === 0) {
2491 if (!isset($SESSION->calendarshoweventtype)) {
2492 $SESSION->calendarshoweventtype = $default;
2494 $preference = $SESSION->calendarshoweventtype;
2496 $preference = get_user_preferences('calendar_savedflt', $default, $user);
2498 $current = $preference & $type;
2499 if ($display === null) {
2500 $display = !$current;
2502 if ($display && !$current) {
2503 $preference += $type;
2504 } else if (!$display && $current) {
2505 $preference -= $type;
2507 if ($persist === 0) {
2508 $SESSION->calendarshoweventtype = $preference;
2510 if ($preference == $default) {
2511 unset_user_preference('calendar_savedflt', $user);
2513 set_user_preference('calendar_savedflt', $preference, $user);
2519 * Get calendar's allowed types.
2521 * @param stdClass $allowed list of allowed edit for event type
2522 * @param stdClass|int $course object of a course or course id
2523 * @param array $groups array of groups for the given course
2524 * @param stdClass|int $category object of a category
2526 function calendar_get_allowed_types(&$allowed, $course = null, $groups = null, $category = null) {
2529 $allowed = new \stdClass();
2530 $allowed->user = has_capability('moodle/calendar:manageownentries', \context_system::instance());
2531 $allowed->groups = false;
2532 $allowed->courses = false;
2533 $allowed->categories = false;
2534 $allowed->site = has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID));
2535 $getgroupsfunc = function($course, $context, $user) use ($groups) {
2536 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2537 if (has_capability('moodle/site:accessallgroups', $context)) {
2538 return is_null($groups) ? groups_get_all_groups($course->id) : $groups;
2540 if (is_null($groups)) {
2541 return groups_get_all_groups($course->id, $user->id);
2543 return array_filter($groups, function($group) use ($user) {
2544 return isset($group->members[$user->id]);
2553 if (!empty($course)) {
2554 if (!is_object($course)) {
2555 $course = $DB->get_record('course', array('id' => $course), 'id, groupmode, groupmodeforce', MUST_EXIST);
2557 if ($course->id != SITEID) {
2558 $coursecontext = \context_course::instance($course->id);
2559 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
2561 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2562 $allowed->courses = array($course->id => 1);
2563 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2564 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
2565 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2570 if (!empty($category)) {
2571 $catcontext = \context_coursecat::instance($category->id);
2572 if (has_capability('moodle/category:manage', $catcontext)) {
2573 $allowed->categories = [$category->id => 1];
2579 * Get all of the allowed types for all of the courses and groups
2580 * the logged in user belongs to.
2582 * The returned array will optionally have 5 keys:
2583 * 'user' : true if the logged in user can create user events
2584 * 'site' : true if the logged in user can create site events
2585 * 'category' : array of course categories that the user can create events for
2586 * 'course' : array of courses that the user can create events for
2587 * 'group': array of groups that the user can create events for
2588 * 'groupcourses' : array of courses that the groups belong to (can
2589 * be different from the list in 'course'.
2591 * @return array The array of allowed types.
2593 function calendar_get_all_allowed_types() {
2594 global $CFG, $USER, $DB;
2596 require_once($CFG->libdir . '/enrollib.php');
2600 $allowed = new stdClass();
2602 calendar_get_allowed_types($allowed);
2604 if ($allowed->user) {
2605 $types['user'] = true;
2608 if ($allowed->site) {
2609 $types['site'] = true;
2612 if (coursecat::has_manage_capability_on_any()) {
2613 $types['category'] = coursecat::make_categories_list('moodle/category:manage');
2616 // This function warms the context cache for the course so the calls
2617 // to load the course context in calendar_get_allowed_types don't result
2618 // in additional DB queries.
2619 $courses = calendar_get_default_courses(null, 'id, groupmode, groupmodeforce', true);
2621 // We want to pre-fetch all of the groups for each course in a single
2622 // query to avoid calendar_get_allowed_types from hitting the DB for
2623 // each separate course.
2624 $groups = groups_get_all_groups_for_courses($courses);
2626 foreach ($courses as $course) {
2627 $coursegroups = isset($groups[$course->id]) ? $groups[$course->id] : null;
2628 calendar_get_allowed_types($allowed, $course, $coursegroups);
2630 if (!empty($allowed->courses)) {
2631 $types['course'][$course->id] = $course;
2634 if (!empty($allowed->groups)) {
2635 $types['groupcourses'][$course->id] = $course;
2637 if (!isset($types['group'])) {
2638 $types['group'] = array_values($allowed->groups);
2640 $types['group'] = array_merge($types['group'], array_values($allowed->groups));
2649 * See if user can add calendar entries at all used to print the "New Event" button.
2651 * @param stdClass $course object of a course or course id
2652 * @return bool has the capability to add at least one event type
2654 function calendar_user_can_add_event($course) {
2655 if (!isloggedin() || isguestuser()) {
2659 calendar_get_allowed_types($allowed, $course);
2661 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->categories || $allowed->site);
2665 * Check wether the current user is permitted to add events.
2667 * @param stdClass $event object of event
2668 * @return bool has the capability to add event
2670 function calendar_add_event_allowed($event) {
2673 // Can not be using guest account.
2674 if (!isloggedin() or isguestuser()) {
2678 $sitecontext = \context_system::instance();
2680 // If user has manageentries at site level, always return true.
2681 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2685 switch ($event->eventtype) {
2687 return has_capability('moodle/category:manage', $event->context);
2689 return has_capability('moodle/calendar:manageentries', $event->context);
2691 // Allow users to add/edit group events if -
2692 // 1) They have manageentries (= entries for whole course).
2693 // 2) They have managegroupentries AND are in the group.
2694 $group = $DB->get_record('groups', array('id' => $event->groupid));
2696 has_capability('moodle/calendar:manageentries', $event->context) ||
2697 (has_capability('moodle/calendar:managegroupentries', $event->context)
2698 && groups_is_member($event->groupid)));
2700 if ($event->userid == $USER->id) {
2701 return (has_capability('moodle/calendar:manageownentries', $event->context));
2703 // There is intentionally no 'break'.
2705 return has_capability('moodle/calendar:manageentries', $event->context);
2707 return has_capability('moodle/calendar:manageentries', $event->context);
2712 * Returns option list for the poll interval setting.
2714 * @return array An array of poll interval options. Interval => description.
2716 function calendar_get_pollinterval_choices() {
2718 '0' => new \lang_string('never', 'calendar'),
2719 HOURSECS => new \lang_string('hourly', 'calendar'),
2720 DAYSECS => new \lang_string('daily', 'calendar'),
2721 WEEKSECS => new \lang_string('weekly', 'calendar'),
2722 '2628000' => new \lang_string('monthly', 'calendar'),
2723 YEARSECS => new \lang_string('annually', 'calendar')
2728 * Returns option list of available options for the calendar event type, given the current user and course.
2730 * @param int $courseid The id of the course
2731 * @return array An array containing the event types the user can create.
2733 function calendar_get_eventtype_choices($courseid) {
2735 $allowed = new \stdClass;
2736 calendar_get_allowed_types($allowed, $courseid);
2738 if ($allowed->user) {
2739 $choices['user'] = get_string('userevents', 'calendar');
2741 if ($allowed->site) {
2742 $choices['site'] = get_string('siteevents', 'calendar');
2744 if (!empty($allowed->courses)) {
2745 $choices['course'] = get_string('courseevents', 'calendar');
2747 if (!empty($allowed->categories)) {
2748 $choices['category'] = get_string('categoryevents', 'calendar');
2750 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2751 $choices['group'] = get_string('group');
2754 return array($choices, $allowed->groups);
2758 * Add an iCalendar subscription to the database.
2760 * @param stdClass $sub The subscription object (e.g. from the form)
2761 * @return int The insert ID, if any.
2763 function calendar_add_subscription($sub) {
2764 global $DB, $USER, $SITE;
2766 // Undo the form definition work around to allow us to have two different
2767 // course selectors present depending on which event type the user selects.
2768 if (!empty($sub->groupcourseid)) {
2769 $sub->courseid = $sub->groupcourseid;
2770 unset($sub->groupcourseid);
2773 // Pull the group id back out of the value. The form saves the value
2774 // as "<courseid>-<groupid>" to allow the javascript to work correctly.
2775 if (!empty($sub->groupid)) {
2776 list($courseid, $groupid) = explode('-', $sub->groupid);
2777 $sub->courseid = $courseid;
2778 $sub->groupid = $groupid;
2781 // Default course id if none is set.
2782 if (empty($sub->courseid)) {
2783 if ($sub->eventtype === 'site') {
2784 $sub->courseid = SITEID;
2790 if ($sub->eventtype === 'site') {
2791 $sub->courseid = $SITE->id;
2792 } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
2793 $sub->courseid = $sub->courseid;
2794 } else if ($sub->eventtype === 'category') {
2795 $sub->categoryid = $sub->categoryid;
2800 $sub->userid = $USER->id;
2802 // File subscriptions never update.
2803 if (empty($sub->url)) {
2804 $sub->pollinterval = 0;
2807 if (!empty($sub->name)) {
2808 if (empty($sub->id)) {
2809 $id = $DB->insert_record('event_subscriptions', $sub);
2810 // We cannot cache the data here because $sub is not complete.
2812 // Trigger event, calendar subscription added.
2813 $eventparams = array('objectid' => $sub->id,
2814 'context' => calendar_get_calendar_context($sub),
2816 'eventtype' => $sub->eventtype,
2819 switch ($sub->eventtype) {
2821 $eventparams['other']['categoryid'] = $sub->categoryid;
2824 $eventparams['other']['courseid'] = $sub->courseid;
2827 $eventparams['other']['courseid'] = $sub->courseid;
2828 $eventparams['other']['groupid'] = $sub->groupid;
2831 $eventparams['other']['courseid'] = $sub->courseid;
2834 $event = \core\event\calendar_subscription_created::create($eventparams);
2838 // Why are we doing an update here?
2839 calendar_update_subscription($sub);
2843 print_error('errorbadsubscription', 'importcalendar');
2848 * Add an iCalendar event to the Moodle calendar.
2850 * @param stdClass $event The RFC-2445 iCalendar event
2851 * @param int $unused Deprecated
2852 * @param int $subscriptionid The iCalendar subscription ID
2853 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2854 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2855 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2857 function calendar_add_icalendar_event($event, $unused = null, $subscriptionid, $timezone='UTC') {
2860 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2861 if (empty($event->properties['SUMMARY'])) {
2865 $name = $event->properties['SUMMARY'][0]->value;
2866 $name = str_replace('\n', '<br />', $name);
2867 $name = str_replace('\\', '', $name);
2868 $name = preg_replace('/\s+/u', ' ', $name);
2870 $eventrecord = new \stdClass;
2871 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
2873 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2876 $description = $event->properties['DESCRIPTION'][0]->value;
2877 $description = clean_param($description, PARAM_NOTAGS);
2878 $description = str_replace('\n', '<br />', $description);
2879 $description = str_replace('\\', '', $description);
2880 $description = preg_replace('/\s+/u', ' ', $description);
2882 $eventrecord->description = $description;
2884 // Probably a repeating event with RRULE etc. TODO: skip for now.
2885 if (empty($event->properties['DTSTART'][0]->value)) {
2889 if (isset($event->properties['DTSTART'][0]->parameters['TZID'])) {
2890 $tz = $event->properties['DTSTART'][0]->parameters['TZID'];
2894 $tz = \core_date::normalise_timezone($tz);
2895 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value . ' ' . $tz);
2896 if (empty($event->properties['DTEND'])) {
2897 $eventrecord->timeduration = 0; // No duration if no end time specified.
2899 if (isset($event->properties['DTEND'][0]->parameters['TZID'])) {
2900 $endtz = $event->properties['DTEND'][0]->parameters['TZID'];
2904 $endtz = \core_date::normalise_timezone($endtz);
2905 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value . ' ' . $endtz) - $eventrecord->timestart;
2908 // Check to see if it should be treated as an all day event.
2909 if ($eventrecord->timeduration == DAYSECS) {
2910 // Check to see if the event started at Midnight on the imported calendar.
2911 date_default_timezone_set($timezone);
2912 if (date('H:i:s', $eventrecord->timestart) === "00:00:00") {
2913 // This event should be an all day event. This is not correct, we don't do anything differently for all day events.
2915 $eventrecord->timeduration = 0;
2917 \core_date::set_default_server_timezone();
2920 $eventrecord->uuid = $event->properties['UID'][0]->value;
2921 $eventrecord->timemodified = time();
2923 // Add the iCal subscription details if required.
2924 // We should never do anything with an event without a subscription reference.
2925 $sub = calendar_get_subscription($subscriptionid);
2926 $eventrecord->subscriptionid = $subscriptionid;
2927 $eventrecord->userid = $sub->userid;
2928 $eventrecord->groupid = $sub->groupid;
2929 $eventrecord->courseid = $sub->courseid;
2930 $eventrecord->categoryid = $sub->categoryid;
2931 $eventrecord->eventtype = $sub->eventtype;
2933 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid,
2934 'subscriptionid' => $eventrecord->subscriptionid))) {
2935 $eventrecord->id = $updaterecord->id;
2936 $return = CALENDAR_IMPORT_EVENT_UPDATED; // Update.
2938 $return = CALENDAR_IMPORT_EVENT_INSERTED; // Insert.
2940 if ($createdevent = \calendar_event::create($eventrecord, false)) {
2941 if (!empty($event->properties['RRULE'])) {
2942 // Repeating events.
2943 date_default_timezone_set($tz); // Change time zone to parse all events.
2944 $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
2945 $rrule->parse_rrule();
2946 $rrule->create_events($createdevent);
2947 \core_date::set_default_server_timezone(); // Change time zone back to what it was.
2956 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2958 * @param int $subscriptionid The ID of the subscription we are acting upon.
2959 * @param int $pollinterval The poll interval to use.
2960 * @param int $action The action to be performed. One of update or remove.
2961 * @throws dml_exception if invalid subscriptionid is provided
2962 * @return string A log of the import progress, including errors
2964 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2965 // Fetch the subscription from the database making sure it exists.
2966 $sub = calendar_get_subscription($subscriptionid);
2968 // Update or remove the subscription, based on action.
2970 case CALENDAR_SUBSCRIPTION_UPDATE:
2971 // Skip updating file subscriptions.
2972 if (empty($sub->url)) {
2975 $sub->pollinterval = $pollinterval;
2976 calendar_update_subscription($sub);
2978 // Update the events.
2979 return "<p>" . get_string('subscriptionupdated', 'calendar', $sub->name) . "</p>" .
2980 calendar_update_subscription_events($subscriptionid);
2981 case CALENDAR_SUBSCRIPTION_REMOVE:
2982 calendar_delete_subscription($subscriptionid);
2983 return get_string('subscriptionremoved', 'calendar', $sub->name);
2992 * Delete subscription and all related events.
2994 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
2996 function calendar_delete_subscription($subscription) {
2999 if (!is_object($subscription)) {
3000 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST);
3003 // Delete subscription and related events.
3004 $DB->delete_records('event', array('subscriptionid' => $subscription->id));
3005 $DB->delete_records('event_subscriptions', array('id' => $subscription->id));
3006 \cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id));
3008 // Trigger event, calendar subscription deleted.
3009 $eventparams = array('objectid' => $subscription->id,
3010 'context' => calendar_get_calendar_context($subscription),
3012 'eventtype' => $subscription->eventtype,
3015 switch ($subscription->eventtype) {
3017 $eventparams['other']['categoryid'] = $subscription->categoryid;
3020 $eventparams['other']['courseid'] = $subscription->courseid;
3023 $eventparams['other']['courseid'] = $subscription->courseid;
3024 $eventparams['other']['groupid'] = $subscription->groupid;
3027 $eventparams['other']['courseid'] = $subscription->courseid;
3029 $event = \core\event\calendar_subscription_deleted::create($eventparams);
3034 * From a URL, fetch the calendar and return an iCalendar object.
3036 * @param string $url The iCalendar URL
3037 * @return iCalendar The iCalendar object
3039 function calendar_get_icalendar($url) {
3042 require_once($CFG->libdir . '/filelib.php');
3044 $curl = new \curl();
3045 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
3046 $calendar = $curl->get($url);
3048 // Http code validation should actually be the job of curl class.
3049 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
3050 throw new \moodle_exception('errorinvalidicalurl', 'calendar');
3053 $ical = new \iCalendar();
3054 $ical->unserialize($calendar);
3060 * Import events from an iCalendar object into a course calendar.
3062 * @param iCalendar $ical The iCalendar object.
3063 * @param int $courseid The course ID for the calendar.
3064 * @param int $subscriptionid The subscription ID.
3065 * @return string A log of the import progress, including errors.
3067 function calendar_import_icalendar_events($ical, $unused = null, $subscriptionid = null) {
3074 // Large calendars take a while...
3076 \core_php_time_limit::raise(300);
3079 // Mark all events in a subscription with a zero timestamp.
3080 if (!empty($subscriptionid)) {
3081 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
3082 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3085 // Grab the timezone from the iCalendar file to be used later.
3086 if (isset($ical->properties['X-WR-TIMEZONE'][0]->value)) {
3087 $timezone = $ical->properties['X-WR-TIMEZONE'][0]->value;
3093 foreach ($ical->components['VEVENT'] as $event) {
3094 $res = calendar_add_icalendar_event($event, null, $subscriptionid, $timezone);
3096 case CALENDAR_IMPORT_EVENT_UPDATED:
3099 case CALENDAR_IMPORT_EVENT_INSERTED:
3103 $return .= '<p>' . get_string('erroraddingevent', 'calendar') . ': ';
3104 if (empty($event->properties['SUMMARY'])) {
3105 $return .= '(' . get_string('notitle', 'calendar') . ')';
3107 $return .= $event->properties['SUMMARY'][0]->value;
3109 $return .= "</p>\n";
3114 $return .= "<p>" . get_string('eventsimported', 'calendar', $eventcount) . "</p> ";
3115 $return .= "<p>" . get_string('eventsupdated', 'calendar', $updatecount) . "</p>";
3117 // Delete remaining zero-marked events since they're not in remote calendar.
3118 if (!empty($subscriptionid)) {
3119 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3120 if (!empty($deletecount)) {
3121 $DB->delete_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3122 $return .= "<p> " . get_string('eventsdeleted', 'calendar') . ": {$deletecount} </p>\n";
3130 * Fetch a calendar subscription and update the events in the calendar.
3132 * @param int $subscriptionid The course ID for the calendar.
3133 * @return string A log of the import progress, including errors.
3135 function calendar_update_subscription_events($subscriptionid) {
3136 $sub = calendar_get_subscription($subscriptionid);
3138 // Don't update a file subscription.
3139 if (empty($sub->url)) {
3140 return 'File subscription not updated.';
3143 $ical = calendar_get_icalendar($sub->url);
3144 $return = calendar_import_icalendar_events($ical, null, $subscriptionid);
3145 $sub->lastupdated = time();
3147 calendar_update_subscription($sub);
3153 * Update a calendar subscription. Also updates the associated cache.
3155 * @param stdClass|array $subscription Subscription record.
3156 * @throws coding_exception If something goes wrong
3159 function calendar_update_subscription($subscription) {
3162 if (is_array($subscription)) {
3163 $subscription = (object)$subscription;
3165 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
3166 throw new \coding_exception('Cannot update a subscription without a valid id');
3169 $DB->update_record('event_subscriptions', $subscription);
3172 $cache = \cache::make('core', 'calendar_subscriptions');
3173 $cache->set($subscription->id, $subscription);
3175 // Trigger event, calendar subscription updated.
3176 $eventparams = array('userid' => $subscription->userid,
3177 'objectid' => $subscription->id,
3178 'context' => calendar_get_calendar_context($subscription),
3180 'eventtype' => $subscription->eventtype,
3183 switch ($subscription->eventtype) {
3185 $eventparams['other']['categoryid'] = $subscription->categoryid;
3188 $eventparams['other']['courseid'] = $subscription->courseid;
3191 $eventparams['other']['courseid'] = $subscription->courseid;
3192 $eventparams['other']['groupid'] = $subscription->groupid;
3195 $eventparams['other']['courseid'] = $subscription->courseid;
3197 $event = \core\event\calendar_subscription_updated::create($eventparams);
3202 * Checks to see if the user can edit a given subscription feed.
3204 * @param mixed $subscriptionorid Subscription object or id
3205 * @return bool true if current user can edit the subscription else false
3207 function calendar_can_edit_subscription($subscriptionorid) {
3208 if (is_array($subscriptionorid)) {
3209 $subscription = (object)$subscriptionorid;
3210 } else if (is_object($subscriptionorid)) {
3211 $subscription = $subscriptionorid;
3213 $subscription = calendar_get_subscription($subscriptionorid);
3216 $allowed = new \stdClass;
3217 $courseid = $subscription->courseid;
3218 $categoryid = $subscription->categoryid;
3219 $groupid = $subscription->groupid;
3222 if (!empty($categoryid)) {
3223 $category = \coursecat::get($categoryid);
3225 calendar_get_allowed_types($allowed, $courseid, null, $category);
3226 switch ($subscription->eventtype) {
3228 return $allowed->user;
3230 if (isset($allowed->courses[$courseid])) {
3231 return $allowed->courses[$courseid];
3236 if (isset($allowed->categories[$categoryid])) {
3237 return $allowed->categories[$categoryid];
3242 return $allowed->site;
3244 if (isset($allowed->groups[$groupid])) {
3245 return $allowed->groups[$groupid];
3255 * Helper function to determine the context of a calendar subscription.
3256 * Subscriptions can be created in two contexts COURSE, or USER.
3258 * @param stdClass $subscription
3259 * @return context instance
3261 function calendar_get_calendar_context($subscription) {
3262 // Determine context based on calendar type.
3263 if ($subscription->eventtype === 'site') {
3264 $context = \context_course::instance(SITEID);
3265 } else if ($subscription->eventtype === 'group' || $subscription->eventtype === 'course') {
3266 $context = \context_course::instance($subscription->courseid);
3268 $context = \context_user::instance($subscription->userid);
3274 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
3276 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3280 function core_calendar_user_preferences() {
3282 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED, 'default' => '0',
3283 'choices' => array('0', CALENDAR_TF_12, CALENDAR_TF_24)
3285 $preferences['calendar_startwday'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3286 'choices' => array(0, 1, 2, 3, 4, 5, 6));
3287 $preferences['calendar_maxevents'] = array('type' => PARAM_INT, 'choices' => range(1, 20));
3288 $preferences['calendar_lookahead'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 365,
3289 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3290 $preferences['calendar_persistflt'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3291 'choices' => array(0, 1));
3292 return $preferences;
3296 * Get legacy calendar events
3298 * @param int $tstart Start time of time range for events
3299 * @param int $tend End time of time range for events
3300 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3301 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3302 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3303 * @param boolean $withduration whether only events starting within time range selected
3304 * or events in progress/already started selected as well
3305 * @param boolean $ignorehidden whether to select only visible events or all events
3306 * @param array $categories array of category ids and/or objects.
3307 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3309 function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses,
3310 $withduration = true, $ignorehidden = true, $categories = []) {
3311 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3312 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3313 // parameters, but with the new API method, only null and arrays are accepted.
3314 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3315 // If parameter is true, return null.
3316 if ($param === true) {
3320 // If parameter is false, return an empty array.
3321 if ($param === false) {
3325 // If the parameter is a scalar value, enclose it in an array.
3326 if (!is_array($param)) {
3330 // No normalisation required.
3332 }, [$users, $groups, $courses, $categories]);
3334 $mapper = \core_calendar\local\event\container::get_event_mapper();
3335 $events = \core_calendar\local\api::get_events(
3352 return array_reduce($events, function($carry, $event) use ($mapper) {
3353 return $carry + [$event->get_id() => $mapper->from_event_to_stdclass($event)];
3359 * Get the calendar view output.
3361 * @param \calendar_information $calendar The calendar being represented
3362 * @param string $view The type of calendar to have displayed
3363 * @param bool $includenavigation Whether to include navigation
3364 * @param bool $skipevents Whether to load the events or not
3365 * @return array[array, string]
3367 function calendar_get_view(\calendar_information $calendar, $view, $includenavigation = true, bool $skipevents = false) {
3370 $renderer = $PAGE->get_renderer('core_calendar');
3371 $type = \core_calendar\type_factory::get_calendar_instance();
3373 // Calculate the bounds of the month.
3374 $calendardate = $type->timestamp_to_date_array($calendar->time);
3376 $date = new \DateTime('now', core_date::get_user_timezone_object(99));
3379 if ($view === 'day') {
3380 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday']);
3381 $date->setTimestamp($tstart);
3382 $date->modify('+1 day');
3383 } else if ($view === 'upcoming' || $view === 'upcoming_mini') {
3384 // Number of days in the future that will be used to fetch events.
3385 if (isset($CFG->calendar_lookahead)) {
3386 $defaultlookahead = intval($CFG->calendar_lookahead);
3388 $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD;
3390 $lookahead = get_user_preferences('calendar_lookahead', $defaultlookahead);
3392 // Maximum number of events to be displayed on upcoming view.
3393 $defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS;
3394 if (isset($CFG->calendar_maxevents)) {
3395 $defaultmaxevents = intval($CFG->calendar_maxevents);
3397 $eventlimit = get_user_preferences('calendar_maxevents', $defaultmaxevents);
3399 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday'],
3400 $calendardate['hours']);
3401 $date->setTimestamp($tstart);
3402 $date->modify('+' . $lookahead . ' days');
3404 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], 1);
3405 $monthdays = $type->get_num_days_in_month($calendardate['year'], $calendardate['mon']);
3406 $date->setTimestamp($tstart);
3407 $date->modify('+' . $monthdays . ' days');
3409 if ($view === 'mini' || $view === 'minithree') {
3410 $template = 'core_calendar/calendar_mini';
3412 $template = 'core_calendar/calendar_month';
3416 // We need to extract 1 second to ensure that we don't get into the next day.
3417 $date->modify('-1 second');
3418 $tend = $date->getTimestamp();
3420 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3421 // If parameter is true, return null.
3422 if ($param === true) {
3426 // If parameter is false, return an empty array.
3427 if ($param === false) {
3431 // If the parameter is a scalar value, enclose it in an array.
3432 if (!is_array($param)) {
3436 // No normalisation required.
3438 }, [$calendar->users, $calendar->groups, $calendar->courses, $calendar->categories]);
3443 $events = \core_calendar\local\api::get_events(
3459 if ($proxy = $event->get_course_module()) {
3460 $cminfo = $proxy->get_proxied_instance();
3461 return $cminfo->uservisible;
3464 if ($proxy = $event->get_category()) {
3465 $category = $proxy->get_proxied_instance();
3467 return $category->is_uservisible();
3476 'events' => $events,
3477 'cache' => new \core_calendar\external\events_related_objects_cache($events),
3482 if ($view == "month" || $view == "mini" || $view == "minithree") {
3483 $month = new \core_calendar\external\month_exporter($calendar, $type, $related);
3484 $month->set_includenavigation($includenavigation);
3485 $month->set_initialeventsloaded(!$skipevents);
3486 $data = $month->export($renderer);
3487 } else if ($view == "day") {
3488 $day = new \core_calendar\external\calendar_day_exporter($calendar, $related);
3489 $data = $day->export($renderer);
3490 $template = 'core_calendar/calendar_day';
3491 } else if ($view == "upcoming" || $view == "upcoming_mini") {
3492 $upcoming = new \core_calendar\external\calendar_upcoming_exporter($calendar, $related);
3493 $data = $upcoming->export($renderer);
3495 if ($view == "upcoming") {
3496 $template = 'core_calendar/calendar_upcoming';
3497 } else if ($view == "upcoming_mini") {
3498 $template = 'core_calendar/calendar_upcoming_mini';
3502 return [$data, $template];
3506 * Request and render event form fragment.
3508 * @param array $args The fragment arguments.
3509 * @return string The rendered mform fragment.
3511 function calendar_output_fragment_event_form($args) {
3512 global $CFG, $OUTPUT, $USER;
3516 $eventid = isset($args['eventid']) ? clean_param($args['eventid'], PARAM_INT) : null;
3517 $starttime = isset($args['starttime']) ? clean_param($args['starttime'], PARAM_INT) : null;
3518 $courseid = isset($args['courseid']) ? clean_param($args['courseid'], PARAM_INT) : null;
3519 $categoryid = isset($args['categoryid']) ? clean_param($args['categoryid'], PARAM_INT) : null;
3521 $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
3522 $context = \context_user::instance($USER->id);
3523 $editoroptions = \core_calendar\local\event\forms\create::build_editor_options($context);