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;
253 if (empty($data->context)) {
254 $this->properties->context = $this->calculate_context();
261 * Attempts to call a set_$key method if one exists otherwise falls back
262 * to simply set the property.
264 * @param string $key property name
265 * @param mixed $value value of the property
267 public function __set($key, $value) {
268 if (method_exists($this, 'set_'.$key)) {
269 $this->{'set_'.$key}($value);
271 $this->properties->{$key} = $value;
277 * Attempts to call a get_$key method to return the property and ralls over
278 * to return the raw property.
280 * @param string $key property name
281 * @return mixed property value
282 * @throws \coding_exception
284 public function __get($key) {
285 if (method_exists($this, 'get_'.$key)) {
286 return $this->{'get_'.$key}();
288 if (!property_exists($this->properties, $key)) {
289 throw new \coding_exception('Undefined property requested');
291 return $this->properties->{$key};
295 * Magic isset method.
297 * PHP needs an isset magic method if you use the get magic method and
298 * still want empty calls to work.
300 * @param string $key $key property name
301 * @return bool|mixed property value, false if property is not exist
303 public function __isset($key) {
304 return !empty($this->properties->{$key});
308 * Calculate the context value needed for an event.
310 * Event's type can be determine by the available value store in $data
311 * It is important to check for the existence of course/courseid to determine
313 * Default value is set to CONTEXT_USER
315 * @return \stdClass The context object.
317 protected function calculate_context() {
321 if (isset($this->properties->courseid) && $this->properties->courseid > 0) {
322 $context = \context_course::instance($this->properties->courseid);
323 } else if (isset($this->properties->course) && $this->properties->course > 0) {
324 $context = \context_course::instance($this->properties->course);
325 } else if (isset($this->properties->groupid) && $this->properties->groupid > 0) {
326 $group = $DB->get_record('groups', array('id' => $this->properties->groupid));
327 $context = \context_course::instance($group->courseid);
328 } else if (isset($this->properties->userid) && $this->properties->userid > 0
329 && $this->properties->userid == $USER->id) {
330 $context = \context_user::instance($this->properties->userid);
331 } else if (isset($this->properties->userid) && $this->properties->userid > 0
332 && $this->properties->userid != $USER->id &&
333 isset($this->properties->instance) && $this->properties->instance > 0) {
334 $cm = get_coursemodule_from_instance($this->properties->modulename, $this->properties->instance, 0,
336 $context = \context_course::instance($cm->course);
338 $context = \context_user::instance($this->properties->userid);
345 * Returns an array of editoroptions for this event.
347 * @return array event editor options
349 protected function get_editoroptions() {
350 return $this->editoroptions;
354 * Returns an event description: Called by __get
355 * Please use $blah = $event->description;
357 * @return string event description
359 protected function get_description() {
362 require_once($CFG->libdir . '/filelib.php');
364 if ($this->_description === null) {
365 // Check if we have already resolved the context for this event.
366 if ($this->editorcontext === null) {
367 // Switch on the event type to decide upon the appropriate context to use for this event.
368 $this->editorcontext = $this->properties->context;
369 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
370 return clean_text($this->properties->description, $this->properties->format);
374 // Work out the item id for the editor, if this is a repeated event
375 // then the files will be associated with the original.
376 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
377 $itemid = $this->properties->repeatid;
379 $itemid = $this->properties->id;
382 // Convert file paths in the description so that things display correctly.
383 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php',
384 $this->editorcontext->id, 'calendar', 'event_description', $itemid);
385 // Clean the text so no nasties get through.
386 $this->_description = clean_text($this->_description, $this->properties->format);
389 // Finally return the description.
390 return $this->_description;
394 * Return the number of repeat events there are in this events series.
396 * @return int number of event repeated
398 public function count_repeats() {
400 if (!empty($this->properties->repeatid)) {
401 $this->properties->eventrepeats = $DB->count_records('event',
402 array('repeatid' => $this->properties->repeatid));
403 // We don't want to count ourselves.
404 $this->properties->eventrepeats--;
406 return $this->properties->eventrepeats;
410 * Update or create an event within the database
412 * Pass in a object containing the event properties and this function will
413 * insert it into the database and deal with any associated files
415 * @see self::create()
416 * @see self::update()
418 * @param \stdClass $data object of event
419 * @param bool $checkcapability if moodle should check calendar managing capability or not
420 * @return bool event updated
422 public function update($data, $checkcapability=true) {
425 foreach ($data as $key => $value) {
426 $this->properties->$key = $value;
429 $this->properties->timemodified = time();
430 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
432 // Prepare event data.
434 'context' => $this->properties->context,
435 'objectid' => $this->properties->id,
437 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
438 'timestart' => $this->properties->timestart,
439 'name' => $this->properties->name
443 if (empty($this->properties->id) || $this->properties->id < 1) {
445 if ($checkcapability) {
446 if (!calendar_add_event_allowed($this->properties)) {
447 print_error('nopermissiontoupdatecalendar');
452 switch ($this->properties->eventtype) {
454 $this->properties->courseid = 0;
455 $this->properties->course = 0;
456 $this->properties->groupid = 0;
457 $this->properties->userid = $USER->id;
460 $this->properties->courseid = SITEID;
461 $this->properties->course = SITEID;
462 $this->properties->groupid = 0;
463 $this->properties->userid = $USER->id;
466 $this->properties->groupid = 0;
467 $this->properties->userid = $USER->id;
470 $this->properties->groupid = 0;
471 $this->properties->category = 0;
472 $this->properties->userid = $USER->id;
475 $this->properties->userid = $USER->id;
478 // We should NEVER get here, but just incase we do lets fail gracefully.
479 $usingeditor = false;
483 // If we are actually using the editor, we recalculate the context because some default values
484 // were set when calculate_context() was called from the constructor.
486 $this->properties->context = $this->calculate_context();
487 $this->editorcontext = $this->properties->context;
490 $editor = $this->properties->description;
491 $this->properties->format = $this->properties->description['format'];
492 $this->properties->description = $this->properties->description['text'];
495 // Insert the event into the database.
496 $this->properties->id = $DB->insert_record('event', $this->properties);
499 $this->properties->description = file_save_draft_area_files(
501 $this->editorcontext->id,
504 $this->properties->id,
505 $this->editoroptions,
507 $this->editoroptions['forcehttps']);
508 $DB->set_field('event', 'description', $this->properties->description,
509 array('id' => $this->properties->id));
512 // Log the event entry.
513 $eventargs['objectid'] = $this->properties->id;
514 $eventargs['context'] = $this->properties->context;
515 $event = \core\event\calendar_event_created::create($eventargs);
518 $repeatedids = array();
520 if (!empty($this->properties->repeat)) {
521 $this->properties->repeatid = $this->properties->id;
522 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id' => $this->properties->id));
524 $eventcopy = clone($this->properties);
525 unset($eventcopy->id);
527 $timestart = new \DateTime('@' . $eventcopy->timestart);
528 $timestart->setTimezone(\core_date::get_user_timezone_object());
530 for ($i = 1; $i < $eventcopy->repeats; $i++) {
532 $timestart->add(new \DateInterval('P7D'));
533 $eventcopy->timestart = $timestart->getTimestamp();
535 // Get the event id for the log record.
536 $eventcopyid = $DB->insert_record('event', $eventcopy);
538 // If the context has been set delete all associated files.
540 $fs = get_file_storage();
541 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description',
542 $this->properties->id);
543 foreach ($files as $file) {
544 $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
548 $repeatedids[] = $eventcopyid;
551 $eventargs['objectid'] = $eventcopyid;
552 $eventargs['other']['timestart'] = $eventcopy->timestart;
553 $event = \core\event\calendar_event_created::create($eventargs);
561 if ($checkcapability) {
562 if (!calendar_edit_event_allowed($this->properties)) {
563 print_error('nopermissiontoupdatecalendar');
568 if ($this->editorcontext !== null) {
569 $this->properties->description = file_save_draft_area_files(
570 $this->properties->description['itemid'],
571 $this->editorcontext->id,
574 $this->properties->id,
575 $this->editoroptions,
576 $this->properties->description['text'],
577 $this->editoroptions['forcehttps']);
579 $this->properties->format = $this->properties->description['format'];
580 $this->properties->description = $this->properties->description['text'];
584 $event = $DB->get_record('event', array('id' => $this->properties->id));
586 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
588 if ($updaterepeated) {
590 if ($this->properties->timestart != $event->timestart) {
591 $timestartoffset = $this->properties->timestart - $event->timestart;
592 $sql = "UPDATE {event}
595 timestart = timestart + ?,
599 $params = array($this->properties->name, $this->properties->description, $timestartoffset,
600 $this->properties->timeduration, time(), $event->repeatid);
602 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
603 $params = array($this->properties->name, $this->properties->description,
604 $this->properties->timeduration, time(), $event->repeatid);
606 $DB->execute($sql, $params);
608 // Trigger an update event for each of the calendar event.
609 $events = $DB->get_records('event', array('repeatid' => $event->repeatid), '', '*');
610 foreach ($events as $calendarevent) {
611 $eventargs['objectid'] = $calendarevent->id;
612 $eventargs['other']['timestart'] = $calendarevent->timestart;
613 $event = \core\event\calendar_event_updated::create($eventargs);
614 $event->add_record_snapshot('event', $calendarevent);
618 $DB->update_record('event', $this->properties);
619 $event = self::load($this->properties->id);
620 $this->properties = $event->properties();
622 // Trigger an update event.
623 $event = \core\event\calendar_event_updated::create($eventargs);
624 $event->add_record_snapshot('event', $this->properties);
633 * Deletes an event and if selected an repeated events in the same series
635 * This function deletes an event, any associated events if $deleterepeated=true,
636 * and cleans up any files associated with the events.
638 * @see self::delete()
640 * @param bool $deleterepeated delete event repeatedly
641 * @return bool succession of deleting event
643 public function delete($deleterepeated = false) {
646 // If $this->properties->id is not set then something is wrong.
647 if (empty($this->properties->id)) {
648 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
651 $calevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
653 $DB->delete_records('event', array('id' => $this->properties->id));
655 // Trigger an event for the delete action.
657 'context' => $this->properties->context,
658 'objectid' => $this->properties->id,
660 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
661 'timestart' => $this->properties->timestart,
662 'name' => $this->properties->name
664 $event = \core\event\calendar_event_deleted::create($eventargs);
665 $event->add_record_snapshot('event', $calevent);
668 // If we are deleting parent of a repeated event series, promote the next event in the series as parent.
669 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
670 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC",
671 array($this->properties->id), IGNORE_MULTIPLE);
672 if (!empty($newparent)) {
673 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?",
674 array($newparent, $this->properties->id));
675 // Get all records where the repeatid is the same as the event being removed.
676 $events = $DB->get_records('event', array('repeatid' => $newparent));
677 // For each of the returned events trigger an update event.
678 foreach ($events as $calendarevent) {
679 // Trigger an event for the update.
680 $eventargs['objectid'] = $calendarevent->id;
681 $eventargs['other']['timestart'] = $calendarevent->timestart;
682 $event = \core\event\calendar_event_updated::create($eventargs);
683 $event->add_record_snapshot('event', $calendarevent);
689 // If the editor context hasn't already been set then set it now.
690 if ($this->editorcontext === null) {
691 $this->editorcontext = $this->properties->context;
694 // If the context has been set delete all associated files.
695 if ($this->editorcontext !== null) {
696 $fs = get_file_storage();
697 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
698 foreach ($files as $file) {
703 // If we need to delete repeated events then we will fetch them all and delete one by one.
704 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
705 // Get all records where the repeatid is the same as the event being removed.
706 $events = $DB->get_records('event', array('repeatid' => $this->properties->repeatid));
707 // For each of the returned events populate an event object and call delete.
708 // make sure the arg passed is false as we are already deleting all repeats.
709 foreach ($events as $event) {
710 $event = new calendar_event($event);
711 $event->delete(false);
719 * Fetch all event properties.
721 * This function returns all of the events properties as an object and optionally
722 * can prepare an editor for the description field at the same time. This is
723 * designed to work when the properties are going to be used to set the default
724 * values of a moodle forms form.
726 * @param bool $prepareeditor If set to true a editor is prepared for use with
727 * the mforms editor element. (for description)
728 * @return \stdClass Object containing event properties
730 public function properties($prepareeditor = false) {
733 // First take a copy of the properties. We don't want to actually change the
734 // properties or we'd forever be converting back and forwards between an
735 // editor formatted description and not.
736 $properties = clone($this->properties);
737 // Clean the description here.
738 $properties->description = clean_text($properties->description, $properties->format);
740 // If set to true we need to prepare the properties for use with an editor
741 // and prepare the file area.
742 if ($prepareeditor) {
744 // We may or may not have a property id. If we do then we need to work
745 // out the context so we can copy the existing files to the draft area.
746 if (!empty($properties->id)) {
748 if ($properties->eventtype === 'site') {
750 $this->editorcontext = $this->properties->context;
751 } else if ($properties->eventtype === 'user') {
753 $this->editorcontext = $this->properties->context;
754 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
755 // First check the course is valid.
756 $course = $DB->get_record('course', array('id' => $properties->courseid));
758 print_error('invalidcourse');
761 $this->editorcontext = $this->properties->context;
762 // We have a course and are within the course context so we had
763 // better use the courses max bytes value.
764 $this->editoroptions['maxbytes'] = $course->maxbytes;
765 } else if ($properties->eventtype === 'category') {
766 // First check the course is valid.
767 \coursecat::get($properties->categoryid, MUST_EXIST, true);
769 $this->editorcontext = $this->properties->context;
770 // We have a course and are within the course context so we had
771 // better use the courses max bytes value.
772 $this->editoroptions['maxbytes'] = $course->maxbytes;
774 // If we get here we have a custom event type as used by some
775 // modules. In this case the event will have been added by
776 // code and we won't need the editor.
777 $this->editoroptions['maxbytes'] = 0;
778 $this->editoroptions['maxfiles'] = 0;
781 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
784 // Get the context id that is what we really want.
785 $contextid = $this->editorcontext->id;
789 // If we get here then this is a new event in which case we don't need a
790 // context as there is no existing files to copy to the draft area.
794 // If the contextid === false we don't support files so no preparing
796 if ($contextid !== false) {
797 // Just encase it has already been submitted.
798 $draftiddescription = file_get_submitted_draft_itemid('description');
799 // Prepare the draft area, this copies existing files to the draft area as well.
800 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar',
801 'event_description', $properties->id, $this->editoroptions, $properties->description);
803 $draftiddescription = 0;
806 // Structure the description field as the editor requires.
807 $properties->description = array('text' => $properties->description, 'format' => $properties->format,
808 'itemid' => $draftiddescription);
811 // Finally return the properties.
816 * Toggles the visibility of an event
818 * @param null|bool $force If it is left null the events visibility is flipped,
819 * If it is false the event is made hidden, if it is true it
821 * @return bool if event is successfully updated, toggle will be visible
823 public function toggle_visibility($force = null) {
826 // Set visible to the default if it is not already set.
827 if (empty($this->properties->visible)) {
828 $this->properties->visible = 1;
831 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
832 // Make this event visible.
833 $this->properties->visible = 1;
835 // Make this event hidden.
836 $this->properties->visible = 0;
839 // Update the database to reflect this change.
840 $success = $DB->set_field('event', 'visible', $this->properties->visible, array('id' => $this->properties->id));
841 $calendarevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
843 // Prepare event data.
845 'context' => $this->properties->context,
846 'objectid' => $this->properties->id,
848 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
849 'timestart' => $this->properties->timestart,
850 'name' => $this->properties->name
853 $event = \core\event\calendar_event_updated::create($eventargs);
854 $event->add_record_snapshot('event', $calendarevent);
861 * Returns an event object when provided with an event id.
863 * This function makes use of MUST_EXIST, if the event id passed in is invalid
864 * it will result in an exception being thrown.
866 * @param int|object $param event object or event id
867 * @return calendar_event
869 public static function load($param) {
871 if (is_object($param)) {
872 $event = new calendar_event($param);
874 $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST);
875 $event = new calendar_event($event);
881 * Creates a new event and returns an event object
883 * @param \stdClass|array $properties An object containing event properties
884 * @param bool $checkcapability Check caps or not
885 * @throws \coding_exception
887 * @return calendar_event|bool The event object or false if it failed
889 public static function create($properties, $checkcapability = true) {
890 if (is_array($properties)) {
891 $properties = (object)$properties;
893 if (!is_object($properties)) {
894 throw new \coding_exception('When creating an event properties should be either an object or an assoc array');
896 $event = new calendar_event($properties);
897 if ($event->update($properties, $checkcapability)) {
905 * Format the text using the external API.
907 * This function should we used when text formatting is required in external functions.
909 * @return array an array containing the text formatted and the text format
911 public function format_external_text() {
913 if ($this->editorcontext === null) {
914 // Switch on the event type to decide upon the appropriate context to use for this event.
915 $this->editorcontext = $this->properties->context;
917 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
918 // We don't have a context here, do a normal format_text.
919 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id);
923 // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
924 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
925 $itemid = $this->properties->repeatid;
927 $itemid = $this->properties->id;
930 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id,
931 'calendar', 'event_description', $itemid);
936 * Calendar information class
938 * This class is used simply to organise the information pertaining to a calendar
939 * and is used primarily to make information easily available.
941 * @package core_calendar
943 * @copyright 2010 Sam Hemelryk
944 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
946 class calendar_information {
949 * @var int The timestamp
951 * Rather than setting the day, month and year we will set a timestamp which will be able
952 * to be used by multiple calendars.
956 /** @var int A course id */
957 public $courseid = null;
959 /** @var array An array of categories */
960 public $categories = array();
962 /** @var int The current category */
963 public $categoryid = null;
965 /** @var array An array of courses */
966 public $courses = array();
968 /** @var array An array of groups */
969 public $groups = array();
971 /** @var array An array of users */
972 public $users = array();
975 * Creates a new instance
977 * @param int $day the number of the day
978 * @param int $month the number of the month
979 * @param int $year the number of the year
980 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
981 * and $calyear to support multiple calendars
983 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
984 // If a day, month and year were passed then convert it to a timestamp. If these were passed
985 // then we can assume the day, month and year are passed as Gregorian, as no where in core
986 // should we be passing these values rather than the time. This is done for BC.
987 if (!empty($day) || !empty($month) || !empty($year)) {
988 $date = usergetdate(time());
990 $day = $date['mday'];
993 $month = $date['mon'];
996 $year = $date['year'];
998 if (checkdate($month, $day, $year)) {
999 $time = make_timestamp($year, $month, $day);
1005 $this->set_time($time);
1009 * Set the time period of this instance.
1011 * @param int $time the unixtimestamp representing the date we want to view.
1014 public function set_time($time = null) {
1015 if ($time === null) {
1016 $this->time = time();
1018 $this->time = $time;
1025 * Initialize calendar information
1028 * @param stdClass $course object
1029 * @param array $coursestoload An array of courses [$course->id => $course]
1030 * @param bool $ignorefilters options to use filter
1032 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
1033 debugging('The prepare_for_view() function has been deprecated. Please update your code to use set_sources()',
1035 $this->set_sources($course, $coursestoload);
1039 * Set the sources for events within the calendar.
1041 * If no category is provided, then the category path for the current
1042 * course will be used.
1044 * @param stdClass $course The current course being viewed.
1045 * @param int[] $courses The list of all courses currently accessible.
1046 * @param stdClass $category The current category to show.
1048 public function set_sources(stdClass $course, array $courses, stdClass $category = null) {
1049 // A cousre must always be specified.
1050 $this->course = $course;
1051 $this->courseid = $course->id;
1053 list($courseids, $group, $user) = calendar_set_filters($courses);
1054 $this->courses = $courseids;
1055 $this->groups = $group;
1056 $this->users = $user;
1058 // Do not show category events by default.
1059 $this->categoryid = null;
1060 $this->categories = null;
1062 if (null !== $category) {
1063 // A specific category was requested - set the current category, and include all parents of that category.
1064 $category = \coursecat::get($category->id);
1065 $this->categoryid = $category->id;
1067 $this->categories = $category->get_parents();
1068 $this->categories[] = $category->id;
1069 } else if (SITEID === $this->courseid) {
1070 // This is the site.
1071 // Show categories for all courses the user has access to.
1072 $this->categories = true;
1074 foreach ($courses as $course) {
1075 $category = \coursecat::get($course->category);
1076 $categories = array_merge($categories, $category->get_parents());
1077 $categories[] = $category->id;
1080 // And all categories that the user can manage.
1081 foreach (\coursecat::get_all() as $category) {
1082 if (!$category->has_manage_capability()) {
1086 $categories = array_merge($categories, $category->get_parents());
1087 $categories[] = $category->id;
1090 $this->categories = array_unique($categories);
1095 * Ensures the date for the calendar is correct and either sets it to now
1096 * or throws a moodle_exception if not
1098 * @param bool $defaultonow use current time
1099 * @throws moodle_exception
1100 * @return bool validation of checkdate
1102 public function checkdate($defaultonow = true) {
1103 if (!checkdate($this->month, $this->day, $this->year)) {
1105 $now = usergetdate(time());
1106 $this->day = intval($now['mday']);
1107 $this->month = intval($now['mon']);
1108 $this->year = intval($now['year']);
1111 throw new moodle_exception('invaliddate');
1118 * Gets todays timestamp for the calendar
1120 * @return int today timestamp
1122 public function timestamp_today() {
1126 * Gets tomorrows timestamp for the calendar
1128 * @return int tomorrow timestamp
1130 public function timestamp_tomorrow() {
1131 return strtotime('+1 day', $this->time);
1134 * Adds the pretend blocks for the calendar
1136 * @param core_calendar_renderer $renderer
1137 * @param bool $showfilters display filters, false is set as default
1138 * @param string|null $view preference view options (eg: day, month, upcoming)
1140 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
1142 $filters = new block_contents();
1143 $filters->content = $renderer->event_filter();
1144 $filters->footer = '';
1145 $filters->title = get_string('eventskey', 'calendar');
1146 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
1148 $block = new block_contents;
1149 $block->content = $renderer->fake_block_threemonths($this);
1150 $block->footer = '';
1151 $block->title = get_string('monthlyview', 'calendar');
1152 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
1157 * Get calendar events.
1159 * @param int $tstart Start time of time range for events
1160 * @param int $tend End time of time range for events
1161 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
1162 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
1163 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
1164 * @param boolean $withduration whether only events starting within time range selected
1165 * or events in progress/already started selected as well
1166 * @param boolean $ignorehidden whether to select only visible events or all events
1167 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
1169 function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
1175 if (empty($users) && empty($groups) && empty($courses)) {
1179 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
1180 // Events from a number of users
1181 if(!empty($whereclause)) $whereclause .= ' OR';
1182 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED);
1183 $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0)";
1184 $params = array_merge($params, $inparamsusers);
1185 } else if($users === true) {
1186 // Events from ALL users
1187 if(!empty($whereclause)) $whereclause .= ' OR';
1188 $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0)';
1189 } else if($users === false) {
1190 // No user at all, do nothing
1193 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
1194 // Events from a number of groups
1195 if(!empty($whereclause)) $whereclause .= ' OR';
1196 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED);
1197 $whereclause .= " e.groupid $insqlgroups ";
1198 $params = array_merge($params, $inparamsgroups);
1199 } else if($groups === true) {
1200 // Events from ALL groups
1201 if(!empty($whereclause)) $whereclause .= ' OR ';
1202 $whereclause .= ' e.groupid != 0';
1204 // boolean false (no groups at all): we don't need to do anything
1206 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
1207 if(!empty($whereclause)) $whereclause .= ' OR';
1208 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED);
1209 $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
1210 $params = array_merge($params, $inparamscourses);
1211 } else if ($courses === true) {
1212 // Events from ALL courses
1213 if(!empty($whereclause)) $whereclause .= ' OR';
1214 $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
1217 // Security check: if, by now, we have NOTHING in $whereclause, then it means
1218 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
1219 // events no matter what. Allowing the code to proceed might return a completely
1220 // valid query with only time constraints, thus selecting ALL events in that time frame!
1221 if(empty($whereclause)) {
1226 $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1229 $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1231 if(!empty($whereclause)) {
1232 // We have additional constraints
1233 $whereclause = $timeclause.' AND ('.$whereclause.')';
1236 // Just basic time filtering
1237 $whereclause = $timeclause;
1240 if ($ignorehidden) {
1241 $whereclause .= ' AND e.visible = 1';
1246 LEFT JOIN {modules} m ON e.modulename = m.name
1247 -- Non visible modules will have a value of 0.
1248 WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
1249 ORDER BY e.timestart";
1250 $events = $DB->get_records_sql($sql, $params);
1252 if ($events === false) {
1259 * Return the days of the week.
1261 * @return array array of days
1263 function calendar_get_days() {
1264 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1265 return $calendartype->get_weekdays();
1269 * Get the subscription from a given id.
1272 * @param int $id id of the subscription
1273 * @return stdClass Subscription record from DB
1274 * @throws moodle_exception for an invalid id
1276 function calendar_get_subscription($id) {
1279 $cache = \cache::make('core', 'calendar_subscriptions');
1280 $subscription = $cache->get($id);
1281 if (empty($subscription)) {
1282 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
1283 $cache->set($id, $subscription);
1286 return $subscription;
1290 * Gets the first day of the week.
1292 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
1296 function calendar_get_starting_weekday() {
1297 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1298 return $calendartype->get_starting_weekday();
1302 * Gets the calendar upcoming event.
1304 * @param array $courses array of courses
1305 * @param array|int|bool $groups array of groups, group id or boolean for all/no group events
1306 * @param array|int|bool $users array of users, user id or boolean for all/no user events
1307 * @param int $daysinfuture number of days in the future we 'll look
1308 * @param int $maxevents maximum number of events
1309 * @param int $fromtime start time
1310 * @return array $output array of upcoming events
1312 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
1315 $display = new \stdClass;
1316 $display->range = $daysinfuture; // How many days in the future we 'll look.
1317 $display->maxevents = $maxevents;
1322 $now = time(); // We 'll need this later.
1323 $usermidnighttoday = usergetmidnight($now);
1326 $display->tstart = $fromtime;
1328 $display->tstart = $usermidnighttoday;
1331 // This works correctly with respect to the user's DST, but it is accurate
1332 // only because $fromtime is always the exact midnight of some day!
1333 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
1335 // Get the events matching our criteria.
1336 $events = calendar_get_legacy_events($display->tstart, $display->tend, $users, $groups, $courses);
1338 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
1339 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
1340 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
1341 // arguments to this function.
1342 $hrefparams = array();
1343 if (!empty($courses)) {
1344 $courses = array_diff($courses, array(SITEID));
1345 if (count($courses) == 1) {
1346 $hrefparams['course'] = reset($courses);
1350 if ($events !== false) {
1351 foreach ($events as $event) {
1352 if (!empty($event->modulename)) {
1353 $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
1354 if (empty($instances[$event->instance]->uservisible)) {
1359 if ($processed >= $display->maxevents) {
1363 $event->time = calendar_format_event_time($event, $now, $hrefparams);
1373 * Get a HTML link to a course.
1375 * @param int|stdClass $course the course id or course object
1376 * @return string a link to the course (as HTML); empty if the course id is invalid
1378 function calendar_get_courselink($course) {
1383 if (!is_object($course)) {
1384 $course = calendar_get_course_cached($coursecache, $course);
1386 $context = \context_course::instance($course->id);
1387 $fullname = format_string($course->fullname, true, array('context' => $context));
1388 $url = new \moodle_url('/course/view.php', array('id' => $course->id));
1389 $link = \html_writer::link($url, $fullname);
1395 * Get current module cache.
1397 * Only use this method if you do not know courseid. Otherwise use:
1398 * get_fast_modinfo($courseid)->instances[$modulename][$instance]
1400 * @param array $modulecache in memory module cache
1401 * @param string $modulename name of the module
1402 * @param int $instance module instance number
1403 * @return stdClass|bool $module information
1405 function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
1406 if (!isset($modulecache[$modulename . '_' . $instance])) {
1407 $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
1410 return $modulecache[$modulename . '_' . $instance];
1414 * Get current course cache.
1416 * @param array $coursecache list of course cache
1417 * @param int $courseid id of the course
1418 * @return stdClass $coursecache[$courseid] return the specific course cache
1420 function calendar_get_course_cached(&$coursecache, $courseid) {
1421 if (!isset($coursecache[$courseid])) {
1422 $coursecache[$courseid] = get_course($courseid);
1424 return $coursecache[$courseid];
1428 * Get group from groupid for calendar display
1430 * @param int $groupid
1431 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1433 function calendar_get_group_cached($groupid) {
1434 static $groupscache = array();
1435 if (!isset($groupscache[$groupid])) {
1436 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1438 return $groupscache[$groupid];
1442 * Add calendar event metadata
1444 * @param stdClass $event event info
1445 * @return stdClass $event metadata
1447 function calendar_add_event_metadata($event) {
1448 global $CFG, $OUTPUT;
1450 // Support multilang in event->name.
1451 $event->name = format_string($event->name, true);
1453 if (!empty($event->modulename)) { // Activity event.
1454 // The module name is set. I will assume that it has to be displayed, and
1455 // also that it is an automatically-generated event. And of course that the
1456 // instace id and modulename are set correctly.
1457 $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
1458 if (!array_key_exists($event->instance, $instances)) {
1461 $module = $instances[$event->instance];
1463 $modulename = $module->get_module_type_name(false);
1464 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
1465 // Will be used as alt text if the event icon.
1466 $eventtype = get_string($event->eventtype, $event->modulename);
1471 $event->icon = '<img src="' . s($module->get_icon_url()) . '" alt="' . s($eventtype) .
1472 '" title="' . s($modulename) . '" class="icon" />';
1473 $event->referer = html_writer::link($module->url, $event->name);
1474 $event->courselink = calendar_get_courselink($module->get_course());
1475 $event->cmid = $module->id;
1476 } else if ($event->courseid == SITEID) { // Site event.
1477 $event->icon = '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
1478 get_string('globalevent', 'calendar') . '" class="icon" />';
1479 $event->cssclass = 'calendar_event_global';
1480 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event.
1481 $event->icon = '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
1482 get_string('courseevent', 'calendar') . '" class="icon" />';
1483 $event->courselink = calendar_get_courselink($event->courseid);
1484 $event->cssclass = 'calendar_event_course';
1485 } else if ($event->groupid) { // Group event.
1486 if ($group = calendar_get_group_cached($event->groupid)) {
1487 $groupname = format_string($group->name, true, \context_course::instance($group->courseid));
1491 $event->icon = \html_writer::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
1492 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
1493 $event->courselink = calendar_get_courselink($event->courseid) . ', ' . $groupname;
1494 $event->cssclass = 'calendar_event_group';
1495 } else if ($event->userid) { // User event.
1496 $event->icon = '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
1497 get_string('userevent', 'calendar') . '" class="icon" />';
1498 $event->cssclass = 'calendar_event_user';
1505 * Get calendar events by id.
1508 * @param array $eventids list of event ids
1509 * @return array Array of event entries, empty array if nothing found
1511 function calendar_get_events_by_id($eventids) {
1514 if (!is_array($eventids) || empty($eventids)) {
1518 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
1519 $wheresql = "id $wheresql";
1521 return $DB->get_records_select('event', $wheresql, $params);
1525 * Get control options for calendar.
1527 * @param string $type of calendar
1528 * @param array $data calendar information
1529 * @return string $content return available control for the calender in html
1531 function calendar_top_controls($type, $data) {
1532 global $PAGE, $OUTPUT;
1534 // Get the calendar type we are using.
1535 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1539 // Ensure course id passed if relevant.
1541 if (!empty($data['id'])) {
1542 $courseid = '&course=' . $data['id'];
1545 // If we are passing a month and year then we need to convert this to a timestamp to
1546 // support multiple calendars. No where in core should these be passed, this logic
1547 // here is for third party plugins that may use this function.
1548 if (!empty($data['m']) && !empty($date['y'])) {
1549 if (!isset($data['d'])) {
1552 if (!checkdate($data['m'], $data['d'], $data['y'])) {
1555 $time = make_timestamp($data['y'], $data['m'], $data['d']);
1557 } else if (!empty($data['time'])) {
1558 $time = $data['time'];
1563 // Get the date for the calendar type.
1564 $date = $calendartype->timestamp_to_date_array($time);
1566 $urlbase = $PAGE->url;
1568 // We need to get the previous and next months in certain cases.
1569 if ($type == 'frontpage' || $type == 'course' || $type == 'month') {
1570 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1571 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
1572 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
1573 $prevmonthtime['hour'], $prevmonthtime['minute']);
1575 $nextmonth = calendar_add_month($date['mon'], $date['year']);
1576 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
1577 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
1578 $nextmonthtime['hour'], $nextmonthtime['minute']);
1583 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1584 true, $prevmonthtime);
1585 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true,
1587 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1588 false, false, false, $time);
1590 if (!empty($data['id'])) {
1591 $calendarlink->param('course', $data['id']);
1596 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1597 $content .= $prevlink . '<span class="hide"> | </span>';
1598 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1599 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1600 ), array('class' => 'current'));
1601 $content .= '<span class="hide"> | </span>' . $right;
1602 $content .= "<span class=\"clearer\"><!-- --></span>\n";
1603 $content .= \html_writer::end_tag('div');
1607 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1608 true, $prevmonthtime);
1609 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false,
1610 true, $nextmonthtime);
1611 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1612 false, false, false, $time);
1614 if (!empty($data['id'])) {
1615 $calendarlink->param('course', $data['id']);
1618 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1619 $content .= $prevlink . '<span class="hide"> | </span>';
1620 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1621 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1622 ), array('class' => 'current'));
1623 $content .= '<span class="hide"> | </span>' . $nextlink;
1624 $content .= "<span class=\"clearer\"><!-- --></span>";
1625 $content .= \html_writer::end_tag('div');
1628 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'upcoming')),
1629 false, false, false, $time);
1630 if (!empty($data['id'])) {
1631 $calendarlink->param('course', $data['id']);
1633 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1634 $content .= \html_writer::tag('div', $calendarlink, array('class' => 'centered'));
1637 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1638 false, false, false, $time);
1639 if (!empty($data['id'])) {
1640 $calendarlink->param('course', $data['id']);
1642 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1643 $content .= \html_writer::tag('h3', $calendarlink);
1646 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1647 'view.php?view=month' . $courseid . '&', false, false, false, false, $prevmonthtime);
1648 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1649 'view.php?view=month' . $courseid . '&', false, false, false, false, $nextmonthtime);
1651 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1652 $content .= $prevlink . '<span class="hide"> | </span>';
1653 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1654 $content .= '<span class="hide"> | </span>' . $nextlink;
1655 $content .= '<span class="clearer"><!-- --></span>';
1656 $content .= \html_writer::end_tag('div')."\n";
1659 $days = calendar_get_days();
1661 $prevtimestamp = strtotime('-1 day', $time);
1662 $nexttimestamp = strtotime('+1 day', $time);
1664 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1665 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1667 $prevname = $days[$prevdate['wday']]['fullname'];
1668 $nextname = $days[$nextdate['wday']]['fullname'];
1669 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&', false, false,
1670 false, false, $prevtimestamp);
1671 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&', false, false, false,
1672 false, $nexttimestamp);
1674 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1675 $content .= $prevlink;
1676 $content .= '<span class="hide"> | </span><span class="current">' .userdate($time,
1677 get_string('strftimedaydate')) . '</span>';
1678 $content .= '<span class="hide"> | </span>' . $nextlink;
1679 $content .= "<span class=\"clearer\"><!-- --></span>";
1680 $content .= \html_writer::end_tag('div') . "\n";
1689 * Return the representation day.
1691 * @param int $tstamp Timestamp in GMT
1692 * @param int|bool $now current Unix timestamp
1693 * @param bool $usecommonwords
1694 * @return string the formatted date/time
1696 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1697 static $shortformat;
1699 if (empty($shortformat)) {
1700 $shortformat = get_string('strftimedayshort');
1703 if ($now === false) {
1707 // To have it in one place, if a change is needed.
1708 $formal = userdate($tstamp, $shortformat);
1710 $datestamp = usergetdate($tstamp);
1711 $datenow = usergetdate($now);
1713 if ($usecommonwords == false) {
1714 // We don't want words, just a date.
1716 } else if ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1717 return get_string('today', 'calendar');
1718 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1719 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12
1720 && $datenow['yday'] == 1)) {
1721 return get_string('yesterday', 'calendar');
1722 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1723 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12
1724 && $datestamp['yday'] == 1)) {
1725 return get_string('tomorrow', 'calendar');
1732 * return the formatted representation time.
1735 * @param int $time the timestamp in UTC, as obtained from the database
1736 * @return string the formatted date/time
1738 function calendar_time_representation($time) {
1739 static $langtimeformat = null;
1741 if ($langtimeformat === null) {
1742 $langtimeformat = get_string('strftimetime');
1745 $timeformat = get_user_preferences('calendar_timeformat');
1746 if (empty($timeformat)) {
1747 $timeformat = get_config(null, 'calendar_site_timeformat');
1750 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
1754 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1756 * @param string|moodle_url $linkbase
1757 * @param int $d The number of the day.
1758 * @param int $m The number of the month.
1759 * @param int $y The number of the year.
1760 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1761 * $m and $y are kept for backwards compatibility.
1762 * @return moodle_url|null $linkbase
1764 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1765 if (empty($linkbase)) {
1769 if (!($linkbase instanceof \moodle_url)) {
1770 $linkbase = new \moodle_url($linkbase);
1773 $linkbase->param('time', calendar_get_timestamp($d, $m, $y, $time));
1779 * Build and return a previous month HTML link, with an arrow.
1781 * @param string $text The text label.
1782 * @param string|moodle_url $linkbase The URL stub.
1783 * @param int $d The number of the date.
1784 * @param int $m The number of the month.
1785 * @param int $y year The number of the year.
1786 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1787 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1788 * $m and $y are kept for backwards compatibility.
1789 * @return string HTML string.
1791 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1792 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1799 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1800 'data-drop-zone' => 'nav-link',
1803 return link_arrow_left($text, $href->out(false), $accesshide, 'previous', $attrs);
1807 * Build and return a next month HTML link, with an arrow.
1809 * @param string $text The text label.
1810 * @param string|moodle_url $linkbase The URL stub.
1811 * @param int $d the number of the Day
1812 * @param int $m The number of the month.
1813 * @param int $y The number of the year.
1814 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1815 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1816 * $m and $y are kept for backwards compatibility.
1817 * @return string HTML string.
1819 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1820 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1827 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1828 'data-drop-zone' => 'nav-link',
1831 return link_arrow_right($text, $href->out(false), $accesshide, 'next', $attrs);
1835 * Return the number of days in month.
1837 * @param int $month the number of the month.
1838 * @param int $year the number of the year
1841 function calendar_days_in_month($month, $year) {
1842 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1843 return $calendartype->get_num_days_in_month($year, $month);
1847 * Get the next following month.
1849 * @param int $month the number of the month.
1850 * @param int $year the number of the year.
1851 * @return array the following month
1853 function calendar_add_month($month, $year) {
1854 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1855 return $calendartype->get_next_month($year, $month);
1859 * Get the previous month.
1861 * @param int $month the number of the month.
1862 * @param int $year the number of the year.
1863 * @return array previous month
1865 function calendar_sub_month($month, $year) {
1866 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1867 return $calendartype->get_prev_month($year, $month);
1871 * Get per-day basis events
1873 * @param array $events list of events
1874 * @param int $month the number of the month
1875 * @param int $year the number of the year
1876 * @param array $eventsbyday event on specific day
1877 * @param array $durationbyday duration of the event in days
1878 * @param array $typesbyday event type (eg: global, course, user, or group)
1879 * @param array $courses list of courses
1882 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1883 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1885 $eventsbyday = array();
1886 $typesbyday = array();
1887 $durationbyday = array();
1889 if ($events === false) {
1893 foreach ($events as $event) {
1894 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
1895 if ($event->timeduration) {
1896 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
1898 $enddate = $startdate;
1901 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair.
1902 if (!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) &&
1903 ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1907 $eventdaystart = intval($startdate['mday']);
1909 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
1910 // Give the event to its day.
1911 $eventsbyday[$eventdaystart][] = $event->id;
1913 // Mark the day as having such an event.
1914 if ($event->courseid == SITEID && $event->groupid == 0) {
1915 $typesbyday[$eventdaystart]['startglobal'] = true;
1916 // Set event class for global event.
1917 $events[$event->id]->class = 'calendar_event_global';
1918 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1919 $typesbyday[$eventdaystart]['startcourse'] = true;
1920 // Set event class for course event.
1921 $events[$event->id]->class = 'calendar_event_course';
1922 } else if ($event->groupid) {
1923 $typesbyday[$eventdaystart]['startgroup'] = true;
1924 // Set event class for group event.
1925 $events[$event->id]->class = 'calendar_event_group';
1926 } else if ($event->userid) {
1927 $typesbyday[$eventdaystart]['startuser'] = true;
1928 // Set event class for user event.
1929 $events[$event->id]->class = 'calendar_event_user';
1933 if ($event->timeduration == 0) {
1934 // Proceed with the next.
1938 // The event starts on $month $year or before.
1939 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
1940 $lowerbound = intval($startdate['mday']);
1945 // Also, it ends on $month $year or later.
1946 if ($enddate['mon'] == $month && $enddate['year'] == $year) {
1947 $upperbound = intval($enddate['mday']);
1949 $upperbound = calendar_days_in_month($month, $year);
1952 // Mark all days between $lowerbound and $upperbound (inclusive) as duration.
1953 for ($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
1954 $durationbyday[$i][] = $event->id;
1955 if ($event->courseid == SITEID && $event->groupid == 0) {
1956 $typesbyday[$i]['durationglobal'] = true;
1957 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1958 $typesbyday[$i]['durationcourse'] = true;
1959 } else if ($event->groupid) {
1960 $typesbyday[$i]['durationgroup'] = true;
1961 } else if ($event->userid) {
1962 $typesbyday[$i]['durationuser'] = true;
1971 * Returns the courses to load events for.
1973 * @param array $courseeventsfrom An array of courses to load calendar events for
1974 * @param bool $ignorefilters specify the use of filters, false is set as default
1975 * @return array An array of courses, groups, and user to load calendar events for based upon filters
1977 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
1980 // For backwards compatability we have to check whether the courses array contains
1981 // just id's in which case we need to load course objects.
1982 $coursestoload = array();
1983 foreach ($courseeventsfrom as $id => $something) {
1984 if (!is_object($something)) {
1985 $coursestoload[] = $id;
1986 unset($courseeventsfrom[$id]);
1994 // Get the capabilities that allow seeing group events from all groups.
1995 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
1997 $isloggedin = isloggedin();
1999 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
2000 $courses = array_keys($courseeventsfrom);
2002 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
2003 $courses[] = SITEID;
2005 $courses = array_unique($courses);
2008 if (!empty($courses) && in_array(SITEID, $courses)) {
2009 // Sort courses for consistent colour highlighting.
2010 // Effectively ignoring SITEID as setting as last course id.
2011 $key = array_search(SITEID, $courses);
2012 unset($courses[$key]);
2013 $courses[] = SITEID;
2016 if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
2020 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
2022 if (count($courseeventsfrom) == 1) {
2023 $course = reset($courseeventsfrom);
2024 if (has_any_capability($allgroupscaps, \context_course::instance($course->id))) {
2025 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
2026 $group = array_keys($coursegroups);
2029 if ($group === false) {
2030 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, \context_system::instance())) {
2032 } else if ($isloggedin) {
2033 $groupids = array();
2034 foreach ($courseeventsfrom as $courseid => $course) {
2035 // If the user is an editing teacher in there.
2036 if (!empty($USER->groupmember[$course->id])) {
2037 // We've already cached the users groups for this course so we can just use that.
2038 $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
2039 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2040 // If this course has groups, show events from all of those related to the current user.
2041 $coursegroups = groups_get_user_groups($course->id, $USER->id);
2042 $groupids = array_merge($groupids, $coursegroups['0']);
2045 if (!empty($groupids)) {
2051 if (empty($courses)) {
2055 return array($courses, $group, $user);
2059 * Return the capability for editing calendar event.
2061 * @param calendar_event $event event object
2062 * @param bool $manualedit is the event being edited manually by the user
2063 * @return bool capability to edit event
2065 function calendar_edit_event_allowed($event, $manualedit = false) {
2068 // Must be logged in.
2069 if (!isloggedin()) {
2073 // Can not be using guest account.
2074 if (isguestuser()) {
2078 if ($manualedit && !empty($event->modulename)) {
2079 $hascallback = component_callback_exists(
2080 'mod_' . $event->modulename,
2081 'core_calendar_event_timestart_updated'
2084 if (!$hascallback) {
2085 // If the activity hasn't implemented the correct callback
2086 // to handle changes to it's events then don't allow any
2087 // manual changes to them.
2091 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2092 $hasmodule = isset($coursemodules[$event->modulename]);
2093 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2095 // If modinfo doesn't know about the module, return false to be safe.
2096 if (!$hasmodule || !$hasinstance) {
2100 $coursemodule = $coursemodules[$event->modulename][$event->instance];
2101 $context = context_module::instance($coursemodule->id);
2102 // This is the capability that allows a user to modify the activity
2103 // settings. Since the activity generated this event we need to check
2104 // that the current user has the same capability before allowing them
2105 // to update the event because the changes to the event will be
2106 // reflected within the activity.
2107 return has_capability('moodle/course:manageactivities', $context);
2110 // You cannot edit URL based calendar subscription events presently.
2111 if (!empty($event->subscriptionid)) {
2112 if (!empty($event->subscription->url)) {
2113 // This event can be updated externally, so it cannot be edited.
2118 $sitecontext = \context_system::instance();
2120 // If user has manageentries at site level, return true.
2121 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2125 // If groupid is set, it's definitely a group event.
2126 if (!empty($event->groupid)) {
2127 // Allow users to add/edit group events if -
2128 // 1) They have manageentries for the course OR
2129 // 2) They have managegroupentries AND are in the group.
2130 $group = $DB->get_record('groups', array('id' => $event->groupid));
2132 has_capability('moodle/calendar:manageentries', $event->context) ||
2133 (has_capability('moodle/calendar:managegroupentries', $event->context)
2134 && groups_is_member($event->groupid)));
2135 } else if (!empty($event->courseid)) {
2136 // If groupid is not set, but course is set, it's definiely a course event.
2137 return has_capability('moodle/calendar:manageentries', $event->context);
2138 } else if (!empty($event->userid) && $event->userid == $USER->id) {
2139 // If course is not set, but userid id set, it's a user event.
2140 return (has_capability('moodle/calendar:manageownentries', $event->context));
2141 } else if (!empty($event->userid)) {
2142 return (has_capability('moodle/calendar:manageentries', $event->context));
2149 * Return the capability for deleting a calendar event.
2151 * @param calendar_event $event The event object
2152 * @return bool Whether the user has permission to delete the event or not.
2154 function calendar_delete_event_allowed($event) {
2155 // Only allow delete if you have capabilities and it is not an module event.
2156 return (calendar_edit_event_allowed($event) && empty($event->modulename));
2160 * Returns the default courses to display on the calendar when there isn't a specific
2161 * course to display.
2163 * @return array $courses Array of courses to display
2165 function calendar_get_default_courses() {
2168 if (!isloggedin()) {
2172 if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', \context_system::instance())) {
2173 $select = ', ' . \context_helper::get_preload_record_columns_sql('ctx');
2174 $join = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
2175 $sql = "SELECT c.* $select
2178 WHERE EXISTS (SELECT 1 FROM {event} e WHERE e.courseid = c.id)
2180 $courses = $DB->get_records_sql($sql, array('contextlevel' => CONTEXT_COURSE), 0, 20);
2181 foreach ($courses as $course) {
2182 \context_helper::preload_from_record($course);
2187 $courses = enrol_get_my_courses();
2193 * Get event format time.
2195 * @param calendar_event $event event object
2196 * @param int $now current time in gmt
2197 * @param array $linkparams list of params for event link
2198 * @param bool $usecommonwords the words as formatted date/time.
2199 * @param int $showtime determine the show time GMT timestamp
2200 * @return string $eventtime link/string for event time
2202 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
2203 $starttime = $event->timestart;
2204 $endtime = $event->timestart + $event->timeduration;
2206 if (empty($linkparams) || !is_array($linkparams)) {
2207 $linkparams = array();
2210 $linkparams['view'] = 'day';
2212 // OK, now to get a meaningful display.
2213 // Check if there is a duration for this event.
2214 if ($event->timeduration) {
2215 // Get the midnight of the day the event will start.
2216 $usermidnightstart = usergetmidnight($starttime);
2217 // Get the midnight of the day the event will end.
2218 $usermidnightend = usergetmidnight($endtime);
2219 // Check if we will still be on the same day.
2220 if ($usermidnightstart == $usermidnightend) {
2221 // Check if we are running all day.
2222 if ($event->timeduration == DAYSECS) {
2223 $time = get_string('allday', 'calendar');
2224 } else { // Specify the time we will be running this from.
2225 $datestart = calendar_time_representation($starttime);
2226 $dateend = calendar_time_representation($endtime);
2227 $time = $datestart . ' <strong>»</strong> ' . $dateend;
2230 // Set printable representation.
2232 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2233 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2234 $eventtime = \html_writer::link($url, $day) . ', ' . $time;
2238 } else { // It must spans two or more days.
2239 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
2240 if ($showtime == $usermidnightstart) {
2243 $timestart = calendar_time_representation($event->timestart);
2244 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
2245 if ($showtime == $usermidnightend) {
2248 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
2250 // Set printable representation.
2251 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2252 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2253 $eventtime = $timestart . ' <strong>»</strong> ' . \html_writer::link($url, $dayend) . $timeend;
2255 // The event is in the future, print start and end links.
2256 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2257 $eventtime = \html_writer::link($url, $daystart) . $timestart . ' <strong>»</strong> ';
2259 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2260 $eventtime .= \html_writer::link($url, $dayend) . $timeend;
2263 } else { // There is no time duration.
2264 $time = calendar_time_representation($event->timestart);
2265 // Set printable representation.
2267 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2268 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2269 $eventtime = \html_writer::link($url, $day) . ', ' . trim($time);
2275 // Check if It has expired.
2276 if ($event->timestart + $event->timeduration < $now) {
2277 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2284 * Checks to see if the requested type of event should be shown for the given user.
2286 * @param int $type The type to check the display for (default is to display all)
2287 * @param stdClass|int|null $user The user to check for - by default the current user
2288 * @return bool True if the tyep should be displayed false otherwise
2290 function calendar_show_event_type($type, $user = null) {
2291 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
2293 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2295 if (!isset($SESSION->calendarshoweventtype)) {
2296 $SESSION->calendarshoweventtype = $default;
2298 return $SESSION->calendarshoweventtype & $type;
2300 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2305 * Sets the display of the event type given $display.
2307 * If $display = true the event type will be shown.
2308 * If $display = false the event type will NOT be shown.
2309 * If $display = null the current value will be toggled and saved.
2311 * @param int $type object of CALENDAR_EVENT_XXX
2312 * @param bool $display option to display event type
2313 * @param stdClass|int $user moodle user object or id, null means current user
2315 function calendar_set_event_type_display($type, $display = null, $user = null) {
2316 $persist = get_user_preferences('calendar_persistflt', 0, $user);
2317 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP
2318 + CALENDAR_EVENT_USER + CALENDAR_EVENT_COURSECAT;
2319 if ($persist === 0) {
2321 if (!isset($SESSION->calendarshoweventtype)) {
2322 $SESSION->calendarshoweventtype = $default;
2324 $preference = $SESSION->calendarshoweventtype;
2326 $preference = get_user_preferences('calendar_savedflt', $default, $user);
2328 $current = $preference & $type;
2329 if ($display === null) {
2330 $display = !$current;
2332 if ($display && !$current) {
2333 $preference += $type;
2334 } else if (!$display && $current) {
2335 $preference -= $type;
2337 if ($persist === 0) {
2338 $SESSION->calendarshoweventtype = $preference;
2340 if ($preference == $default) {
2341 unset_user_preference('calendar_savedflt', $user);
2343 set_user_preference('calendar_savedflt', $preference, $user);
2349 * Get calendar's allowed types.
2351 * @param stdClass $allowed list of allowed edit for event type
2352 * @param stdClass|int $course object of a course or course id
2353 * @param array $groups array of groups for the given course
2354 * @param stdClass|int $category object of a category
2356 function calendar_get_allowed_types(&$allowed, $course = null, $groups = null, $category = null) {
2359 $allowed = new \stdClass();
2360 $allowed->user = has_capability('moodle/calendar:manageownentries', \context_system::instance());
2361 $allowed->groups = false;
2362 $allowed->courses = false;
2363 $allowed->categories = false;
2364 $allowed->site = has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID));
2365 $getgroupsfunc = function($course, $context, $user) use ($groups) {
2366 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2367 if (has_capability('moodle/site:accessallgroups', $context)) {
2368 return is_null($groups) ? groups_get_all_groups($course->id) : $groups;
2370 if (is_null($groups)) {
2371 return groups_get_all_groups($course->id, $user->id);
2373 return array_filter($groups, function($group) use ($user) {
2374 return isset($group->members[$user->id]);
2383 if (!empty($course)) {
2384 if (!is_object($course)) {
2385 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST);
2387 if ($course->id != SITEID) {
2388 $coursecontext = \context_course::instance($course->id);
2389 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
2391 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2392 $allowed->courses = array($course->id => 1);
2393 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2394 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
2395 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2400 if (!empty($category)) {
2401 $catcontext = \context_coursecat::instance($category->id);
2402 if (has_capability('moodle/category:manage', $catcontext)) {
2403 $allowed->categories = [$category->id => 1];
2409 * Get all of the allowed types for all of the courses and groups
2410 * the logged in user belongs to.
2412 * The returned array will optionally have 5 keys:
2413 * 'user' : true if the logged in user can create user events
2414 * 'site' : true if the logged in user can create site events
2415 * 'category' : array of course categories that the user can create events for
2416 * 'course' : array of courses that the user can create events for
2417 * 'group': array of groups that the user can create events for
2418 * 'groupcourses' : array of courses that the groups belong to (can
2419 * be different from the list in 'course'.
2421 * @return array The array of allowed types.
2423 function calendar_get_all_allowed_types() {
2424 global $CFG, $USER, $DB;
2426 require_once($CFG->libdir . '/enrollib.php');
2430 calendar_get_allowed_types($allowed);
2432 if ($allowed->user) {
2433 $types['user'] = true;
2436 if ($allowed->site) {
2437 $types['site'] = true;
2440 if (coursecat::has_manage_capability_on_any()) {
2441 $types['category'] = coursecat::make_categories_list('moodle/category:manage');
2444 // This function warms the context cache for the course so the calls
2445 // to load the course context in calendar_get_allowed_types don't result
2446 // in additional DB queries.
2447 $courses = enrol_get_users_courses($USER->id, true);
2448 // We want to pre-fetch all of the groups for each course in a single
2449 // query to avoid calendar_get_allowed_types from hitting the DB for
2450 // each separate course.
2451 $groups = groups_get_all_groups_for_courses($courses);
2453 foreach ($courses as $course) {
2454 $coursegroups = isset($groups[$course->id]) ? $groups[$course->id] : null;
2455 calendar_get_allowed_types($allowed, $course, $coursegroups);
2457 if (!empty($allowed->courses)) {
2458 if (!isset($types['course'])) {
2459 $types['course'] = [$course];
2461 $types['course'][] = $course;
2465 if (!empty($allowed->groups)) {
2466 if (!isset($types['groupcourses'])) {
2467 $types['groupcourses'] = [$course];
2469 $types['groupcourses'][] = $course;
2472 if (!isset($types['group'])) {
2473 $types['group'] = array_values($allowed->groups);
2475 $types['group'] = array_merge($types['group'], array_values($allowed->groups));
2484 * See if user can add calendar entries at all used to print the "New Event" button.
2486 * @param stdClass $course object of a course or course id
2487 * @return bool has the capability to add at least one event type
2489 function calendar_user_can_add_event($course) {
2490 if (!isloggedin() || isguestuser()) {
2494 calendar_get_allowed_types($allowed, $course);
2496 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->category || $allowed->site);
2500 * Check wether the current user is permitted to add events.
2502 * @param stdClass $event object of event
2503 * @return bool has the capability to add event
2505 function calendar_add_event_allowed($event) {
2508 // Can not be using guest account.
2509 if (!isloggedin() or isguestuser()) {
2513 $sitecontext = \context_system::instance();
2515 // If user has manageentries at site level, always return true.
2516 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2520 switch ($event->eventtype) {
2522 return has_capability('moodle/category:manage', $event->context);
2524 return has_capability('moodle/calendar:manageentries', $event->context);
2526 // Allow users to add/edit group events if -
2527 // 1) They have manageentries (= entries for whole course).
2528 // 2) They have managegroupentries AND are in the group.
2529 $group = $DB->get_record('groups', array('id' => $event->groupid));
2531 has_capability('moodle/calendar:manageentries', $event->context) ||
2532 (has_capability('moodle/calendar:managegroupentries', $event->context)
2533 && groups_is_member($event->groupid)));
2535 if ($event->userid == $USER->id) {
2536 return (has_capability('moodle/calendar:manageownentries', $event->context));
2538 // There is intentionally no 'break'.
2540 return has_capability('moodle/calendar:manageentries', $event->context);
2542 return has_capability('moodle/calendar:manageentries', $event->context);
2547 * Returns option list for the poll interval setting.
2549 * @return array An array of poll interval options. Interval => description.
2551 function calendar_get_pollinterval_choices() {
2553 '0' => new \lang_string('never', 'calendar'),
2554 HOURSECS => new \lang_string('hourly', 'calendar'),
2555 DAYSECS => new \lang_string('daily', 'calendar'),
2556 WEEKSECS => new \lang_string('weekly', 'calendar'),
2557 '2628000' => new \lang_string('monthly', 'calendar'),
2558 YEARSECS => new \lang_string('annually', 'calendar')
2563 * Returns option list of available options for the calendar event type, given the current user and course.
2565 * @param int $courseid The id of the course
2566 * @return array An array containing the event types the user can create.
2568 function calendar_get_eventtype_choices($courseid) {
2570 $allowed = new \stdClass;
2571 calendar_get_allowed_types($allowed, $courseid);
2573 if ($allowed->user) {
2574 $choices['user'] = get_string('userevents', 'calendar');
2576 if ($allowed->site) {
2577 $choices['site'] = get_string('siteevents', 'calendar');
2579 if (!empty($allowed->courses)) {
2580 $choices['course'] = get_string('courseevents', 'calendar');
2582 if (!empty($allowed->categories)) {
2583 $choices['category'] = get_string('categoryevents', 'calendar');
2585 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2586 $choices['group'] = get_string('group');
2589 return array($choices, $allowed->groups);
2593 * Add an iCalendar subscription to the database.
2595 * @param stdClass $sub The subscription object (e.g. from the form)
2596 * @return int The insert ID, if any.
2598 function calendar_add_subscription($sub) {
2599 global $DB, $USER, $SITE;
2601 if ($sub->eventtype === 'site') {
2602 $sub->courseid = $SITE->id;
2603 } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
2604 $sub->courseid = $sub->course;
2605 } else if ($sub->eventtype === 'category') {
2606 $sub->categoryid = $sub->category;
2611 $sub->userid = $USER->id;
2613 // File subscriptions never update.
2614 if (empty($sub->url)) {
2615 $sub->pollinterval = 0;
2618 if (!empty($sub->name)) {
2619 if (empty($sub->id)) {
2620 $id = $DB->insert_record('event_subscriptions', $sub);
2621 // We cannot cache the data here because $sub is not complete.
2623 // Trigger event, calendar subscription added.
2624 $eventparams = array('objectid' => $sub->id,
2625 'context' => calendar_get_calendar_context($sub),
2626 'other' => array('eventtype' => $sub->eventtype, 'courseid' => $sub->courseid)
2628 $event = \core\event\calendar_subscription_created::create($eventparams);
2632 // Why are we doing an update here?
2633 calendar_update_subscription($sub);
2637 print_error('errorbadsubscription', 'importcalendar');
2642 * Add an iCalendar event to the Moodle calendar.
2644 * @param stdClass $event The RFC-2445 iCalendar event
2645 * @param int $courseid The course ID
2646 * @param int $subscriptionid The iCalendar subscription ID
2647 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2648 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2649 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2651 function calendar_add_icalendar_event($event, $courseid, $subscriptionid, $timezone='UTC') {
2654 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2655 if (empty($event->properties['SUMMARY'])) {
2659 $name = $event->properties['SUMMARY'][0]->value;
2660 $name = str_replace('\n', '<br />', $name);
2661 $name = str_replace('\\', '', $name);
2662 $name = preg_replace('/\s+/u', ' ', $name);
2664 $eventrecord = new \stdClass;
2665 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
2667 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2670 $description = $event->properties['DESCRIPTION'][0]->value;
2671 $description = clean_param($description, PARAM_NOTAGS);
2672 $description = str_replace('\n', '<br />', $description);
2673 $description = str_replace('\\', '', $description);
2674 $description = preg_replace('/\s+/u', ' ', $description);
2676 $eventrecord->description = $description;
2678 // Probably a repeating event with RRULE etc. TODO: skip for now.
2679 if (empty($event->properties['DTSTART'][0]->value)) {
2683 if (isset($event->properties['DTSTART'][0]->parameters['TZID'])) {
2684 $tz = $event->properties['DTSTART'][0]->parameters['TZID'];
2688 $tz = \core_date::normalise_timezone($tz);
2689 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value . ' ' . $tz);
2690 if (empty($event->properties['DTEND'])) {
2691 $eventrecord->timeduration = 0; // No duration if no end time specified.
2693 if (isset($event->properties['DTEND'][0]->parameters['TZID'])) {
2694 $endtz = $event->properties['DTEND'][0]->parameters['TZID'];
2698 $endtz = \core_date::normalise_timezone($endtz);
2699 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value . ' ' . $endtz) - $eventrecord->timestart;
2702 // Check to see if it should be treated as an all day event.
2703 if ($eventrecord->timeduration == DAYSECS) {
2704 // Check to see if the event started at Midnight on the imported calendar.
2705 date_default_timezone_set($timezone);
2706 if (date('H:i:s', $eventrecord->timestart) === "00:00:00") {
2707 // This event should be an all day event. This is not correct, we don't do anything differently for all day events.
2709 $eventrecord->timeduration = 0;
2711 \core_date::set_default_server_timezone();
2714 $eventrecord->uuid = $event->properties['UID'][0]->value;
2715 $eventrecord->timemodified = time();
2717 // Add the iCal subscription details if required.
2718 // We should never do anything with an event without a subscription reference.
2719 $sub = calendar_get_subscription($subscriptionid);
2720 $eventrecord->subscriptionid = $subscriptionid;
2721 $eventrecord->userid = $sub->userid;
2722 $eventrecord->groupid = $sub->groupid;
2723 $eventrecord->courseid = $sub->courseid;
2724 $eventrecord->eventtype = $sub->eventtype;
2726 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid,
2727 'subscriptionid' => $eventrecord->subscriptionid))) {
2728 $eventrecord->id = $updaterecord->id;
2729 $return = CALENDAR_IMPORT_EVENT_UPDATED; // Update.
2731 $return = CALENDAR_IMPORT_EVENT_INSERTED; // Insert.
2733 if ($createdevent = \calendar_event::create($eventrecord, false)) {
2734 if (!empty($event->properties['RRULE'])) {
2735 // Repeating events.
2736 date_default_timezone_set($tz); // Change time zone to parse all events.
2737 $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
2738 $rrule->parse_rrule();
2739 $rrule->create_events($createdevent);
2740 \core_date::set_default_server_timezone(); // Change time zone back to what it was.
2749 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2751 * @param int $subscriptionid The ID of the subscription we are acting upon.
2752 * @param int $pollinterval The poll interval to use.
2753 * @param int $action The action to be performed. One of update or remove.
2754 * @throws dml_exception if invalid subscriptionid is provided
2755 * @return string A log of the import progress, including errors
2757 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2758 // Fetch the subscription from the database making sure it exists.
2759 $sub = calendar_get_subscription($subscriptionid);
2761 // Update or remove the subscription, based on action.
2763 case CALENDAR_SUBSCRIPTION_UPDATE:
2764 // Skip updating file subscriptions.
2765 if (empty($sub->url)) {
2768 $sub->pollinterval = $pollinterval;
2769 calendar_update_subscription($sub);
2771 // Update the events.
2772 return "<p>" . get_string('subscriptionupdated', 'calendar', $sub->name) . "</p>" .
2773 calendar_update_subscription_events($subscriptionid);
2774 case CALENDAR_SUBSCRIPTION_REMOVE:
2775 calendar_delete_subscription($subscriptionid);
2776 return get_string('subscriptionremoved', 'calendar', $sub->name);
2785 * Delete subscription and all related events.
2787 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
2789 function calendar_delete_subscription($subscription) {
2792 if (!is_object($subscription)) {
2793 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST);
2796 // Delete subscription and related events.
2797 $DB->delete_records('event', array('subscriptionid' => $subscription->id));
2798 $DB->delete_records('event_subscriptions', array('id' => $subscription->id));
2799 \cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id));
2801 // Trigger event, calendar subscription deleted.
2802 $eventparams = array('objectid' => $subscription->id,
2803 'context' => calendar_get_calendar_context($subscription),
2804 'other' => array('courseid' => $subscription->courseid)
2806 $event = \core\event\calendar_subscription_deleted::create($eventparams);
2811 * From a URL, fetch the calendar and return an iCalendar object.
2813 * @param string $url The iCalendar URL
2814 * @return iCalendar The iCalendar object
2816 function calendar_get_icalendar($url) {
2819 require_once($CFG->libdir . '/filelib.php');
2821 $curl = new \curl();
2822 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
2823 $calendar = $curl->get($url);
2825 // Http code validation should actually be the job of curl class.
2826 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
2827 throw new \moodle_exception('errorinvalidicalurl', 'calendar');
2830 $ical = new \iCalendar();
2831 $ical->unserialize($calendar);
2837 * Import events from an iCalendar object into a course calendar.
2839 * @param iCalendar $ical The iCalendar object.
2840 * @param int $courseid The course ID for the calendar.
2841 * @param int $subscriptionid The subscription ID.
2842 * @return string A log of the import progress, including errors.
2844 function calendar_import_icalendar_events($ical, $courseid, $subscriptionid = null) {
2851 // Large calendars take a while...
2853 \core_php_time_limit::raise(300);
2856 // Mark all events in a subscription with a zero timestamp.
2857 if (!empty($subscriptionid)) {
2858 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
2859 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
2862 // Grab the timezone from the iCalendar file to be used later.
2863 if (isset($ical->properties['X-WR-TIMEZONE'][0]->value)) {
2864 $timezone = $ical->properties['X-WR-TIMEZONE'][0]->value;
2870 foreach ($ical->components['VEVENT'] as $event) {
2871 $res = calendar_add_icalendar_event($event, $courseid, $subscriptionid, $timezone);
2873 case CALENDAR_IMPORT_EVENT_UPDATED:
2876 case CALENDAR_IMPORT_EVENT_INSERTED:
2880 $return .= '<p>' . get_string('erroraddingevent', 'calendar') . ': ';
2881 if (empty($event->properties['SUMMARY'])) {
2882 $return .= '(' . get_string('notitle', 'calendar') . ')';
2884 $return .= $event->properties['SUMMARY'][0]->value;
2886 $return .= "</p>\n";
2891 $return .= "<p>" . get_string('eventsimported', 'calendar', $eventcount) . "</p> ";
2892 $return .= "<p>" . get_string('eventsupdated', 'calendar', $updatecount) . "</p>";
2894 // Delete remaining zero-marked events since they're not in remote calendar.
2895 if (!empty($subscriptionid)) {
2896 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
2897 if (!empty($deletecount)) {
2898 $DB->delete_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
2899 $return .= "<p> " . get_string('eventsdeleted', 'calendar') . ": {$deletecount} </p>\n";
2907 * Fetch a calendar subscription and update the events in the calendar.
2909 * @param int $subscriptionid The course ID for the calendar.
2910 * @return string A log of the import progress, including errors.
2912 function calendar_update_subscription_events($subscriptionid) {
2913 $sub = calendar_get_subscription($subscriptionid);
2915 // Don't update a file subscription.
2916 if (empty($sub->url)) {
2917 return 'File subscription not updated.';
2920 $ical = calendar_get_icalendar($sub->url);
2921 $return = calendar_import_icalendar_events($ical, $sub->courseid, $subscriptionid);
2922 $sub->lastupdated = time();
2924 calendar_update_subscription($sub);
2930 * Update a calendar subscription. Also updates the associated cache.
2932 * @param stdClass|array $subscription Subscription record.
2933 * @throws coding_exception If something goes wrong
2936 function calendar_update_subscription($subscription) {
2939 if (is_array($subscription)) {
2940 $subscription = (object)$subscription;
2942 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
2943 throw new \coding_exception('Cannot update a subscription without a valid id');
2946 $DB->update_record('event_subscriptions', $subscription);
2949 $cache = \cache::make('core', 'calendar_subscriptions');
2950 $cache->set($subscription->id, $subscription);
2952 // Trigger event, calendar subscription updated.
2953 $eventparams = array('userid' => $subscription->userid,
2954 'objectid' => $subscription->id,
2955 'context' => calendar_get_calendar_context($subscription),
2956 'other' => array('eventtype' => $subscription->eventtype, 'courseid' => $subscription->courseid)
2958 $event = \core\event\calendar_subscription_updated::create($eventparams);
2963 * Checks to see if the user can edit a given subscription feed.
2965 * @param mixed $subscriptionorid Subscription object or id
2966 * @return bool true if current user can edit the subscription else false
2968 function calendar_can_edit_subscription($subscriptionorid) {
2969 if (is_array($subscriptionorid)) {
2970 $subscription = (object)$subscriptionorid;
2971 } else if (is_object($subscriptionorid)) {
2972 $subscription = $subscriptionorid;
2974 $subscription = calendar_get_subscription($subscriptionorid);
2977 $allowed = new \stdClass;
2978 $courseid = $subscription->courseid;
2979 $groupid = $subscription->groupid;
2981 calendar_get_allowed_types($allowed, $courseid);
2982 switch ($subscription->eventtype) {
2984 return $allowed->user;
2986 if (isset($allowed->courses[$courseid])) {
2987 return $allowed->courses[$courseid];
2992 return $allowed->site;
2994 if (isset($allowed->groups[$groupid])) {
2995 return $allowed->groups[$groupid];
3005 * Helper function to determine the context of a calendar subscription.
3006 * Subscriptions can be created in two contexts COURSE, or USER.
3008 * @param stdClass $subscription
3009 * @return context instance
3011 function calendar_get_calendar_context($subscription) {
3012 // Determine context based on calendar type.
3013 if ($subscription->eventtype === 'site') {
3014 $context = \context_course::instance(SITEID);
3015 } else if ($subscription->eventtype === 'group' || $subscription->eventtype === 'course') {
3016 $context = \context_course::instance($subscription->courseid);
3018 $context = \context_user::instance($subscription->userid);
3024 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
3026 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3030 function core_calendar_user_preferences() {
3032 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED, 'default' => '0',
3033 'choices' => array('0', CALENDAR_TF_12, CALENDAR_TF_24)
3035 $preferences['calendar_startwday'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3036 'choices' => array(0, 1, 2, 3, 4, 5, 6));
3037 $preferences['calendar_maxevents'] = array('type' => PARAM_INT, 'choices' => range(1, 20));
3038 $preferences['calendar_lookahead'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 365,
3039 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3040 $preferences['calendar_persistflt'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3041 'choices' => array(0, 1));
3042 return $preferences;
3046 * Get legacy calendar events
3048 * @param int $tstart Start time of time range for events
3049 * @param int $tend End time of time range for events
3050 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3051 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3052 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3053 * @param boolean $withduration whether only events starting within time range selected
3054 * or events in progress/already started selected as well
3055 * @param boolean $ignorehidden whether to select only visible events or all events
3056 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3058 function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses,
3059 $withduration = true, $ignorehidden = true, $categories = []) {
3060 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3061 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3062 // parameters, but with the new API method, only null and arrays are accepted.
3063 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3064 // If parameter is true, return null.
3065 if ($param === true) {
3069 // If parameter is false, return an empty array.
3070 if ($param === false) {
3074 // If the parameter is a scalar value, enclose it in an array.
3075 if (!is_array($param)) {
3079 // No normalisation required.
3081 }, [$users, $groups, $courses, $categories]);
3083 $mapper = \core_calendar\local\event\container::get_event_mapper();
3084 $events = \core_calendar\local\api::get_events(
3101 return array_reduce($events, function($carry, $event) use ($mapper) {
3102 return $carry + [$event->get_id() => $mapper->from_event_to_stdclass($event)];
3108 * Get the calendar view output.
3110 * @param \calendar_information $calendar The calendar being represented
3111 * @param string $view The type of calendar to have displayed
3112 * @param bool $includenavigation Whether to include navigation
3113 * @return array[array, string]
3115 function calendar_get_view(\calendar_information $calendar, $view, $includenavigation = true) {
3118 $renderer = $PAGE->get_renderer('core_calendar');
3119 $type = \core_calendar\type_factory::get_calendar_instance();
3121 // Calculate the bounds of the month.
3122 $date = $type->timestamp_to_date_array($calendar->time);
3124 if ($view === 'day') {
3125 $tstart = $type->convert_to_timestamp($date['year'], $date['mon'], $date['mday']);
3126 $tend = $tstart + DAYSECS - 1;
3127 } else if ($view === 'upcoming') {
3128 if (isset($CFG->calendar_lookahead)) {
3129 $defaultlookahead = intval($CFG->calendar_lookahead);
3131 $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD;
3133 $tstart = $type->convert_to_timestamp($date['year'], $date['mon'], 1);
3134 $tend = $tstart + get_user_preferences('calendar_lookahead', $defaultlookahead);
3136 $tstart = $type->convert_to_timestamp($date['year'], $date['mon'], 1);
3137 $monthdays = $type->get_num_days_in_month($date['year'], $date['mon']);
3138 $tend = $tstart + ($monthdays * DAYSECS) - 1;
3139 $selectortitle = get_string('detailedmonthviewfor', 'calendar');
3140 if ($view === 'mini' || $view === 'minithree') {
3141 $template = 'core_calendar/calendar_mini';
3143 $template = 'core_calendar/calendar_month';
3147 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3148 // If parameter is true, return null.
3149 if ($param === true) {
3153 // If parameter is false, return an empty array.
3154 if ($param === false) {
3158 // If the parameter is a scalar value, enclose it in an array.
3159 if (!is_array($param)) {
3163 // No normalisation required.
3165 }, [$calendar->users, $calendar->groups, $calendar->courses, $calendar->categories]);
3167 $events = \core_calendar\local\api::get_events(
3183 if ($proxy = $event->get_course_module()) {
3184 $cminfo = $proxy->get_proxied_instance();
3185 return $cminfo->uservisible;
3194 'events' => $events,
3195 'cache' => new \core_calendar\external\events_related_objects_cache($events),
3200 if ($view == "month" || $view == "mini" || $view == "minithree") {
3201 $month = new \core_calendar\external\month_exporter($calendar, $type, $related);
3202 $month->set_includenavigation($includenavigation);
3203 $data = $month->export($renderer);
3204 } else if ($view == "day") {
3205 $daydata = $type->timestamp_to_date_array($tstart);
3206 $day = new \core_calendar\external\day_exporter($calendar, $daydata, $related);
3207 $data = $day->export($renderer);
3208 $template = 'core_calendar/day_detailed';
3211 return [$data, $template];
3215 * Request and render event form fragment.
3217 * @param array $args The fragment arguments.
3218 * @return string The rendered mform fragment.
3220 function calendar_output_fragment_event_form($args) {
3221 global $CFG, $OUTPUT, $USER;
3225 $eventid = isset($args['eventid']) ? clean_param($args['eventid'], PARAM_INT) : null;
3226 $starttime = isset($args['starttime']) ? clean_param($args['starttime'], PARAM_INT) : null;
3227 $courseid = isset($args['courseid']) ? clean_param($args['courseid'], PARAM_INT) : null;
3229 $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
3230 $context = \context_user::instance($USER->id);
3231 $editoroptions = \core_calendar\local\event\forms\create::build_editor_options($context);
3232 $formoptions = ['editoroptions' => $editoroptions];
3236 parse_str(clean_param($args['formdata'], PARAM_TEXT), $data);
3237 if (isset($data['description']['itemid'])) {
3238 $draftitemid = $data['description']['itemid'];
3243 $formoptions['starttime'] = $starttime;
3246 if (is_null($eventid)) {
3247 $mform = new \core_calendar\local\event\forms\create(
3256 if ($courseid != SITEID) {
3257 $data['eventtype'] = 'course';
3258 $data['courseid'] = $courseid;
3259 $data['groupcourseid'] = $courseid;
3261 $mform->set_data($data);
3263 $event = calendar_event::load($eventid);
3264 $mapper = new \core_calendar\local\event\mappers\create_update_form_mapper();
3265 $eventdata = $mapper->from_legacy_event_to_data($event);
3266 $data = array_merge((array) $eventdata, $data);
3267 $event->count_repeats();
3268 $formoptions['event'] = $event;
3269 $data['description']['text'] = file_prepare_draft_area(
3271 $event->context->id,
3273 'event_description',
3276 $data['description']['text']
3278 $data['description']['itemid'] = $draftitemid;
3280 $mform = new \core_calendar\local\event\forms\update(
3289 $mform->set_data($data);
3291 // Check to see if this event is part of a subscription or import.
3292 // If so display a warning on edit.
3293 if (isset($event->subscriptionid) && ($event->subscriptionid != null)) {
3294 $renderable = new \core\output\notification(
3295 get_string('eventsubscriptioneditwarning', 'calendar'),
3296 \core\output\notification::NOTIFY_INFO
3299 $html .= $OUTPUT->render($renderable);
3304 $mform->is_validated();
3307 $html .= $mform->render();
3312 * Calculate the timestamp from the supplied Gregorian Year, Month, and Day.
3314 * @param int $d The day
3315 * @param int $m The month
3316 * @param int $y The year
3317 * @param int $time The timestamp to use instead of a separate y/m/d.
3318 * @return int The timestamp
3320 function calendar_get_timestamp($d, $m, $y, $time = 0) {
3321 // If a day, month and year were passed then convert it to a timestamp. If these were passed
3322 // then we can assume the day, month and year are passed as Gregorian, as no where in core
3323 // should we be passing these values rather than the time.
3324 if (!empty($d) && !empty($m) && !empty($y)) {
3325 if (checkdate($m, $d, $y)) {
3326 $time = make_timestamp($y, $m, $d);
3330 } else if (empty($time)) {
3338 * Get the calendar footer options.
3340 * @param calendar_information $calendar The calendar information object.
3341 * @return array The data for template and template name.
3343 function calendar_get_footer_options($calendar) {
3344 global $CFG, $USER, $DB, $PAGE;
3346 // Generate hash for iCal link.
3347 $rawhash = $USER->id . $DB->get_field('user', 'password', ['id' => $USER->id]) . $CFG->calendar_exportsalt;
3348 $authtoken = sha1($rawhash);
3350 $renderer = $PAGE->get_renderer('core_calendar');
3351 $footer = new \core_calendar\external\footer_options_exporter($calendar, $USER->id, $authtoken);
3352 $data = $footer->export($renderer);
3353 $template = 'core_calendar/footer_options';
3355 return [$data, $template];
3359 * Get the list of potential calendar filter types as a type => name
3364 function calendar_get_filter_types() {
3373 return array_map(function($type) {
3376 'name' => get_string("eventtype{$type}", "calendar"),
3382 * Check whether the specified event type is valid.
3384 * @param string $type
3387 function calendar_is_valid_eventtype($type) {
3395 return in_array($type, $validtypes);