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->categoryid) && $this->properties->categoryid > 0) {
322 $context = \context_coursecat::instance($this->properties->categoryid);
323 } else if (isset($this->properties->courseid) && $this->properties->courseid > 0) {
324 $context = \context_course::instance($this->properties->courseid);
325 } else if (isset($this->properties->course) && $this->properties->course > 0) {
326 $context = \context_course::instance($this->properties->course);
327 } else if (isset($this->properties->groupid) && $this->properties->groupid > 0) {
328 $group = $DB->get_record('groups', array('id' => $this->properties->groupid));
329 $context = \context_course::instance($group->courseid);
330 } else if (isset($this->properties->userid) && $this->properties->userid > 0
331 && $this->properties->userid == $USER->id) {
332 $context = \context_user::instance($this->properties->userid);
333 } else if (isset($this->properties->userid) && $this->properties->userid > 0
334 && $this->properties->userid != $USER->id &&
335 isset($this->properties->instance) && $this->properties->instance > 0) {
336 $cm = get_coursemodule_from_instance($this->properties->modulename, $this->properties->instance, 0,
338 $context = \context_course::instance($cm->course);
340 $context = \context_user::instance($this->properties->userid);
347 * Returns an array of editoroptions for this event.
349 * @return array event editor options
351 protected function get_editoroptions() {
352 return $this->editoroptions;
356 * Returns an event description: Called by __get
357 * Please use $blah = $event->description;
359 * @return string event description
361 protected function get_description() {
364 require_once($CFG->libdir . '/filelib.php');
366 if ($this->_description === null) {
367 // Check if we have already resolved the context for this event.
368 if ($this->editorcontext === null) {
369 // Switch on the event type to decide upon the appropriate context to use for this event.
370 $this->editorcontext = $this->properties->context;
371 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
372 return clean_text($this->properties->description, $this->properties->format);
376 // Work out the item id for the editor, if this is a repeated event
377 // then the files will be associated with the original.
378 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
379 $itemid = $this->properties->repeatid;
381 $itemid = $this->properties->id;
384 // Convert file paths in the description so that things display correctly.
385 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php',
386 $this->editorcontext->id, 'calendar', 'event_description', $itemid);
387 // Clean the text so no nasties get through.
388 $this->_description = clean_text($this->_description, $this->properties->format);
391 // Finally return the description.
392 return $this->_description;
396 * Return the number of repeat events there are in this events series.
398 * @return int number of event repeated
400 public function count_repeats() {
402 if (!empty($this->properties->repeatid)) {
403 $this->properties->eventrepeats = $DB->count_records('event',
404 array('repeatid' => $this->properties->repeatid));
405 // We don't want to count ourselves.
406 $this->properties->eventrepeats--;
408 return $this->properties->eventrepeats;
412 * Update or create an event within the database
414 * Pass in a object containing the event properties and this function will
415 * insert it into the database and deal with any associated files
417 * @see self::create()
418 * @see self::update()
420 * @param \stdClass $data object of event
421 * @param bool $checkcapability if moodle should check calendar managing capability or not
422 * @return bool event updated
424 public function update($data, $checkcapability=true) {
427 foreach ($data as $key => $value) {
428 $this->properties->$key = $value;
431 $this->properties->timemodified = time();
432 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
434 // Prepare event data.
436 'context' => $this->properties->context,
437 'objectid' => $this->properties->id,
439 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
440 'timestart' => $this->properties->timestart,
441 'name' => $this->properties->name
445 if (empty($this->properties->id) || $this->properties->id < 1) {
447 if ($checkcapability) {
448 if (!calendar_add_event_allowed($this->properties)) {
449 print_error('nopermissiontoupdatecalendar');
454 switch ($this->properties->eventtype) {
456 $this->properties->courseid = 0;
457 $this->properties->course = 0;
458 $this->properties->groupid = 0;
459 $this->properties->userid = $USER->id;
462 $this->properties->courseid = SITEID;
463 $this->properties->course = SITEID;
464 $this->properties->groupid = 0;
465 $this->properties->userid = $USER->id;
468 $this->properties->groupid = 0;
469 $this->properties->userid = $USER->id;
472 $this->properties->groupid = 0;
473 $this->properties->category = 0;
474 $this->properties->userid = $USER->id;
477 $this->properties->userid = $USER->id;
480 // We should NEVER get here, but just incase we do lets fail gracefully.
481 $usingeditor = false;
485 // If we are actually using the editor, we recalculate the context because some default values
486 // were set when calculate_context() was called from the constructor.
488 $this->properties->context = $this->calculate_context();
489 $this->editorcontext = $this->properties->context;
492 $editor = $this->properties->description;
493 $this->properties->format = $this->properties->description['format'];
494 $this->properties->description = $this->properties->description['text'];
497 // Insert the event into the database.
498 $this->properties->id = $DB->insert_record('event', $this->properties);
501 $this->properties->description = file_save_draft_area_files(
503 $this->editorcontext->id,
506 $this->properties->id,
507 $this->editoroptions,
509 $this->editoroptions['forcehttps']);
510 $DB->set_field('event', 'description', $this->properties->description,
511 array('id' => $this->properties->id));
514 // Log the event entry.
515 $eventargs['objectid'] = $this->properties->id;
516 $eventargs['context'] = $this->properties->context;
517 $event = \core\event\calendar_event_created::create($eventargs);
520 $repeatedids = array();
522 if (!empty($this->properties->repeat)) {
523 $this->properties->repeatid = $this->properties->id;
524 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id' => $this->properties->id));
526 $eventcopy = clone($this->properties);
527 unset($eventcopy->id);
529 $timestart = new \DateTime('@' . $eventcopy->timestart);
530 $timestart->setTimezone(\core_date::get_user_timezone_object());
532 for ($i = 1; $i < $eventcopy->repeats; $i++) {
534 $timestart->add(new \DateInterval('P7D'));
535 $eventcopy->timestart = $timestart->getTimestamp();
537 // Get the event id for the log record.
538 $eventcopyid = $DB->insert_record('event', $eventcopy);
540 // If the context has been set delete all associated files.
542 $fs = get_file_storage();
543 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description',
544 $this->properties->id);
545 foreach ($files as $file) {
546 $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
550 $repeatedids[] = $eventcopyid;
553 $eventargs['objectid'] = $eventcopyid;
554 $eventargs['other']['timestart'] = $eventcopy->timestart;
555 $event = \core\event\calendar_event_created::create($eventargs);
563 if ($checkcapability) {
564 if (!calendar_edit_event_allowed($this->properties)) {
565 print_error('nopermissiontoupdatecalendar');
570 if ($this->editorcontext !== null) {
571 $this->properties->description = file_save_draft_area_files(
572 $this->properties->description['itemid'],
573 $this->editorcontext->id,
576 $this->properties->id,
577 $this->editoroptions,
578 $this->properties->description['text'],
579 $this->editoroptions['forcehttps']);
581 $this->properties->format = $this->properties->description['format'];
582 $this->properties->description = $this->properties->description['text'];
586 $event = $DB->get_record('event', array('id' => $this->properties->id));
588 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
590 if ($updaterepeated) {
592 if ($this->properties->timestart != $event->timestart) {
593 $timestartoffset = $this->properties->timestart - $event->timestart;
594 $sql = "UPDATE {event}
597 timestart = timestart + ?,
601 $params = array($this->properties->name, $this->properties->description, $timestartoffset,
602 $this->properties->timeduration, time(), $event->repeatid);
604 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
605 $params = array($this->properties->name, $this->properties->description,
606 $this->properties->timeduration, time(), $event->repeatid);
608 $DB->execute($sql, $params);
610 // Trigger an update event for each of the calendar event.
611 $events = $DB->get_records('event', array('repeatid' => $event->repeatid), '', '*');
612 foreach ($events as $calendarevent) {
613 $eventargs['objectid'] = $calendarevent->id;
614 $eventargs['other']['timestart'] = $calendarevent->timestart;
615 $event = \core\event\calendar_event_updated::create($eventargs);
616 $event->add_record_snapshot('event', $calendarevent);
620 $DB->update_record('event', $this->properties);
621 $event = self::load($this->properties->id);
622 $this->properties = $event->properties();
624 // Trigger an update event.
625 $event = \core\event\calendar_event_updated::create($eventargs);
626 $event->add_record_snapshot('event', $this->properties);
635 * Deletes an event and if selected an repeated events in the same series
637 * This function deletes an event, any associated events if $deleterepeated=true,
638 * and cleans up any files associated with the events.
640 * @see self::delete()
642 * @param bool $deleterepeated delete event repeatedly
643 * @return bool succession of deleting event
645 public function delete($deleterepeated = false) {
648 // If $this->properties->id is not set then something is wrong.
649 if (empty($this->properties->id)) {
650 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
653 $calevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
655 $DB->delete_records('event', array('id' => $this->properties->id));
657 // Trigger an event for the delete action.
659 'context' => $this->properties->context,
660 'objectid' => $this->properties->id,
662 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
663 'timestart' => $this->properties->timestart,
664 'name' => $this->properties->name
666 $event = \core\event\calendar_event_deleted::create($eventargs);
667 $event->add_record_snapshot('event', $calevent);
670 // If we are deleting parent of a repeated event series, promote the next event in the series as parent.
671 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
672 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC",
673 array($this->properties->id), IGNORE_MULTIPLE);
674 if (!empty($newparent)) {
675 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?",
676 array($newparent, $this->properties->id));
677 // Get all records where the repeatid is the same as the event being removed.
678 $events = $DB->get_records('event', array('repeatid' => $newparent));
679 // For each of the returned events trigger an update event.
680 foreach ($events as $calendarevent) {
681 // Trigger an event for the update.
682 $eventargs['objectid'] = $calendarevent->id;
683 $eventargs['other']['timestart'] = $calendarevent->timestart;
684 $event = \core\event\calendar_event_updated::create($eventargs);
685 $event->add_record_snapshot('event', $calendarevent);
691 // If the editor context hasn't already been set then set it now.
692 if ($this->editorcontext === null) {
693 $this->editorcontext = $this->properties->context;
696 // If the context has been set delete all associated files.
697 if ($this->editorcontext !== null) {
698 $fs = get_file_storage();
699 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
700 foreach ($files as $file) {
705 // If we need to delete repeated events then we will fetch them all and delete one by one.
706 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
707 // Get all records where the repeatid is the same as the event being removed.
708 $events = $DB->get_records('event', array('repeatid' => $this->properties->repeatid));
709 // For each of the returned events populate an event object and call delete.
710 // make sure the arg passed is false as we are already deleting all repeats.
711 foreach ($events as $event) {
712 $event = new calendar_event($event);
713 $event->delete(false);
721 * Fetch all event properties.
723 * This function returns all of the events properties as an object and optionally
724 * can prepare an editor for the description field at the same time. This is
725 * designed to work when the properties are going to be used to set the default
726 * values of a moodle forms form.
728 * @param bool $prepareeditor If set to true a editor is prepared for use with
729 * the mforms editor element. (for description)
730 * @return \stdClass Object containing event properties
732 public function properties($prepareeditor = false) {
735 // First take a copy of the properties. We don't want to actually change the
736 // properties or we'd forever be converting back and forwards between an
737 // editor formatted description and not.
738 $properties = clone($this->properties);
739 // Clean the description here.
740 $properties->description = clean_text($properties->description, $properties->format);
742 // If set to true we need to prepare the properties for use with an editor
743 // and prepare the file area.
744 if ($prepareeditor) {
746 // We may or may not have a property id. If we do then we need to work
747 // out the context so we can copy the existing files to the draft area.
748 if (!empty($properties->id)) {
750 if ($properties->eventtype === 'site') {
752 $this->editorcontext = $this->properties->context;
753 } else if ($properties->eventtype === 'user') {
755 $this->editorcontext = $this->properties->context;
756 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
757 // First check the course is valid.
758 $course = $DB->get_record('course', array('id' => $properties->courseid));
760 print_error('invalidcourse');
763 $this->editorcontext = $this->properties->context;
764 // We have a course and are within the course context so we had
765 // better use the courses max bytes value.
766 $this->editoroptions['maxbytes'] = $course->maxbytes;
767 } else if ($properties->eventtype === 'category') {
768 // First check the course is valid.
769 \coursecat::get($properties->categoryid, MUST_EXIST, true);
771 $this->editorcontext = $this->properties->context;
772 // We have a course and are within the course context so we had
773 // better use the courses max bytes value.
774 $this->editoroptions['maxbytes'] = $course->maxbytes;
776 // If we get here we have a custom event type as used by some
777 // modules. In this case the event will have been added by
778 // code and we won't need the editor.
779 $this->editoroptions['maxbytes'] = 0;
780 $this->editoroptions['maxfiles'] = 0;
783 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
786 // Get the context id that is what we really want.
787 $contextid = $this->editorcontext->id;
791 // If we get here then this is a new event in which case we don't need a
792 // context as there is no existing files to copy to the draft area.
796 // If the contextid === false we don't support files so no preparing
798 if ($contextid !== false) {
799 // Just encase it has already been submitted.
800 $draftiddescription = file_get_submitted_draft_itemid('description');
801 // Prepare the draft area, this copies existing files to the draft area as well.
802 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar',
803 'event_description', $properties->id, $this->editoroptions, $properties->description);
805 $draftiddescription = 0;
808 // Structure the description field as the editor requires.
809 $properties->description = array('text' => $properties->description, 'format' => $properties->format,
810 'itemid' => $draftiddescription);
813 // Finally return the properties.
818 * Toggles the visibility of an event
820 * @param null|bool $force If it is left null the events visibility is flipped,
821 * If it is false the event is made hidden, if it is true it
823 * @return bool if event is successfully updated, toggle will be visible
825 public function toggle_visibility($force = null) {
828 // Set visible to the default if it is not already set.
829 if (empty($this->properties->visible)) {
830 $this->properties->visible = 1;
833 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
834 // Make this event visible.
835 $this->properties->visible = 1;
837 // Make this event hidden.
838 $this->properties->visible = 0;
841 // Update the database to reflect this change.
842 $success = $DB->set_field('event', 'visible', $this->properties->visible, array('id' => $this->properties->id));
843 $calendarevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
845 // Prepare event data.
847 'context' => $this->properties->context,
848 'objectid' => $this->properties->id,
850 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
851 'timestart' => $this->properties->timestart,
852 'name' => $this->properties->name
855 $event = \core\event\calendar_event_updated::create($eventargs);
856 $event->add_record_snapshot('event', $calendarevent);
863 * Returns an event object when provided with an event id.
865 * This function makes use of MUST_EXIST, if the event id passed in is invalid
866 * it will result in an exception being thrown.
868 * @param int|object $param event object or event id
869 * @return calendar_event
871 public static function load($param) {
873 if (is_object($param)) {
874 $event = new calendar_event($param);
876 $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST);
877 $event = new calendar_event($event);
883 * Creates a new event and returns an event object
885 * @param \stdClass|array $properties An object containing event properties
886 * @param bool $checkcapability Check caps or not
887 * @throws \coding_exception
889 * @return calendar_event|bool The event object or false if it failed
891 public static function create($properties, $checkcapability = true) {
892 if (is_array($properties)) {
893 $properties = (object)$properties;
895 if (!is_object($properties)) {
896 throw new \coding_exception('When creating an event properties should be either an object or an assoc array');
898 $event = new calendar_event($properties);
899 if ($event->update($properties, $checkcapability)) {
907 * Format the text using the external API.
909 * This function should we used when text formatting is required in external functions.
911 * @return array an array containing the text formatted and the text format
913 public function format_external_text() {
915 if ($this->editorcontext === null) {
916 // Switch on the event type to decide upon the appropriate context to use for this event.
917 $this->editorcontext = $this->properties->context;
919 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
920 // We don't have a context here, do a normal format_text.
921 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id);
925 // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
926 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
927 $itemid = $this->properties->repeatid;
929 $itemid = $this->properties->id;
932 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id,
933 'calendar', 'event_description', $itemid);
938 * Calendar information class
940 * This class is used simply to organise the information pertaining to a calendar
941 * and is used primarily to make information easily available.
943 * @package core_calendar
945 * @copyright 2010 Sam Hemelryk
946 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
948 class calendar_information {
951 * @var int The timestamp
953 * Rather than setting the day, month and year we will set a timestamp which will be able
954 * to be used by multiple calendars.
958 /** @var int A course id */
959 public $courseid = null;
961 /** @var array An array of categories */
962 public $categories = array();
964 /** @var int The current category */
965 public $categoryid = null;
967 /** @var array An array of courses */
968 public $courses = array();
970 /** @var array An array of groups */
971 public $groups = array();
973 /** @var array An array of users */
974 public $users = array();
977 * Creates a new instance
979 * @param int $day the number of the day
980 * @param int $month the number of the month
981 * @param int $year the number of the year
982 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
983 * and $calyear to support multiple calendars
985 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
986 // If a day, month and year were passed then convert it to a timestamp. If these were passed
987 // then we can assume the day, month and year are passed as Gregorian, as no where in core
988 // should we be passing these values rather than the time. This is done for BC.
989 if (!empty($day) || !empty($month) || !empty($year)) {
990 $date = usergetdate(time());
992 $day = $date['mday'];
995 $month = $date['mon'];
998 $year = $date['year'];
1000 if (checkdate($month, $day, $year)) {
1001 $time = make_timestamp($year, $month, $day);
1007 $this->set_time($time);
1011 * Set the time period of this instance.
1013 * @param int $time the unixtimestamp representing the date we want to view.
1016 public function set_time($time = null) {
1018 $this->time = time();
1020 $this->time = $time;
1027 * Initialize calendar information
1030 * @param stdClass $course object
1031 * @param array $coursestoload An array of courses [$course->id => $course]
1032 * @param bool $ignorefilters options to use filter
1034 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
1035 debugging('The prepare_for_view() function has been deprecated. Please update your code to use set_sources()',
1037 $this->set_sources($course, $coursestoload);
1041 * Set the sources for events within the calendar.
1043 * If no category is provided, then the category path for the current
1044 * course will be used.
1046 * @param stdClass $course The current course being viewed.
1047 * @param int[] $courses The list of all courses currently accessible.
1048 * @param stdClass $category The current category to show.
1050 public function set_sources(stdClass $course, array $courses, stdClass $category = null) {
1051 // A cousre must always be specified.
1052 $this->course = $course;
1053 $this->courseid = $course->id;
1055 list($courseids, $group, $user) = calendar_set_filters($courses);
1056 $this->courses = $courseids;
1057 $this->groups = $group;
1058 $this->users = $user;
1060 // Do not show category events by default.
1061 $this->categoryid = null;
1062 $this->categories = null;
1064 if (null !== $category && $category->id > 0) {
1065 // A specific category was requested - set the current category, and include all parents of that category.
1066 $category = \coursecat::get($category->id);
1067 $this->categoryid = $category->id;
1069 $this->categories = $category->get_parents();
1070 $this->categories[] = $category->id;
1071 } else if (SITEID === $this->courseid) {
1072 // This is the site.
1073 // Show categories for all courses the user has access to.
1074 $this->categories = true;
1076 foreach ($courses as $course) {
1077 $category = \coursecat::get($course->category);
1078 $categories = array_merge($categories, $category->get_parents());
1079 $categories[] = $category->id;
1082 // And all categories that the user can manage.
1083 foreach (\coursecat::get_all() as $category) {
1084 if (!$category->has_manage_capability()) {
1088 $categories = array_merge($categories, $category->get_parents());
1089 $categories[] = $category->id;
1092 $this->categories = array_unique($categories);
1097 * Ensures the date for the calendar is correct and either sets it to now
1098 * or throws a moodle_exception if not
1100 * @param bool $defaultonow use current time
1101 * @throws moodle_exception
1102 * @return bool validation of checkdate
1104 public function checkdate($defaultonow = true) {
1105 if (!checkdate($this->month, $this->day, $this->year)) {
1107 $now = usergetdate(time());
1108 $this->day = intval($now['mday']);
1109 $this->month = intval($now['mon']);
1110 $this->year = intval($now['year']);
1113 throw new moodle_exception('invaliddate');
1120 * Gets todays timestamp for the calendar
1122 * @return int today timestamp
1124 public function timestamp_today() {
1128 * Gets tomorrows timestamp for the calendar
1130 * @return int tomorrow timestamp
1132 public function timestamp_tomorrow() {
1133 return strtotime('+1 day', $this->time);
1136 * Adds the pretend blocks for the calendar
1138 * @param core_calendar_renderer $renderer
1139 * @param bool $showfilters display filters, false is set as default
1140 * @param string|null $view preference view options (eg: day, month, upcoming)
1142 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
1144 $filters = new block_contents();
1145 $filters->content = $renderer->event_filter();
1146 $filters->footer = '';
1147 $filters->title = get_string('eventskey', 'calendar');
1148 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
1150 $block = new block_contents;
1151 $block->content = $renderer->fake_block_threemonths($this);
1152 $block->footer = '';
1153 $block->title = get_string('monthlyview', 'calendar');
1154 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
1159 * Get calendar events.
1161 * @param int $tstart Start time of time range for events
1162 * @param int $tend End time of time range for events
1163 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
1164 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
1165 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
1166 * @param boolean $withduration whether only events starting within time range selected
1167 * or events in progress/already started selected as well
1168 * @param boolean $ignorehidden whether to select only visible events or all events
1169 * @param array|int|boolean $categories array of categories, category id or boolean for all/no course events
1170 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
1172 function calendar_get_events($tstart, $tend, $users, $groups, $courses,
1173 $withduration = true, $ignorehidden = true, $categories = []) {
1179 if (empty($users) && empty($groups) && empty($courses) && empty($categories)) {
1183 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
1184 // Events from a number of users
1185 if(!empty($whereclause)) $whereclause .= ' OR';
1186 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED);
1187 $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)";
1188 $params = array_merge($params, $inparamsusers);
1189 } else if($users === true) {
1190 // Events from ALL users
1191 if(!empty($whereclause)) $whereclause .= ' OR';
1192 $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)';
1193 } else if($users === false) {
1194 // No user at all, do nothing
1197 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
1198 // Events from a number of groups
1199 if(!empty($whereclause)) $whereclause .= ' OR';
1200 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED);
1201 $whereclause .= " e.groupid $insqlgroups ";
1202 $params = array_merge($params, $inparamsgroups);
1203 } else if($groups === true) {
1204 // Events from ALL groups
1205 if(!empty($whereclause)) $whereclause .= ' OR ';
1206 $whereclause .= ' e.groupid != 0';
1208 // boolean false (no groups at all): we don't need to do anything
1210 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
1211 if(!empty($whereclause)) $whereclause .= ' OR';
1212 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED);
1213 $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
1214 $params = array_merge($params, $inparamscourses);
1215 } else if ($courses === true) {
1216 // Events from ALL courses
1217 if(!empty($whereclause)) $whereclause .= ' OR';
1218 $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
1221 if ((is_array($categories) && !empty($categories)) || is_numeric($categories)) {
1222 if (!empty($whereclause)) {
1223 $whereclause .= ' OR';
1225 list($insqlcategories, $inparamscategories) = $DB->get_in_or_equal($categories, SQL_PARAMS_NAMED);
1226 $whereclause .= " (e.groupid = 0 AND e.courseid = 0 AND e.categoryid $insqlcategories)";
1227 $params = array_merge($params, $inparamscategories);
1228 } else if ($categories === true) {
1229 // Events from ALL categories.
1230 if (!empty($whereclause)) {
1231 $whereclause .= ' OR';
1233 $whereclause .= ' (e.groupid = 0 AND e.courseid = 0 AND e.categoryid != 0)';
1236 // Security check: if, by now, we have NOTHING in $whereclause, then it means
1237 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
1238 // events no matter what. Allowing the code to proceed might return a completely
1239 // valid query with only time constraints, thus selecting ALL events in that time frame!
1240 if(empty($whereclause)) {
1245 $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1248 $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1250 if(!empty($whereclause)) {
1251 // We have additional constraints
1252 $whereclause = $timeclause.' AND ('.$whereclause.')';
1255 // Just basic time filtering
1256 $whereclause = $timeclause;
1259 if ($ignorehidden) {
1260 $whereclause .= ' AND e.visible = 1';
1265 LEFT JOIN {modules} m ON e.modulename = m.name
1266 -- Non visible modules will have a value of 0.
1267 WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
1268 ORDER BY e.timestart";
1269 $events = $DB->get_records_sql($sql, $params);
1271 if ($events === false) {
1278 * Return the days of the week.
1280 * @return array array of days
1282 function calendar_get_days() {
1283 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1284 return $calendartype->get_weekdays();
1288 * Get the subscription from a given id.
1291 * @param int $id id of the subscription
1292 * @return stdClass Subscription record from DB
1293 * @throws moodle_exception for an invalid id
1295 function calendar_get_subscription($id) {
1298 $cache = \cache::make('core', 'calendar_subscriptions');
1299 $subscription = $cache->get($id);
1300 if (empty($subscription)) {
1301 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
1302 $cache->set($id, $subscription);
1305 return $subscription;
1309 * Gets the first day of the week.
1311 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
1315 function calendar_get_starting_weekday() {
1316 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1317 return $calendartype->get_starting_weekday();
1321 * Gets the calendar upcoming event.
1323 * @param array $courses array of courses
1324 * @param array|int|bool $groups array of groups, group id or boolean for all/no group events
1325 * @param array|int|bool $users array of users, user id or boolean for all/no user events
1326 * @param int $daysinfuture number of days in the future we 'll look
1327 * @param int $maxevents maximum number of events
1328 * @param int $fromtime start time
1329 * @return array $output array of upcoming events
1331 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
1334 $display = new \stdClass;
1335 $display->range = $daysinfuture; // How many days in the future we 'll look.
1336 $display->maxevents = $maxevents;
1341 $now = time(); // We 'll need this later.
1342 $usermidnighttoday = usergetmidnight($now);
1345 $display->tstart = $fromtime;
1347 $display->tstart = $usermidnighttoday;
1350 // This works correctly with respect to the user's DST, but it is accurate
1351 // only because $fromtime is always the exact midnight of some day!
1352 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
1354 // Get the events matching our criteria.
1355 $events = calendar_get_legacy_events($display->tstart, $display->tend, $users, $groups, $courses);
1357 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
1358 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
1359 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
1360 // arguments to this function.
1361 $hrefparams = array();
1362 if (!empty($courses)) {
1363 $courses = array_diff($courses, array(SITEID));
1364 if (count($courses) == 1) {
1365 $hrefparams['course'] = reset($courses);
1369 if ($events !== false) {
1370 foreach ($events as $event) {
1371 if (!empty($event->modulename)) {
1372 $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
1373 if (empty($instances[$event->instance]->uservisible)) {
1378 if ($processed >= $display->maxevents) {
1382 $event->time = calendar_format_event_time($event, $now, $hrefparams);
1392 * Get a HTML link to a course.
1394 * @param int|stdClass $course the course id or course object
1395 * @return string a link to the course (as HTML); empty if the course id is invalid
1397 function calendar_get_courselink($course) {
1402 if (!is_object($course)) {
1403 $course = calendar_get_course_cached($coursecache, $course);
1405 $context = \context_course::instance($course->id);
1406 $fullname = format_string($course->fullname, true, array('context' => $context));
1407 $url = new \moodle_url('/course/view.php', array('id' => $course->id));
1408 $link = \html_writer::link($url, $fullname);
1414 * Get current module cache.
1416 * Only use this method if you do not know courseid. Otherwise use:
1417 * get_fast_modinfo($courseid)->instances[$modulename][$instance]
1419 * @param array $modulecache in memory module cache
1420 * @param string $modulename name of the module
1421 * @param int $instance module instance number
1422 * @return stdClass|bool $module information
1424 function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
1425 if (!isset($modulecache[$modulename . '_' . $instance])) {
1426 $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
1429 return $modulecache[$modulename . '_' . $instance];
1433 * Get current course cache.
1435 * @param array $coursecache list of course cache
1436 * @param int $courseid id of the course
1437 * @return stdClass $coursecache[$courseid] return the specific course cache
1439 function calendar_get_course_cached(&$coursecache, $courseid) {
1440 if (!isset($coursecache[$courseid])) {
1441 $coursecache[$courseid] = get_course($courseid);
1443 return $coursecache[$courseid];
1447 * Get group from groupid for calendar display
1449 * @param int $groupid
1450 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1452 function calendar_get_group_cached($groupid) {
1453 static $groupscache = array();
1454 if (!isset($groupscache[$groupid])) {
1455 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1457 return $groupscache[$groupid];
1461 * Add calendar event metadata
1463 * @param stdClass $event event info
1464 * @return stdClass $event metadata
1466 function calendar_add_event_metadata($event) {
1467 global $CFG, $OUTPUT;
1469 // Support multilang in event->name.
1470 $event->name = format_string($event->name, true);
1472 if (!empty($event->modulename)) { // Activity event.
1473 // The module name is set. I will assume that it has to be displayed, and
1474 // also that it is an automatically-generated event. And of course that the
1475 // instace id and modulename are set correctly.
1476 $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
1477 if (!array_key_exists($event->instance, $instances)) {
1480 $module = $instances[$event->instance];
1482 $modulename = $module->get_module_type_name(false);
1483 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
1484 // Will be used as alt text if the event icon.
1485 $eventtype = get_string($event->eventtype, $event->modulename);
1490 $event->icon = '<img src="' . s($module->get_icon_url()) . '" alt="' . s($eventtype) .
1491 '" title="' . s($modulename) . '" class="icon" />';
1492 $event->referer = html_writer::link($module->url, $event->name);
1493 $event->courselink = calendar_get_courselink($module->get_course());
1494 $event->cmid = $module->id;
1495 } else if ($event->courseid == SITEID) { // Site event.
1496 $event->icon = '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
1497 get_string('globalevent', 'calendar') . '" class="icon" />';
1498 $event->cssclass = 'calendar_event_global';
1499 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event.
1500 $event->icon = '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
1501 get_string('courseevent', 'calendar') . '" class="icon" />';
1502 $event->courselink = calendar_get_courselink($event->courseid);
1503 $event->cssclass = 'calendar_event_course';
1504 } else if ($event->groupid) { // Group event.
1505 if ($group = calendar_get_group_cached($event->groupid)) {
1506 $groupname = format_string($group->name, true, \context_course::instance($group->courseid));
1510 $event->icon = \html_writer::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
1511 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
1512 $event->courselink = calendar_get_courselink($event->courseid) . ', ' . $groupname;
1513 $event->cssclass = 'calendar_event_group';
1514 } else if ($event->userid) { // User event.
1515 $event->icon = '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
1516 get_string('userevent', 'calendar') . '" class="icon" />';
1517 $event->cssclass = 'calendar_event_user';
1524 * Get calendar events by id.
1527 * @param array $eventids list of event ids
1528 * @return array Array of event entries, empty array if nothing found
1530 function calendar_get_events_by_id($eventids) {
1533 if (!is_array($eventids) || empty($eventids)) {
1537 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
1538 $wheresql = "id $wheresql";
1540 return $DB->get_records_select('event', $wheresql, $params);
1544 * Get control options for calendar.
1546 * @param string $type of calendar
1547 * @param array $data calendar information
1548 * @return string $content return available control for the calender in html
1550 function calendar_top_controls($type, $data) {
1551 global $PAGE, $OUTPUT;
1553 // Get the calendar type we are using.
1554 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1558 // Ensure course id passed if relevant.
1560 if (!empty($data['id'])) {
1561 $courseid = '&course=' . $data['id'];
1564 // If we are passing a month and year then we need to convert this to a timestamp to
1565 // support multiple calendars. No where in core should these be passed, this logic
1566 // here is for third party plugins that may use this function.
1567 if (!empty($data['m']) && !empty($date['y'])) {
1568 if (!isset($data['d'])) {
1571 if (!checkdate($data['m'], $data['d'], $data['y'])) {
1574 $time = make_timestamp($data['y'], $data['m'], $data['d']);
1576 } else if (!empty($data['time'])) {
1577 $time = $data['time'];
1582 // Get the date for the calendar type.
1583 $date = $calendartype->timestamp_to_date_array($time);
1585 $urlbase = $PAGE->url;
1587 // We need to get the previous and next months in certain cases.
1588 if ($type == 'frontpage' || $type == 'course' || $type == 'month') {
1589 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1590 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
1591 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
1592 $prevmonthtime['hour'], $prevmonthtime['minute']);
1594 $nextmonth = calendar_add_month($date['mon'], $date['year']);
1595 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
1596 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
1597 $nextmonthtime['hour'], $nextmonthtime['minute']);
1602 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1603 true, $prevmonthtime);
1604 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true,
1606 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1607 false, false, false, $time);
1609 if (!empty($data['id'])) {
1610 $calendarlink->param('course', $data['id']);
1615 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1616 $content .= $prevlink . '<span class="hide"> | </span>';
1617 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1618 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1619 ), array('class' => 'current'));
1620 $content .= '<span class="hide"> | </span>' . $right;
1621 $content .= "<span class=\"clearer\"><!-- --></span>\n";
1622 $content .= \html_writer::end_tag('div');
1626 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1627 true, $prevmonthtime);
1628 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false,
1629 true, $nextmonthtime);
1630 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1631 false, false, false, $time);
1633 if (!empty($data['id'])) {
1634 $calendarlink->param('course', $data['id']);
1637 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1638 $content .= $prevlink . '<span class="hide"> | </span>';
1639 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1640 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1641 ), array('class' => 'current'));
1642 $content .= '<span class="hide"> | </span>' . $nextlink;
1643 $content .= "<span class=\"clearer\"><!-- --></span>";
1644 $content .= \html_writer::end_tag('div');
1647 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'upcoming')),
1648 false, false, false, $time);
1649 if (!empty($data['id'])) {
1650 $calendarlink->param('course', $data['id']);
1652 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1653 $content .= \html_writer::tag('div', $calendarlink, array('class' => 'centered'));
1656 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1657 false, false, false, $time);
1658 if (!empty($data['id'])) {
1659 $calendarlink->param('course', $data['id']);
1661 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1662 $content .= \html_writer::tag('h3', $calendarlink);
1665 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1666 'view.php?view=month' . $courseid . '&', false, false, false, false, $prevmonthtime);
1667 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1668 'view.php?view=month' . $courseid . '&', false, false, false, false, $nextmonthtime);
1670 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1671 $content .= $prevlink . '<span class="hide"> | </span>';
1672 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1673 $content .= '<span class="hide"> | </span>' . $nextlink;
1674 $content .= '<span class="clearer"><!-- --></span>';
1675 $content .= \html_writer::end_tag('div')."\n";
1678 $days = calendar_get_days();
1680 $prevtimestamp = strtotime('-1 day', $time);
1681 $nexttimestamp = strtotime('+1 day', $time);
1683 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1684 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1686 $prevname = $days[$prevdate['wday']]['fullname'];
1687 $nextname = $days[$nextdate['wday']]['fullname'];
1688 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&', false, false,
1689 false, false, $prevtimestamp);
1690 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&', false, false, false,
1691 false, $nexttimestamp);
1693 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1694 $content .= $prevlink;
1695 $content .= '<span class="hide"> | </span><span class="current">' .userdate($time,
1696 get_string('strftimedaydate')) . '</span>';
1697 $content .= '<span class="hide"> | </span>' . $nextlink;
1698 $content .= "<span class=\"clearer\"><!-- --></span>";
1699 $content .= \html_writer::end_tag('div') . "\n";
1708 * Return the representation day.
1710 * @param int $tstamp Timestamp in GMT
1711 * @param int|bool $now current Unix timestamp
1712 * @param bool $usecommonwords
1713 * @return string the formatted date/time
1715 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1716 static $shortformat;
1718 if (empty($shortformat)) {
1719 $shortformat = get_string('strftimedayshort');
1722 if ($now === false) {
1726 // To have it in one place, if a change is needed.
1727 $formal = userdate($tstamp, $shortformat);
1729 $datestamp = usergetdate($tstamp);
1730 $datenow = usergetdate($now);
1732 if ($usecommonwords == false) {
1733 // We don't want words, just a date.
1735 } else if ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1736 return get_string('today', 'calendar');
1737 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1738 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12
1739 && $datenow['yday'] == 1)) {
1740 return get_string('yesterday', 'calendar');
1741 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1742 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12
1743 && $datestamp['yday'] == 1)) {
1744 return get_string('tomorrow', 'calendar');
1751 * return the formatted representation time.
1754 * @param int $time the timestamp in UTC, as obtained from the database
1755 * @return string the formatted date/time
1757 function calendar_time_representation($time) {
1758 static $langtimeformat = null;
1760 if ($langtimeformat === null) {
1761 $langtimeformat = get_string('strftimetime');
1764 $timeformat = get_user_preferences('calendar_timeformat');
1765 if (empty($timeformat)) {
1766 $timeformat = get_config(null, 'calendar_site_timeformat');
1769 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
1773 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1775 * @param string|moodle_url $linkbase
1776 * @param int $d The number of the day.
1777 * @param int $m The number of the month.
1778 * @param int $y The number of the year.
1779 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1780 * $m and $y are kept for backwards compatibility.
1781 * @return moodle_url|null $linkbase
1783 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1784 if (empty($linkbase)) {
1788 if (!($linkbase instanceof \moodle_url)) {
1789 $linkbase = new \moodle_url($linkbase);
1792 $linkbase->param('time', calendar_get_timestamp($d, $m, $y, $time));
1798 * Build and return a previous month HTML link, with an arrow.
1800 * @param string $text The text label.
1801 * @param string|moodle_url $linkbase The URL stub.
1802 * @param int $d The number of the date.
1803 * @param int $m The number of the month.
1804 * @param int $y year The number of the year.
1805 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1806 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1807 * $m and $y are kept for backwards compatibility.
1808 * @return string HTML string.
1810 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1811 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1818 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1819 'data-drop-zone' => 'nav-link',
1822 return link_arrow_left($text, $href->out(false), $accesshide, 'previous', $attrs);
1826 * Build and return a next month HTML link, with an arrow.
1828 * @param string $text The text label.
1829 * @param string|moodle_url $linkbase The URL stub.
1830 * @param int $d the number of the Day
1831 * @param int $m The number of the month.
1832 * @param int $y The number of the year.
1833 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1834 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1835 * $m and $y are kept for backwards compatibility.
1836 * @return string HTML string.
1838 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1839 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1846 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1847 'data-drop-zone' => 'nav-link',
1850 return link_arrow_right($text, $href->out(false), $accesshide, 'next', $attrs);
1854 * Return the number of days in month.
1856 * @param int $month the number of the month.
1857 * @param int $year the number of the year
1860 function calendar_days_in_month($month, $year) {
1861 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1862 return $calendartype->get_num_days_in_month($year, $month);
1866 * Get the next following month.
1868 * @param int $month the number of the month.
1869 * @param int $year the number of the year.
1870 * @return array the following month
1872 function calendar_add_month($month, $year) {
1873 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1874 return $calendartype->get_next_month($year, $month);
1878 * Get the previous month.
1880 * @param int $month the number of the month.
1881 * @param int $year the number of the year.
1882 * @return array previous month
1884 function calendar_sub_month($month, $year) {
1885 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1886 return $calendartype->get_prev_month($year, $month);
1890 * Get per-day basis events
1892 * @param array $events list of events
1893 * @param int $month the number of the month
1894 * @param int $year the number of the year
1895 * @param array $eventsbyday event on specific day
1896 * @param array $durationbyday duration of the event in days
1897 * @param array $typesbyday event type (eg: global, course, user, or group)
1898 * @param array $courses list of courses
1901 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1902 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1904 $eventsbyday = array();
1905 $typesbyday = array();
1906 $durationbyday = array();
1908 if ($events === false) {
1912 foreach ($events as $event) {
1913 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
1914 if ($event->timeduration) {
1915 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
1917 $enddate = $startdate;
1920 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair.
1921 if (!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) &&
1922 ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1926 $eventdaystart = intval($startdate['mday']);
1928 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
1929 // Give the event to its day.
1930 $eventsbyday[$eventdaystart][] = $event->id;
1932 // Mark the day as having such an event.
1933 if ($event->courseid == SITEID && $event->groupid == 0) {
1934 $typesbyday[$eventdaystart]['startglobal'] = true;
1935 // Set event class for global event.
1936 $events[$event->id]->class = 'calendar_event_global';
1937 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1938 $typesbyday[$eventdaystart]['startcourse'] = true;
1939 // Set event class for course event.
1940 $events[$event->id]->class = 'calendar_event_course';
1941 } else if ($event->groupid) {
1942 $typesbyday[$eventdaystart]['startgroup'] = true;
1943 // Set event class for group event.
1944 $events[$event->id]->class = 'calendar_event_group';
1945 } else if ($event->userid) {
1946 $typesbyday[$eventdaystart]['startuser'] = true;
1947 // Set event class for user event.
1948 $events[$event->id]->class = 'calendar_event_user';
1952 if ($event->timeduration == 0) {
1953 // Proceed with the next.
1957 // The event starts on $month $year or before.
1958 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
1959 $lowerbound = intval($startdate['mday']);
1964 // Also, it ends on $month $year or later.
1965 if ($enddate['mon'] == $month && $enddate['year'] == $year) {
1966 $upperbound = intval($enddate['mday']);
1968 $upperbound = calendar_days_in_month($month, $year);
1971 // Mark all days between $lowerbound and $upperbound (inclusive) as duration.
1972 for ($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
1973 $durationbyday[$i][] = $event->id;
1974 if ($event->courseid == SITEID && $event->groupid == 0) {
1975 $typesbyday[$i]['durationglobal'] = true;
1976 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1977 $typesbyday[$i]['durationcourse'] = true;
1978 } else if ($event->groupid) {
1979 $typesbyday[$i]['durationgroup'] = true;
1980 } else if ($event->userid) {
1981 $typesbyday[$i]['durationuser'] = true;
1990 * Returns the courses to load events for.
1992 * @param array $courseeventsfrom An array of courses to load calendar events for
1993 * @param bool $ignorefilters specify the use of filters, false is set as default
1994 * @return array An array of courses, groups, and user to load calendar events for based upon filters
1996 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
1999 // For backwards compatability we have to check whether the courses array contains
2000 // just id's in which case we need to load course objects.
2001 $coursestoload = array();
2002 foreach ($courseeventsfrom as $id => $something) {
2003 if (!is_object($something)) {
2004 $coursestoload[] = $id;
2005 unset($courseeventsfrom[$id]);
2013 // Get the capabilities that allow seeing group events from all groups.
2014 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
2016 $isloggedin = isloggedin();
2018 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
2019 $courses = array_keys($courseeventsfrom);
2021 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
2022 $courses[] = SITEID;
2024 $courses = array_unique($courses);
2027 if (!empty($courses) && in_array(SITEID, $courses)) {
2028 // Sort courses for consistent colour highlighting.
2029 // Effectively ignoring SITEID as setting as last course id.
2030 $key = array_search(SITEID, $courses);
2031 unset($courses[$key]);
2032 $courses[] = SITEID;
2035 if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
2039 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
2041 if (count($courseeventsfrom) == 1) {
2042 $course = reset($courseeventsfrom);
2043 if (has_any_capability($allgroupscaps, \context_course::instance($course->id))) {
2044 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
2045 $group = array_keys($coursegroups);
2048 if ($group === false) {
2049 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, \context_system::instance())) {
2051 } else if ($isloggedin) {
2052 $groupids = array();
2053 foreach ($courseeventsfrom as $courseid => $course) {
2054 // If the user is an editing teacher in there.
2055 if (!empty($USER->groupmember[$course->id])) {
2056 // We've already cached the users groups for this course so we can just use that.
2057 $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
2058 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2059 // If this course has groups, show events from all of those related to the current user.
2060 $coursegroups = groups_get_user_groups($course->id, $USER->id);
2061 $groupids = array_merge($groupids, $coursegroups['0']);
2064 if (!empty($groupids)) {
2070 if (empty($courses)) {
2074 return array($courses, $group, $user);
2078 * Return the capability for editing calendar event.
2080 * @param calendar_event $event event object
2081 * @param bool $manualedit is the event being edited manually by the user
2082 * @return bool capability to edit event
2084 function calendar_edit_event_allowed($event, $manualedit = false) {
2087 // Must be logged in.
2088 if (!isloggedin()) {
2092 // Can not be using guest account.
2093 if (isguestuser()) {
2097 if ($manualedit && !empty($event->modulename)) {
2098 $hascallback = component_callback_exists(
2099 'mod_' . $event->modulename,
2100 'core_calendar_event_timestart_updated'
2103 if (!$hascallback) {
2104 // If the activity hasn't implemented the correct callback
2105 // to handle changes to it's events then don't allow any
2106 // manual changes to them.
2110 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2111 $hasmodule = isset($coursemodules[$event->modulename]);
2112 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2114 // If modinfo doesn't know about the module, return false to be safe.
2115 if (!$hasmodule || !$hasinstance) {
2119 $coursemodule = $coursemodules[$event->modulename][$event->instance];
2120 $context = context_module::instance($coursemodule->id);
2121 // This is the capability that allows a user to modify the activity
2122 // settings. Since the activity generated this event we need to check
2123 // that the current user has the same capability before allowing them
2124 // to update the event because the changes to the event will be
2125 // reflected within the activity.
2126 return has_capability('moodle/course:manageactivities', $context);
2129 // You cannot edit URL based calendar subscription events presently.
2130 if (!empty($event->subscriptionid)) {
2131 if (!empty($event->subscription->url)) {
2132 // This event can be updated externally, so it cannot be edited.
2137 $sitecontext = \context_system::instance();
2139 // If user has manageentries at site level, return true.
2140 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2144 // If groupid is set, it's definitely a group event.
2145 if (!empty($event->groupid)) {
2146 // Allow users to add/edit group events if -
2147 // 1) They have manageentries for the course OR
2148 // 2) They have managegroupentries AND are in the group.
2149 $eventcontext = \context_course::instance($event->courseid);
2150 $group = $DB->get_record('groups', array('id' => $event->groupid));
2152 has_capability('moodle/calendar:manageentries', $eventcontext) ||
2153 (has_capability('moodle/calendar:managegroupentries', $eventcontext)
2154 && groups_is_member($event->groupid)));
2155 } else if (!empty($event->courseid)) {
2156 // If groupid is not set, but course is set, it's definitely a course event.
2157 $eventcontext = \context_course::instance($event->courseid);
2158 return has_capability('moodle/calendar:manageentries', $eventcontext);
2159 } else if (!empty($event->categoryid)) {
2160 // If groupid is not set, but category is set, it's definitely a category event.
2161 $eventcontext = \context_coursecat::instance($event->categoryid);
2162 return has_capability('moodle/calendar:manageentries', $eventcontext);
2163 } else if (!empty($event->userid) && $event->userid == $USER->id) {
2164 // If course is not set, but userid id set, it's a user event.
2165 $eventcontext = \context_user::instance($event->userid);
2166 return (has_capability('moodle/calendar:manageownentries', $eventcontext));
2167 } else if (!empty($event->userid)) {
2168 $eventcontext = \context_user::instance($event->userid);
2169 return (has_capability('moodle/calendar:manageentries', $eventcontext));
2176 * Return the capability for deleting a calendar event.
2178 * @param calendar_event $event The event object
2179 * @return bool Whether the user has permission to delete the event or not.
2181 function calendar_delete_event_allowed($event) {
2182 // Only allow delete if you have capabilities and it is not an module event.
2183 return (calendar_edit_event_allowed($event) && empty($event->modulename));
2187 * Returns the default courses to display on the calendar when there isn't a specific
2188 * course to display.
2190 * @return array $courses Array of courses to display
2192 function calendar_get_default_courses() {
2195 if (!isloggedin()) {
2199 if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', \context_system::instance())) {
2200 $select = ', ' . \context_helper::get_preload_record_columns_sql('ctx');
2201 $join = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
2202 $sql = "SELECT c.* $select
2205 WHERE EXISTS (SELECT 1 FROM {event} e WHERE e.courseid = c.id)
2207 $courses = $DB->get_records_sql($sql, array('contextlevel' => CONTEXT_COURSE), 0, 20);
2208 foreach ($courses as $course) {
2209 \context_helper::preload_from_record($course);
2214 $courses = enrol_get_my_courses();
2220 * Get event format time.
2222 * @param calendar_event $event event object
2223 * @param int $now current time in gmt
2224 * @param array $linkparams list of params for event link
2225 * @param bool $usecommonwords the words as formatted date/time.
2226 * @param int $showtime determine the show time GMT timestamp
2227 * @return string $eventtime link/string for event time
2229 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
2230 $starttime = $event->timestart;
2231 $endtime = $event->timestart + $event->timeduration;
2233 if (empty($linkparams) || !is_array($linkparams)) {
2234 $linkparams = array();
2237 $linkparams['view'] = 'day';
2239 // OK, now to get a meaningful display.
2240 // Check if there is a duration for this event.
2241 if ($event->timeduration) {
2242 // Get the midnight of the day the event will start.
2243 $usermidnightstart = usergetmidnight($starttime);
2244 // Get the midnight of the day the event will end.
2245 $usermidnightend = usergetmidnight($endtime);
2246 // Check if we will still be on the same day.
2247 if ($usermidnightstart == $usermidnightend) {
2248 // Check if we are running all day.
2249 if ($event->timeduration == DAYSECS) {
2250 $time = get_string('allday', 'calendar');
2251 } else { // Specify the time we will be running this from.
2252 $datestart = calendar_time_representation($starttime);
2253 $dateend = calendar_time_representation($endtime);
2254 $time = $datestart . ' <strong>»</strong> ' . $dateend;
2257 // Set printable representation.
2259 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2260 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2261 $eventtime = \html_writer::link($url, $day) . ', ' . $time;
2265 } else { // It must spans two or more days.
2266 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
2267 if ($showtime == $usermidnightstart) {
2270 $timestart = calendar_time_representation($event->timestart);
2271 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
2272 if ($showtime == $usermidnightend) {
2275 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
2277 // Set printable representation.
2278 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2279 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2280 $eventtime = $timestart . ' <strong>»</strong> ' . \html_writer::link($url, $dayend) . $timeend;
2282 // The event is in the future, print start and end links.
2283 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2284 $eventtime = \html_writer::link($url, $daystart) . $timestart . ' <strong>»</strong> ';
2286 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2287 $eventtime .= \html_writer::link($url, $dayend) . $timeend;
2290 } else { // There is no time duration.
2291 $time = calendar_time_representation($event->timestart);
2292 // Set printable representation.
2294 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2295 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2296 $eventtime = \html_writer::link($url, $day) . ', ' . trim($time);
2302 // Check if It has expired.
2303 if ($event->timestart + $event->timeduration < $now) {
2304 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2311 * Checks to see if the requested type of event should be shown for the given user.
2313 * @param int $type The type to check the display for (default is to display all)
2314 * @param stdClass|int|null $user The user to check for - by default the current user
2315 * @return bool True if the tyep should be displayed false otherwise
2317 function calendar_show_event_type($type, $user = null) {
2318 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
2320 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2322 if (!isset($SESSION->calendarshoweventtype)) {
2323 $SESSION->calendarshoweventtype = $default;
2325 return $SESSION->calendarshoweventtype & $type;
2327 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2332 * Sets the display of the event type given $display.
2334 * If $display = true the event type will be shown.
2335 * If $display = false the event type will NOT be shown.
2336 * If $display = null the current value will be toggled and saved.
2338 * @param int $type object of CALENDAR_EVENT_XXX
2339 * @param bool $display option to display event type
2340 * @param stdClass|int $user moodle user object or id, null means current user
2342 function calendar_set_event_type_display($type, $display = null, $user = null) {
2343 $persist = get_user_preferences('calendar_persistflt', 0, $user);
2344 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP
2345 + CALENDAR_EVENT_USER + CALENDAR_EVENT_COURSECAT;
2346 if ($persist === 0) {
2348 if (!isset($SESSION->calendarshoweventtype)) {
2349 $SESSION->calendarshoweventtype = $default;
2351 $preference = $SESSION->calendarshoweventtype;
2353 $preference = get_user_preferences('calendar_savedflt', $default, $user);
2355 $current = $preference & $type;
2356 if ($display === null) {
2357 $display = !$current;
2359 if ($display && !$current) {
2360 $preference += $type;
2361 } else if (!$display && $current) {
2362 $preference -= $type;
2364 if ($persist === 0) {
2365 $SESSION->calendarshoweventtype = $preference;
2367 if ($preference == $default) {
2368 unset_user_preference('calendar_savedflt', $user);
2370 set_user_preference('calendar_savedflt', $preference, $user);
2376 * Get calendar's allowed types.
2378 * @param stdClass $allowed list of allowed edit for event type
2379 * @param stdClass|int $course object of a course or course id
2380 * @param array $groups array of groups for the given course
2381 * @param stdClass|int $category object of a category
2383 function calendar_get_allowed_types(&$allowed, $course = null, $groups = null, $category = null) {
2386 $allowed = new \stdClass();
2387 $allowed->user = has_capability('moodle/calendar:manageownentries', \context_system::instance());
2388 $allowed->groups = false;
2389 $allowed->courses = false;
2390 $allowed->categories = false;
2391 $allowed->site = has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID));
2392 $getgroupsfunc = function($course, $context, $user) use ($groups) {
2393 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2394 if (has_capability('moodle/site:accessallgroups', $context)) {
2395 return is_null($groups) ? groups_get_all_groups($course->id) : $groups;
2397 if (is_null($groups)) {
2398 return groups_get_all_groups($course->id, $user->id);
2400 return array_filter($groups, function($group) use ($user) {
2401 return isset($group->members[$user->id]);
2410 if (!empty($course)) {
2411 if (!is_object($course)) {
2412 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST);
2414 if ($course->id != SITEID) {
2415 $coursecontext = \context_course::instance($course->id);
2416 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
2418 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2419 $allowed->courses = array($course->id => 1);
2420 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2421 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
2422 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2427 if (!empty($category)) {
2428 $catcontext = \context_coursecat::instance($category->id);
2429 if (has_capability('moodle/category:manage', $catcontext)) {
2430 $allowed->categories = [$category->id => 1];
2436 * Get all of the allowed types for all of the courses and groups
2437 * the logged in user belongs to.
2439 * The returned array will optionally have 5 keys:
2440 * 'user' : true if the logged in user can create user events
2441 * 'site' : true if the logged in user can create site events
2442 * 'category' : array of course categories that the user can create events for
2443 * 'course' : array of courses that the user can create events for
2444 * 'group': array of groups that the user can create events for
2445 * 'groupcourses' : array of courses that the groups belong to (can
2446 * be different from the list in 'course'.
2448 * @return array The array of allowed types.
2450 function calendar_get_all_allowed_types() {
2451 global $CFG, $USER, $DB;
2453 require_once($CFG->libdir . '/enrollib.php');
2457 calendar_get_allowed_types($allowed);
2459 if ($allowed->user) {
2460 $types['user'] = true;
2463 if ($allowed->site) {
2464 $types['site'] = true;
2467 if (coursecat::has_manage_capability_on_any()) {
2468 $types['category'] = coursecat::make_categories_list('moodle/category:manage');
2471 // This function warms the context cache for the course so the calls
2472 // to load the course context in calendar_get_allowed_types don't result
2473 // in additional DB queries.
2474 $courses = enrol_get_users_courses($USER->id, true);
2475 // We want to pre-fetch all of the groups for each course in a single
2476 // query to avoid calendar_get_allowed_types from hitting the DB for
2477 // each separate course.
2478 $groups = groups_get_all_groups_for_courses($courses);
2480 foreach ($courses as $course) {
2481 $coursegroups = isset($groups[$course->id]) ? $groups[$course->id] : null;
2482 calendar_get_allowed_types($allowed, $course, $coursegroups);
2484 if (!empty($allowed->courses)) {
2485 if (!isset($types['course'])) {
2486 $types['course'] = [$course];
2488 $types['course'][] = $course;
2492 if (!empty($allowed->groups)) {
2493 if (!isset($types['groupcourses'])) {
2494 $types['groupcourses'] = [$course];
2496 $types['groupcourses'][] = $course;
2499 if (!isset($types['group'])) {
2500 $types['group'] = array_values($allowed->groups);
2502 $types['group'] = array_merge($types['group'], array_values($allowed->groups));
2511 * See if user can add calendar entries at all used to print the "New Event" button.
2513 * @param stdClass $course object of a course or course id
2514 * @return bool has the capability to add at least one event type
2516 function calendar_user_can_add_event($course) {
2517 if (!isloggedin() || isguestuser()) {
2521 calendar_get_allowed_types($allowed, $course);
2523 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->category || $allowed->site);
2527 * Check wether the current user is permitted to add events.
2529 * @param stdClass $event object of event
2530 * @return bool has the capability to add event
2532 function calendar_add_event_allowed($event) {
2535 // Can not be using guest account.
2536 if (!isloggedin() or isguestuser()) {
2540 $sitecontext = \context_system::instance();
2542 // If user has manageentries at site level, always return true.
2543 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2547 switch ($event->eventtype) {
2549 return has_capability('moodle/category:manage', $event->context);
2551 return has_capability('moodle/calendar:manageentries', $event->context);
2553 // Allow users to add/edit group events if -
2554 // 1) They have manageentries (= entries for whole course).
2555 // 2) They have managegroupentries AND are in the group.
2556 $group = $DB->get_record('groups', array('id' => $event->groupid));
2558 has_capability('moodle/calendar:manageentries', $event->context) ||
2559 (has_capability('moodle/calendar:managegroupentries', $event->context)
2560 && groups_is_member($event->groupid)));
2562 if ($event->userid == $USER->id) {
2563 return (has_capability('moodle/calendar:manageownentries', $event->context));
2565 // There is intentionally no 'break'.
2567 return has_capability('moodle/calendar:manageentries', $event->context);
2569 return has_capability('moodle/calendar:manageentries', $event->context);
2574 * Returns option list for the poll interval setting.
2576 * @return array An array of poll interval options. Interval => description.
2578 function calendar_get_pollinterval_choices() {
2580 '0' => new \lang_string('never', 'calendar'),
2581 HOURSECS => new \lang_string('hourly', 'calendar'),
2582 DAYSECS => new \lang_string('daily', 'calendar'),
2583 WEEKSECS => new \lang_string('weekly', 'calendar'),
2584 '2628000' => new \lang_string('monthly', 'calendar'),
2585 YEARSECS => new \lang_string('annually', 'calendar')
2590 * Returns option list of available options for the calendar event type, given the current user and course.
2592 * @param int $courseid The id of the course
2593 * @return array An array containing the event types the user can create.
2595 function calendar_get_eventtype_choices($courseid) {
2597 $allowed = new \stdClass;
2598 calendar_get_allowed_types($allowed, $courseid);
2600 if ($allowed->user) {
2601 $choices['user'] = get_string('userevents', 'calendar');
2603 if ($allowed->site) {
2604 $choices['site'] = get_string('siteevents', 'calendar');
2606 if (!empty($allowed->courses)) {
2607 $choices['course'] = get_string('courseevents', 'calendar');
2609 if (!empty($allowed->categories)) {
2610 $choices['category'] = get_string('categoryevents', 'calendar');
2612 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2613 $choices['group'] = get_string('group');
2616 return array($choices, $allowed->groups);
2620 * Add an iCalendar subscription to the database.
2622 * @param stdClass $sub The subscription object (e.g. from the form)
2623 * @return int The insert ID, if any.
2625 function calendar_add_subscription($sub) {
2626 global $DB, $USER, $SITE;
2628 if ($sub->eventtype === 'site') {
2629 $sub->courseid = $SITE->id;
2630 } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
2631 $sub->courseid = $sub->course;
2632 } else if ($sub->eventtype === 'category') {
2633 $sub->categoryid = $sub->category;
2638 $sub->userid = $USER->id;
2640 // File subscriptions never update.
2641 if (empty($sub->url)) {
2642 $sub->pollinterval = 0;
2645 if (!empty($sub->name)) {
2646 if (empty($sub->id)) {
2647 $id = $DB->insert_record('event_subscriptions', $sub);
2648 // We cannot cache the data here because $sub is not complete.
2650 // Trigger event, calendar subscription added.
2651 $eventparams = array('objectid' => $sub->id,
2652 'context' => calendar_get_calendar_context($sub),
2653 'other' => array('eventtype' => $sub->eventtype, 'courseid' => $sub->courseid)
2655 $event = \core\event\calendar_subscription_created::create($eventparams);
2659 // Why are we doing an update here?
2660 calendar_update_subscription($sub);
2664 print_error('errorbadsubscription', 'importcalendar');
2669 * Add an iCalendar event to the Moodle calendar.
2671 * @param stdClass $event The RFC-2445 iCalendar event
2672 * @param int $courseid The course ID
2673 * @param int $subscriptionid The iCalendar subscription ID
2674 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2675 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2676 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2678 function calendar_add_icalendar_event($event, $courseid, $subscriptionid, $timezone='UTC') {
2681 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2682 if (empty($event->properties['SUMMARY'])) {
2686 $name = $event->properties['SUMMARY'][0]->value;
2687 $name = str_replace('\n', '<br />', $name);
2688 $name = str_replace('\\', '', $name);
2689 $name = preg_replace('/\s+/u', ' ', $name);
2691 $eventrecord = new \stdClass;
2692 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
2694 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2697 $description = $event->properties['DESCRIPTION'][0]->value;
2698 $description = clean_param($description, PARAM_NOTAGS);
2699 $description = str_replace('\n', '<br />', $description);
2700 $description = str_replace('\\', '', $description);
2701 $description = preg_replace('/\s+/u', ' ', $description);
2703 $eventrecord->description = $description;
2705 // Probably a repeating event with RRULE etc. TODO: skip for now.
2706 if (empty($event->properties['DTSTART'][0]->value)) {
2710 if (isset($event->properties['DTSTART'][0]->parameters['TZID'])) {
2711 $tz = $event->properties['DTSTART'][0]->parameters['TZID'];
2715 $tz = \core_date::normalise_timezone($tz);
2716 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value . ' ' . $tz);
2717 if (empty($event->properties['DTEND'])) {
2718 $eventrecord->timeduration = 0; // No duration if no end time specified.
2720 if (isset($event->properties['DTEND'][0]->parameters['TZID'])) {
2721 $endtz = $event->properties['DTEND'][0]->parameters['TZID'];
2725 $endtz = \core_date::normalise_timezone($endtz);
2726 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value . ' ' . $endtz) - $eventrecord->timestart;
2729 // Check to see if it should be treated as an all day event.
2730 if ($eventrecord->timeduration == DAYSECS) {
2731 // Check to see if the event started at Midnight on the imported calendar.
2732 date_default_timezone_set($timezone);
2733 if (date('H:i:s', $eventrecord->timestart) === "00:00:00") {
2734 // This event should be an all day event. This is not correct, we don't do anything differently for all day events.
2736 $eventrecord->timeduration = 0;
2738 \core_date::set_default_server_timezone();
2741 $eventrecord->uuid = $event->properties['UID'][0]->value;
2742 $eventrecord->timemodified = time();
2744 // Add the iCal subscription details if required.
2745 // We should never do anything with an event without a subscription reference.
2746 $sub = calendar_get_subscription($subscriptionid);
2747 $eventrecord->subscriptionid = $subscriptionid;
2748 $eventrecord->userid = $sub->userid;
2749 $eventrecord->groupid = $sub->groupid;
2750 $eventrecord->courseid = $sub->courseid;
2751 $eventrecord->eventtype = $sub->eventtype;
2753 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid,
2754 'subscriptionid' => $eventrecord->subscriptionid))) {
2755 $eventrecord->id = $updaterecord->id;
2756 $return = CALENDAR_IMPORT_EVENT_UPDATED; // Update.
2758 $return = CALENDAR_IMPORT_EVENT_INSERTED; // Insert.
2760 if ($createdevent = \calendar_event::create($eventrecord, false)) {
2761 if (!empty($event->properties['RRULE'])) {
2762 // Repeating events.
2763 date_default_timezone_set($tz); // Change time zone to parse all events.
2764 $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
2765 $rrule->parse_rrule();
2766 $rrule->create_events($createdevent);
2767 \core_date::set_default_server_timezone(); // Change time zone back to what it was.
2776 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2778 * @param int $subscriptionid The ID of the subscription we are acting upon.
2779 * @param int $pollinterval The poll interval to use.
2780 * @param int $action The action to be performed. One of update or remove.
2781 * @throws dml_exception if invalid subscriptionid is provided
2782 * @return string A log of the import progress, including errors
2784 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2785 // Fetch the subscription from the database making sure it exists.
2786 $sub = calendar_get_subscription($subscriptionid);
2788 // Update or remove the subscription, based on action.
2790 case CALENDAR_SUBSCRIPTION_UPDATE:
2791 // Skip updating file subscriptions.
2792 if (empty($sub->url)) {
2795 $sub->pollinterval = $pollinterval;
2796 calendar_update_subscription($sub);
2798 // Update the events.
2799 return "<p>" . get_string('subscriptionupdated', 'calendar', $sub->name) . "</p>" .
2800 calendar_update_subscription_events($subscriptionid);
2801 case CALENDAR_SUBSCRIPTION_REMOVE:
2802 calendar_delete_subscription($subscriptionid);
2803 return get_string('subscriptionremoved', 'calendar', $sub->name);
2812 * Delete subscription and all related events.
2814 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
2816 function calendar_delete_subscription($subscription) {
2819 if (!is_object($subscription)) {
2820 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST);
2823 // Delete subscription and related events.
2824 $DB->delete_records('event', array('subscriptionid' => $subscription->id));
2825 $DB->delete_records('event_subscriptions', array('id' => $subscription->id));
2826 \cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id));
2828 // Trigger event, calendar subscription deleted.
2829 $eventparams = array('objectid' => $subscription->id,
2830 'context' => calendar_get_calendar_context($subscription),
2831 'other' => array('courseid' => $subscription->courseid)
2833 $event = \core\event\calendar_subscription_deleted::create($eventparams);
2838 * From a URL, fetch the calendar and return an iCalendar object.
2840 * @param string $url The iCalendar URL
2841 * @return iCalendar The iCalendar object
2843 function calendar_get_icalendar($url) {
2846 require_once($CFG->libdir . '/filelib.php');
2848 $curl = new \curl();
2849 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
2850 $calendar = $curl->get($url);
2852 // Http code validation should actually be the job of curl class.
2853 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
2854 throw new \moodle_exception('errorinvalidicalurl', 'calendar');
2857 $ical = new \iCalendar();
2858 $ical->unserialize($calendar);
2864 * Import events from an iCalendar object into a course calendar.
2866 * @param iCalendar $ical The iCalendar object.
2867 * @param int $courseid The course ID for the calendar.
2868 * @param int $subscriptionid The subscription ID.
2869 * @return string A log of the import progress, including errors.
2871 function calendar_import_icalendar_events($ical, $courseid, $subscriptionid = null) {
2878 // Large calendars take a while...
2880 \core_php_time_limit::raise(300);
2883 // Mark all events in a subscription with a zero timestamp.
2884 if (!empty($subscriptionid)) {
2885 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
2886 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
2889 // Grab the timezone from the iCalendar file to be used later.
2890 if (isset($ical->properties['X-WR-TIMEZONE'][0]->value)) {
2891 $timezone = $ical->properties['X-WR-TIMEZONE'][0]->value;
2897 foreach ($ical->components['VEVENT'] as $event) {
2898 $res = calendar_add_icalendar_event($event, $courseid, $subscriptionid, $timezone);
2900 case CALENDAR_IMPORT_EVENT_UPDATED:
2903 case CALENDAR_IMPORT_EVENT_INSERTED:
2907 $return .= '<p>' . get_string('erroraddingevent', 'calendar') . ': ';
2908 if (empty($event->properties['SUMMARY'])) {
2909 $return .= '(' . get_string('notitle', 'calendar') . ')';
2911 $return .= $event->properties['SUMMARY'][0]->value;
2913 $return .= "</p>\n";
2918 $return .= "<p>" . get_string('eventsimported', 'calendar', $eventcount) . "</p> ";
2919 $return .= "<p>" . get_string('eventsupdated', 'calendar', $updatecount) . "</p>";
2921 // Delete remaining zero-marked events since they're not in remote calendar.
2922 if (!empty($subscriptionid)) {
2923 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
2924 if (!empty($deletecount)) {
2925 $DB->delete_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
2926 $return .= "<p> " . get_string('eventsdeleted', 'calendar') . ": {$deletecount} </p>\n";
2934 * Fetch a calendar subscription and update the events in the calendar.
2936 * @param int $subscriptionid The course ID for the calendar.
2937 * @return string A log of the import progress, including errors.
2939 function calendar_update_subscription_events($subscriptionid) {
2940 $sub = calendar_get_subscription($subscriptionid);
2942 // Don't update a file subscription.
2943 if (empty($sub->url)) {
2944 return 'File subscription not updated.';
2947 $ical = calendar_get_icalendar($sub->url);
2948 $return = calendar_import_icalendar_events($ical, $sub->courseid, $subscriptionid);
2949 $sub->lastupdated = time();
2951 calendar_update_subscription($sub);
2957 * Update a calendar subscription. Also updates the associated cache.
2959 * @param stdClass|array $subscription Subscription record.
2960 * @throws coding_exception If something goes wrong
2963 function calendar_update_subscription($subscription) {
2966 if (is_array($subscription)) {
2967 $subscription = (object)$subscription;
2969 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
2970 throw new \coding_exception('Cannot update a subscription without a valid id');
2973 $DB->update_record('event_subscriptions', $subscription);
2976 $cache = \cache::make('core', 'calendar_subscriptions');
2977 $cache->set($subscription->id, $subscription);
2979 // Trigger event, calendar subscription updated.
2980 $eventparams = array('userid' => $subscription->userid,
2981 'objectid' => $subscription->id,
2982 'context' => calendar_get_calendar_context($subscription),
2983 'other' => array('eventtype' => $subscription->eventtype, 'courseid' => $subscription->courseid)
2985 $event = \core\event\calendar_subscription_updated::create($eventparams);
2990 * Checks to see if the user can edit a given subscription feed.
2992 * @param mixed $subscriptionorid Subscription object or id
2993 * @return bool true if current user can edit the subscription else false
2995 function calendar_can_edit_subscription($subscriptionorid) {
2996 if (is_array($subscriptionorid)) {
2997 $subscription = (object)$subscriptionorid;
2998 } else if (is_object($subscriptionorid)) {
2999 $subscription = $subscriptionorid;
3001 $subscription = calendar_get_subscription($subscriptionorid);
3004 $allowed = new \stdClass;
3005 $courseid = $subscription->courseid;
3006 $groupid = $subscription->groupid;
3008 calendar_get_allowed_types($allowed, $courseid);
3009 switch ($subscription->eventtype) {
3011 return $allowed->user;
3013 if (isset($allowed->courses[$courseid])) {
3014 return $allowed->courses[$courseid];
3019 return $allowed->site;
3021 if (isset($allowed->groups[$groupid])) {
3022 return $allowed->groups[$groupid];
3032 * Helper function to determine the context of a calendar subscription.
3033 * Subscriptions can be created in two contexts COURSE, or USER.
3035 * @param stdClass $subscription
3036 * @return context instance
3038 function calendar_get_calendar_context($subscription) {
3039 // Determine context based on calendar type.
3040 if ($subscription->eventtype === 'site') {
3041 $context = \context_course::instance(SITEID);
3042 } else if ($subscription->eventtype === 'group' || $subscription->eventtype === 'course') {
3043 $context = \context_course::instance($subscription->courseid);
3045 $context = \context_user::instance($subscription->userid);
3051 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
3053 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3057 function core_calendar_user_preferences() {
3059 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED, 'default' => '0',
3060 'choices' => array('0', CALENDAR_TF_12, CALENDAR_TF_24)
3062 $preferences['calendar_startwday'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3063 'choices' => array(0, 1, 2, 3, 4, 5, 6));
3064 $preferences['calendar_maxevents'] = array('type' => PARAM_INT, 'choices' => range(1, 20));
3065 $preferences['calendar_lookahead'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 365,
3066 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3067 $preferences['calendar_persistflt'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3068 'choices' => array(0, 1));
3069 return $preferences;
3073 * Get legacy calendar events
3075 * @param int $tstart Start time of time range for events
3076 * @param int $tend End time of time range for events
3077 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3078 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3079 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3080 * @param boolean $withduration whether only events starting within time range selected
3081 * or events in progress/already started selected as well
3082 * @param boolean $ignorehidden whether to select only visible events or all events
3083 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3085 function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses,
3086 $withduration = true, $ignorehidden = true, $categories = []) {
3087 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3088 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3089 // parameters, but with the new API method, only null and arrays are accepted.
3090 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3091 // If parameter is true, return null.
3092 if ($param === true) {
3096 // If parameter is false, return an empty array.
3097 if ($param === false) {
3101 // If the parameter is a scalar value, enclose it in an array.
3102 if (!is_array($param)) {
3106 // No normalisation required.
3108 }, [$users, $groups, $courses, $categories]);
3110 $mapper = \core_calendar\local\event\container::get_event_mapper();
3111 $events = \core_calendar\local\api::get_events(
3128 return array_reduce($events, function($carry, $event) use ($mapper) {
3129 return $carry + [$event->get_id() => $mapper->from_event_to_stdclass($event)];
3135 * Get the calendar view output.
3137 * @param \calendar_information $calendar The calendar being represented
3138 * @param string $view The type of calendar to have displayed
3139 * @param bool $includenavigation Whether to include navigation
3140 * @return array[array, string]
3142 function calendar_get_view(\calendar_information $calendar, $view, $includenavigation = true) {
3145 $renderer = $PAGE->get_renderer('core_calendar');
3146 $type = \core_calendar\type_factory::get_calendar_instance();
3148 // Calculate the bounds of the month.
3149 $date = $type->timestamp_to_date_array($calendar->time);
3151 if ($view === 'day') {
3152 $tstart = $type->convert_to_timestamp($date['year'], $date['mon'], $date['mday']);
3153 $tend = $tstart + DAYSECS - 1;
3154 } else if ($view === 'upcoming') {
3155 if (isset($CFG->calendar_lookahead)) {
3156 $defaultlookahead = intval($CFG->calendar_lookahead);
3158 $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD;
3160 $tstart = $type->convert_to_timestamp($date['year'], $date['mon'], 1);
3161 $tend = $tstart + get_user_preferences('calendar_lookahead', $defaultlookahead);
3163 $tstart = $type->convert_to_timestamp($date['year'], $date['mon'], 1);
3164 $monthdays = $type->get_num_days_in_month($date['year'], $date['mon']);
3165 $tend = $tstart + ($monthdays * DAYSECS) - 1;
3166 $selectortitle = get_string('detailedmonthviewfor', 'calendar');
3167 if ($view === 'mini' || $view === 'minithree') {
3168 $template = 'core_calendar/calendar_mini';
3170 $template = 'core_calendar/calendar_month';
3174 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3175 // If parameter is true, return null.
3176 if ($param === true) {
3180 // If parameter is false, return an empty array.
3181 if ($param === false) {
3185 // If the parameter is a scalar value, enclose it in an array.
3186 if (!is_array($param)) {
3190 // No normalisation required.
3192 }, [$calendar->users, $calendar->groups, $calendar->courses, $calendar->categories]);
3194 $events = \core_calendar\local\api::get_events(
3210 if ($proxy = $event->get_course_module()) {
3211 $cminfo = $proxy->get_proxied_instance();
3212 return $cminfo->uservisible;
3215 if ($proxy = $event->get_category()) {
3216 $category = $proxy->get_proxied_instance();
3218 return $category->is_uservisible();
3226 'events' => $events,
3227 'cache' => new \core_calendar\external\events_related_objects_cache($events),
3232 if ($view == "month" || $view == "mini" || $view == "minithree") {
3233 $month = new \core_calendar\external\month_exporter($calendar, $type, $related);
3234 $month->set_includenavigation($includenavigation);
3235 $data = $month->export($renderer);
3236 } else if ($view == "day") {
3237 $daydata = $type->timestamp_to_date_array($tstart);
3238 $day = new \core_calendar\external\day_exporter($calendar, $daydata, $related);
3239 $data = $day->export($renderer);
3240 $template = 'core_calendar/day_detailed';
3243 return [$data, $template];
3247 * Request and render event form fragment.
3249 * @param array $args The fragment arguments.
3250 * @return string The rendered mform fragment.
3252 function calendar_output_fragment_event_form($args) {
3253 global $CFG, $OUTPUT, $USER;
3257 $eventid = isset($args['eventid']) ? clean_param($args['eventid'], PARAM_INT) : null;
3258 $starttime = isset($args['starttime']) ? clean_param($args['starttime'], PARAM_INT) : null;
3259 $courseid = isset($args['courseid']) ? clean_param($args['courseid'], PARAM_INT) : null;
3260 $categoryid = isset($args['categoryid']) ? clean_param($args['categoryid'], PARAM_INT) : null;
3262 $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
3263 $context = \context_user::instance($USER->id);
3264 $editoroptions = \core_calendar\local\event\forms\create::build_editor_options($context);
3265 $formoptions = ['editoroptions' => $editoroptions];
3269 parse_str(clean_param($args['formdata'], PARAM_TEXT), $data);
3270 if (isset($data['description']['itemid'])) {
3271 $draftitemid = $data['description']['itemid'];
3276 $formoptions['starttime'] = $starttime;
3279 if (is_null($eventid)) {
3280 $mform = new \core_calendar\local\event\forms\create(
3289 if ($courseid != SITEID) {
3290 $data['eventtype'] = 'course';
3291 $data['courseid'] = $courseid;
3292 $data['groupcourseid'] = $courseid;
3293 } else if (!empty($categoryid)) {
3294 $data['eventtype'] = 'category';
3295 $data['categoryid'] = $categoryid;
3297 $mform->set_data($data);
3299 $event = calendar_event::load($eventid);
3300 $mapper = new \core_calendar\local\event\mappers\create_update_form_mapper();
3301 $eventdata = $mapper->from_legacy_event_to_data($event);
3302 $data = array_merge((array) $eventdata, $data);
3303 $event->count_repeats();
3304 $formoptions['event'] = $event;
3305 $data['description']['text'] = file_prepare_draft_area(
3307 $event->context->id,
3309 'event_description',
3312 $data['description']['text']
3314 $data['description']['itemid'] = $draftitemid;
3316 $mform = new \core_calendar\local\event\forms\update(
3325 $mform->set_data($data);
3327 // Check to see if this event is part of a subscription or import.
3328 // If so display a warning on edit.
3329 if (isset($event->subscriptionid) && ($event->subscriptionid != null)) {
3330 $renderable = new \core\output\notification(
3331 get_string('eventsubscriptioneditwarning', 'calendar'),
3332 \core\output\notification::NOTIFY_INFO
3335 $html .= $OUTPUT->render($renderable);
3340 $mform->is_validated();
3343 $html .= $mform->render();
3348 * Calculate the timestamp from the supplied Gregorian Year, Month, and Day.
3350 * @param int $d The day
3351 * @param int $m The month
3352 * @param int $y The year
3353 * @param int $time The timestamp to use instead of a separate y/m/d.
3354 * @return int The timestamp
3356 function calendar_get_timestamp($d, $m, $y, $time = 0) {
3357 // If a day, month and year were passed then convert it to a timestamp. If these were passed
3358 // then we can assume the day, month and year are passed as Gregorian, as no where in core
3359 // should we be passing these values rather than the time.
3360 if (!empty($d) && !empty($m) && !empty($y)) {
3361 if (checkdate($m, $d, $y)) {
3362 $time = make_timestamp($y, $m, $d);
3366 } else if (empty($time)) {
3374 * Get the calendar footer options.
3376 * @param calendar_information $calendar The calendar information object.
3377 * @return array The data for template and template name.
3379 function calendar_get_footer_options($calendar) {
3380 global $CFG, $USER, $DB, $PAGE;
3382 // Generate hash for iCal link.
3383 $rawhash = $USER->id . $DB->get_field('user', 'password', ['id' => $USER->id]) . $CFG->calendar_exportsalt;
3384 $authtoken = sha1($rawhash);
3386 $renderer = $PAGE->get_renderer('core_calendar');
3387 $footer = new \core_calendar\external\footer_options_exporter($calendar, $USER->id, $authtoken);
3388 $data = $footer->export($renderer);
3389 $template = 'core_calendar/footer_options';
3391 return [$data, $template];
3395 * Get the list of potential calendar filter types as a type => name
3400 function calendar_get_filter_types() {
3409 return array_map(function($type) {
3412 'name' => get_string("eventtype{$type}", "calendar"),
3418 * Check whether the specified event type is valid.
3420 * @param string $type
3423 function calendar_is_valid_eventtype($type) {
3431 return in_array($type, $validtypes);