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
31 * These are read by the administration component to provide default values
35 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
37 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
40 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
42 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
45 * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
47 define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
49 // This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
50 // Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
53 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
55 define('CALENDAR_DEFAULT_WEEKEND', 65);
58 * CALENDAR_URL - path to calendar's folder
60 define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
63 * CALENDAR_TF_24 - Calendar time in 24 hours format
65 define('CALENDAR_TF_24', '%H:%M');
68 * CALENDAR_TF_12 - Calendar time in 12 hours format
70 define('CALENDAR_TF_12', '%I:%M %p');
73 * CALENDAR_EVENT_GLOBAL - Global calendar event types
75 define('CALENDAR_EVENT_GLOBAL', 1);
78 * CALENDAR_EVENT_COURSE - Course calendar event types
80 define('CALENDAR_EVENT_COURSE', 2);
83 * CALENDAR_EVENT_GROUP - group calendar event types
85 define('CALENDAR_EVENT_GROUP', 4);
88 * CALENDAR_EVENT_USER - user calendar event types
90 define('CALENDAR_EVENT_USER', 8);
94 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
96 define('CALENDAR_IMPORT_FROM_FILE', 0);
99 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
101 define('CALENDAR_IMPORT_FROM_URL', 1);
104 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
106 define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
109 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
111 define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
114 * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
116 define('CALENDAR_SUBSCRIPTION_UPDATE', 1);
119 * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
121 define('CALENDAR_SUBSCRIPTION_REMOVE', 2);
124 * CALENDAR_EVENT_USER_OVERRIDE_PRIORITY - Constant for the user override priority.
126 define('CALENDAR_EVENT_USER_OVERRIDE_PRIORITY', 0);
129 * CALENDAR_EVENT_TYPE_STANDARD - Standard events.
131 define('CALENDAR_EVENT_TYPE_STANDARD', 0);
134 * CALENDAR_EVENT_TYPE_ACTION - Action events.
136 define('CALENDAR_EVENT_TYPE_ACTION', 1);
139 * Manage calendar events.
141 * This class provides the required functionality in order to manage calendar events.
142 * It was introduced as part of Moodle 2.0 and was created in order to provide a
143 * better framework for dealing with calendar events in particular regard to file
144 * handling through the new file API.
146 * @package core_calendar
148 * @copyright 2009 Sam Hemelryk
149 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
151 * @property int $id The id within the event table
152 * @property string $name The name of the event
153 * @property string $description The description of the event
154 * @property int $format The format of the description FORMAT_?
155 * @property int $courseid The course the event is associated with (0 if none)
156 * @property int $groupid The group the event is associated with (0 if none)
157 * @property int $userid The user the event is associated with (0 if none)
158 * @property int $repeatid If this is a repeated event this will be set to the
160 * @property string $modulename If added by a module this will be the module name
161 * @property int $instance If added by a module this will be the module instance
162 * @property string $eventtype The event type
163 * @property int $timestart The start time as a timestamp
164 * @property int $timeduration The duration of the event in seconds
165 * @property int $visible 1 if the event is visible
166 * @property int $uuid ?
167 * @property int $sequence ?
168 * @property int $timemodified The time last modified as a timestamp
170 class calendar_event {
172 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
173 protected $properties = null;
175 /** @var string The converted event discription with file paths resolved.
176 * This gets populated when someone requests description for the first time */
177 protected $_description = null;
179 /** @var array The options to use with this description editor */
180 protected $editoroptions = array(
182 'forcehttps' => false,
185 'trusttext' => false);
187 /** @var object The context to use with the description editor */
188 protected $editorcontext = null;
191 * Instantiates a new event and optionally populates its properties with the data provided.
193 * @param \stdClass $data Optional. An object containing the properties to for
196 public function __construct($data = null) {
199 // First convert to object if it is not already (should either be object or assoc array).
200 if (!is_object($data)) {
201 $data = (object) $data;
204 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
206 $data->eventrepeats = 0;
208 if (empty($data->id)) {
212 if (!empty($data->subscriptionid)) {
213 $data->subscription = calendar_get_subscription($data->subscriptionid);
216 // Default to a user event.
217 if (empty($data->eventtype)) {
218 $data->eventtype = 'user';
221 // Default to the current user.
222 if (empty($data->userid)) {
223 $data->userid = $USER->id;
226 if (!empty($data->timeduration) && is_array($data->timeduration)) {
227 $data->timeduration = make_timestamp(
228 $data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'],
229 $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
232 if (!empty($data->description) && is_array($data->description)) {
233 $data->format = $data->description['format'];
234 $data->description = $data->description['text'];
235 } else if (empty($data->description)) {
236 $data->description = '';
237 $data->format = editors_get_preferred_format();
240 // Ensure form is defaulted correctly.
241 if (empty($data->format)) {
242 $data->format = editors_get_preferred_format();
245 $this->properties = $data;
247 if (empty($data->context)) {
248 $this->properties->context = $this->calculate_context();
255 * Attempts to call a set_$key method if one exists otherwise falls back
256 * to simply set the property.
258 * @param string $key property name
259 * @param mixed $value value of the property
261 public function __set($key, $value) {
262 if (method_exists($this, 'set_'.$key)) {
263 $this->{'set_'.$key}($value);
265 $this->properties->{$key} = $value;
271 * Attempts to call a get_$key method to return the property and ralls over
272 * to return the raw property.
274 * @param string $key property name
275 * @return mixed property value
276 * @throws \coding_exception
278 public function __get($key) {
279 if (method_exists($this, 'get_'.$key)) {
280 return $this->{'get_'.$key}();
282 if (!property_exists($this->properties, $key)) {
283 throw new \coding_exception('Undefined property requested');
285 return $this->properties->{$key};
289 * Magic isset method.
291 * PHP needs an isset magic method if you use the get magic method and
292 * still want empty calls to work.
294 * @param string $key $key property name
295 * @return bool|mixed property value, false if property is not exist
297 public function __isset($key) {
298 return !empty($this->properties->{$key});
302 * Calculate the context value needed for an event.
304 * Event's type can be determine by the available value store in $data
305 * It is important to check for the existence of course/courseid to determine
307 * Default value is set to CONTEXT_USER
309 * @return \stdClass The context object.
311 protected function calculate_context() {
315 if (isset($this->properties->courseid) && $this->properties->courseid > 0) {
316 $context = \context_course::instance($this->properties->courseid);
317 } else if (isset($this->properties->course) && $this->properties->course > 0) {
318 $context = \context_course::instance($this->properties->course);
319 } else if (isset($this->properties->groupid) && $this->properties->groupid > 0) {
320 $group = $DB->get_record('groups', array('id' => $this->properties->groupid));
321 $context = \context_course::instance($group->courseid);
322 } else if (isset($this->properties->userid) && $this->properties->userid > 0
323 && $this->properties->userid == $USER->id) {
324 $context = \context_user::instance($this->properties->userid);
325 } else if (isset($this->properties->userid) && $this->properties->userid > 0
326 && $this->properties->userid != $USER->id &&
327 isset($this->properties->instance) && $this->properties->instance > 0) {
328 $cm = get_coursemodule_from_instance($this->properties->modulename, $this->properties->instance, 0,
330 $context = \context_course::instance($cm->course);
332 $context = \context_user::instance($this->properties->userid);
339 * Returns an array of editoroptions for this event.
341 * @return array event editor options
343 protected function get_editoroptions() {
344 return $this->editoroptions;
348 * Returns an event description: Called by __get
349 * Please use $blah = $event->description;
351 * @return string event description
353 protected function get_description() {
356 require_once($CFG->libdir . '/filelib.php');
358 if ($this->_description === null) {
359 // Check if we have already resolved the context for this event.
360 if ($this->editorcontext === null) {
361 // Switch on the event type to decide upon the appropriate context to use for this event.
362 $this->editorcontext = $this->properties->context;
363 if ($this->properties->eventtype != 'user' && $this->properties->eventtype != 'course'
364 && $this->properties->eventtype != 'site' && $this->properties->eventtype != 'group') {
365 return clean_text($this->properties->description, $this->properties->format);
369 // Work out the item id for the editor, if this is a repeated event
370 // then the files will be associated with the original.
371 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
372 $itemid = $this->properties->repeatid;
374 $itemid = $this->properties->id;
377 // Convert file paths in the description so that things display correctly.
378 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php',
379 $this->editorcontext->id, 'calendar', 'event_description', $itemid);
380 // Clean the text so no nasties get through.
381 $this->_description = clean_text($this->_description, $this->properties->format);
384 // Finally return the description.
385 return $this->_description;
389 * Return the number of repeat events there are in this events series.
391 * @return int number of event repeated
393 public function count_repeats() {
395 if (!empty($this->properties->repeatid)) {
396 $this->properties->eventrepeats = $DB->count_records('event',
397 array('repeatid' => $this->properties->repeatid));
398 // We don't want to count ourselves.
399 $this->properties->eventrepeats--;
401 return $this->properties->eventrepeats;
405 * Update or create an event within the database
407 * Pass in a object containing the event properties and this function will
408 * insert it into the database and deal with any associated files
410 * @see self::create()
411 * @see self::update()
413 * @param \stdClass $data object of event
414 * @param bool $checkcapability if moodle should check calendar managing capability or not
415 * @return bool event updated
417 public function update($data, $checkcapability=true) {
420 foreach ($data as $key => $value) {
421 $this->properties->$key = $value;
424 $this->properties->timemodified = time();
425 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
427 // Prepare event data.
429 'context' => $this->properties->context,
430 'objectid' => $this->properties->id,
432 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
433 'timestart' => $this->properties->timestart,
434 'name' => $this->properties->name
438 if (empty($this->properties->id) || $this->properties->id < 1) {
440 if ($checkcapability) {
441 if (!calendar_add_event_allowed($this->properties)) {
442 print_error('nopermissiontoupdatecalendar');
447 switch ($this->properties->eventtype) {
449 $this->properties->courseid = 0;
450 $this->properties->course = 0;
451 $this->properties->groupid = 0;
452 $this->properties->userid = $USER->id;
455 $this->properties->courseid = SITEID;
456 $this->properties->course = SITEID;
457 $this->properties->groupid = 0;
458 $this->properties->userid = $USER->id;
461 $this->properties->groupid = 0;
462 $this->properties->userid = $USER->id;
465 $this->properties->userid = $USER->id;
468 // We should NEVER get here, but just incase we do lets fail gracefully.
469 $usingeditor = false;
473 // If we are actually using the editor, we recalculate the context because some default values
474 // were set when calculate_context() was called from the constructor.
476 $this->properties->context = $this->calculate_context();
477 $this->editorcontext = $this->properties->context;
480 $editor = $this->properties->description;
481 $this->properties->format = $this->properties->description['format'];
482 $this->properties->description = $this->properties->description['text'];
485 // Insert the event into the database.
486 $this->properties->id = $DB->insert_record('event', $this->properties);
489 $this->properties->description = file_save_draft_area_files(
491 $this->editorcontext->id,
494 $this->properties->id,
495 $this->editoroptions,
497 $this->editoroptions['forcehttps']);
498 $DB->set_field('event', 'description', $this->properties->description,
499 array('id' => $this->properties->id));
502 // Log the event entry.
503 $eventargs['objectid'] = $this->properties->id;
504 $eventargs['context'] = $this->properties->context;
505 $event = \core\event\calendar_event_created::create($eventargs);
508 $repeatedids = array();
510 if (!empty($this->properties->repeat)) {
511 $this->properties->repeatid = $this->properties->id;
512 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id' => $this->properties->id));
514 $eventcopy = clone($this->properties);
515 unset($eventcopy->id);
517 $timestart = new \DateTime('@' . $eventcopy->timestart);
518 $timestart->setTimezone(\core_date::get_user_timezone_object());
520 for ($i = 1; $i < $eventcopy->repeats; $i++) {
522 $timestart->add(new \DateInterval('P7D'));
523 $eventcopy->timestart = $timestart->getTimestamp();
525 // Get the event id for the log record.
526 $eventcopyid = $DB->insert_record('event', $eventcopy);
528 // If the context has been set delete all associated files.
530 $fs = get_file_storage();
531 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description',
532 $this->properties->id);
533 foreach ($files as $file) {
534 $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
538 $repeatedids[] = $eventcopyid;
541 $eventargs['objectid'] = $eventcopyid;
542 $eventargs['other']['timestart'] = $eventcopy->timestart;
543 $event = \core\event\calendar_event_created::create($eventargs);
551 if ($checkcapability) {
552 if (!calendar_edit_event_allowed($this->properties)) {
553 print_error('nopermissiontoupdatecalendar');
558 if ($this->editorcontext !== null) {
559 $this->properties->description = file_save_draft_area_files(
560 $this->properties->description['itemid'],
561 $this->editorcontext->id,
564 $this->properties->id,
565 $this->editoroptions,
566 $this->properties->description['text'],
567 $this->editoroptions['forcehttps']);
569 $this->properties->format = $this->properties->description['format'];
570 $this->properties->description = $this->properties->description['text'];
574 $event = $DB->get_record('event', array('id' => $this->properties->id));
576 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
578 if ($updaterepeated) {
580 if ($this->properties->timestart != $event->timestart) {
581 $timestartoffset = $this->properties->timestart - $event->timestart;
582 $sql = "UPDATE {event}
585 timestart = timestart + ?,
589 $params = array($this->properties->name, $this->properties->description, $timestartoffset,
590 $this->properties->timeduration, time(), $event->repeatid);
592 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
593 $params = array($this->properties->name, $this->properties->description,
594 $this->properties->timeduration, time(), $event->repeatid);
596 $DB->execute($sql, $params);
598 // Trigger an update event for each of the calendar event.
599 $events = $DB->get_records('event', array('repeatid' => $event->repeatid), '', '*');
600 foreach ($events as $calendarevent) {
601 $eventargs['objectid'] = $calendarevent->id;
602 $eventargs['other']['timestart'] = $calendarevent->timestart;
603 $event = \core\event\calendar_event_updated::create($eventargs);
604 $event->add_record_snapshot('event', $calendarevent);
608 $DB->update_record('event', $this->properties);
609 $event = self::load($this->properties->id);
610 $this->properties = $event->properties();
612 // Trigger an update event.
613 $event = \core\event\calendar_event_updated::create($eventargs);
614 $event->add_record_snapshot('event', $this->properties);
623 * Deletes an event and if selected an repeated events in the same series
625 * This function deletes an event, any associated events if $deleterepeated=true,
626 * and cleans up any files associated with the events.
628 * @see self::delete()
630 * @param bool $deleterepeated delete event repeatedly
631 * @return bool succession of deleting event
633 public function delete($deleterepeated = false) {
636 // If $this->properties->id is not set then something is wrong.
637 if (empty($this->properties->id)) {
638 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
641 $calevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
643 $DB->delete_records('event', array('id' => $this->properties->id));
645 // Trigger an event for the delete action.
647 'context' => $this->properties->context,
648 'objectid' => $this->properties->id,
650 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
651 'timestart' => $this->properties->timestart,
652 'name' => $this->properties->name
654 $event = \core\event\calendar_event_deleted::create($eventargs);
655 $event->add_record_snapshot('event', $calevent);
658 // If we are deleting parent of a repeated event series, promote the next event in the series as parent.
659 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
660 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC",
661 array($this->properties->id), IGNORE_MULTIPLE);
662 if (!empty($newparent)) {
663 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?",
664 array($newparent, $this->properties->id));
665 // Get all records where the repeatid is the same as the event being removed.
666 $events = $DB->get_records('event', array('repeatid' => $newparent));
667 // For each of the returned events trigger an update event.
668 foreach ($events as $calendarevent) {
669 // Trigger an event for the update.
670 $eventargs['objectid'] = $calendarevent->id;
671 $eventargs['other']['timestart'] = $calendarevent->timestart;
672 $event = \core\event\calendar_event_updated::create($eventargs);
673 $event->add_record_snapshot('event', $calendarevent);
679 // If the editor context hasn't already been set then set it now.
680 if ($this->editorcontext === null) {
681 $this->editorcontext = $this->properties->context;
684 // If the context has been set delete all associated files.
685 if ($this->editorcontext !== null) {
686 $fs = get_file_storage();
687 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
688 foreach ($files as $file) {
693 // If we need to delete repeated events then we will fetch them all and delete one by one.
694 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
695 // Get all records where the repeatid is the same as the event being removed.
696 $events = $DB->get_records('event', array('repeatid' => $this->properties->repeatid));
697 // For each of the returned events populate an event object and call delete.
698 // make sure the arg passed is false as we are already deleting all repeats.
699 foreach ($events as $event) {
700 $event = new calendar_event($event);
701 $event->delete(false);
709 * Fetch all event properties.
711 * This function returns all of the events properties as an object and optionally
712 * can prepare an editor for the description field at the same time. This is
713 * designed to work when the properties are going to be used to set the default
714 * values of a moodle forms form.
716 * @param bool $prepareeditor If set to true a editor is prepared for use with
717 * the mforms editor element. (for description)
718 * @return \stdClass Object containing event properties
720 public function properties($prepareeditor = false) {
723 // First take a copy of the properties. We don't want to actually change the
724 // properties or we'd forever be converting back and forwards between an
725 // editor formatted description and not.
726 $properties = clone($this->properties);
727 // Clean the description here.
728 $properties->description = clean_text($properties->description, $properties->format);
730 // If set to true we need to prepare the properties for use with an editor
731 // and prepare the file area.
732 if ($prepareeditor) {
734 // We may or may not have a property id. If we do then we need to work
735 // out the context so we can copy the existing files to the draft area.
736 if (!empty($properties->id)) {
738 if ($properties->eventtype === 'site') {
740 $this->editorcontext = $this->properties->context;
741 } else if ($properties->eventtype === 'user') {
743 $this->editorcontext = $this->properties->context;
744 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
745 // First check the course is valid.
746 $course = $DB->get_record('course', array('id' => $properties->courseid));
748 print_error('invalidcourse');
751 $this->editorcontext = $this->properties->context;
752 // We have a course and are within the course context so we had
753 // better use the courses max bytes value.
754 $this->editoroptions['maxbytes'] = $course->maxbytes;
756 // If we get here we have a custom event type as used by some
757 // modules. In this case the event will have been added by
758 // code and we won't need the editor.
759 $this->editoroptions['maxbytes'] = 0;
760 $this->editoroptions['maxfiles'] = 0;
763 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
766 // Get the context id that is what we really want.
767 $contextid = $this->editorcontext->id;
771 // If we get here then this is a new event in which case we don't need a
772 // context as there is no existing files to copy to the draft area.
776 // If the contextid === false we don't support files so no preparing
778 if ($contextid !== false) {
779 // Just encase it has already been submitted.
780 $draftiddescription = file_get_submitted_draft_itemid('description');
781 // Prepare the draft area, this copies existing files to the draft area as well.
782 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar',
783 'event_description', $properties->id, $this->editoroptions, $properties->description);
785 $draftiddescription = 0;
788 // Structure the description field as the editor requires.
789 $properties->description = array('text' => $properties->description, 'format' => $properties->format,
790 'itemid' => $draftiddescription);
793 // Finally return the properties.
798 * Toggles the visibility of an event
800 * @param null|bool $force If it is left null the events visibility is flipped,
801 * If it is false the event is made hidden, if it is true it
803 * @return bool if event is successfully updated, toggle will be visible
805 public function toggle_visibility($force = null) {
808 // Set visible to the default if it is not already set.
809 if (empty($this->properties->visible)) {
810 $this->properties->visible = 1;
813 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
814 // Make this event visible.
815 $this->properties->visible = 1;
817 // Make this event hidden.
818 $this->properties->visible = 0;
821 // Update the database to reflect this change.
822 $success = $DB->set_field('event', 'visible', $this->properties->visible, array('id' => $this->properties->id));
823 $calendarevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
825 // Prepare event data.
827 'context' => $this->properties->context,
828 'objectid' => $this->properties->id,
830 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
831 'timestart' => $this->properties->timestart,
832 'name' => $this->properties->name
835 $event = \core\event\calendar_event_updated::create($eventargs);
836 $event->add_record_snapshot('event', $calendarevent);
843 * Returns an event object when provided with an event id.
845 * This function makes use of MUST_EXIST, if the event id passed in is invalid
846 * it will result in an exception being thrown.
848 * @param int|object $param event object or event id
849 * @return calendar_event
851 public static function load($param) {
853 if (is_object($param)) {
854 $event = new calendar_event($param);
856 $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST);
857 $event = new calendar_event($event);
863 * Creates a new event and returns an event object
865 * @param \stdClass|array $properties An object containing event properties
866 * @param bool $checkcapability Check caps or not
867 * @throws \coding_exception
869 * @return calendar_event|bool The event object or false if it failed
871 public static function create($properties, $checkcapability = true) {
872 if (is_array($properties)) {
873 $properties = (object)$properties;
875 if (!is_object($properties)) {
876 throw new \coding_exception('When creating an event properties should be either an object or an assoc array');
878 $event = new calendar_event($properties);
879 if ($event->update($properties, $checkcapability)) {
887 * Format the text using the external API.
889 * This function should we used when text formatting is required in external functions.
891 * @return array an array containing the text formatted and the text format
893 public function format_external_text() {
895 if ($this->editorcontext === null) {
896 // Switch on the event type to decide upon the appropriate context to use for this event.
897 $this->editorcontext = $this->properties->context;
899 if ($this->properties->eventtype != 'user' && $this->properties->eventtype != 'course'
900 && $this->properties->eventtype != 'site' && $this->properties->eventtype != 'group') {
901 // We don't have a context here, do a normal format_text.
902 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id);
906 // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
907 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
908 $itemid = $this->properties->repeatid;
910 $itemid = $this->properties->id;
913 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id,
914 'calendar', 'event_description', $itemid);
919 * Calendar information class
921 * This class is used simply to organise the information pertaining to a calendar
922 * and is used primarily to make information easily available.
924 * @package core_calendar
926 * @copyright 2010 Sam Hemelryk
927 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
929 class calendar_information {
932 * @var int The timestamp
934 * Rather than setting the day, month and year we will set a timestamp which will be able
935 * to be used by multiple calendars.
939 /** @var int A course id */
940 public $courseid = null;
942 /** @var array An array of courses */
943 public $courses = array();
945 /** @var array An array of groups */
946 public $groups = array();
948 /** @var array An array of users */
949 public $users = array();
952 * Creates a new instance
954 * @param int $day the number of the day
955 * @param int $month the number of the month
956 * @param int $year the number of the year
957 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
958 * and $calyear to support multiple calendars
960 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
961 // If a day, month and year were passed then convert it to a timestamp. If these were passed
962 // then we can assume the day, month and year are passed as Gregorian, as no where in core
963 // should we be passing these values rather than the time. This is done for BC.
964 if (!empty($day) || !empty($month) || !empty($year)) {
965 $date = usergetdate(time());
967 $day = $date['mday'];
970 $month = $date['mon'];
973 $year = $date['year'];
975 if (checkdate($month, $day, $year)) {
976 $this->time = make_timestamp($year, $month, $day);
978 $this->time = time();
980 } else if (!empty($time)) {
983 $this->time = time();
988 * Initialize calendar information
990 * @param stdClass $course object
991 * @param array $coursestoload An array of courses [$course->id => $course]
992 * @param bool $ignorefilters options to use filter
994 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
995 $this->courseid = $course->id;
996 $this->course = $course;
997 list($courses, $group, $user) = calendar_set_filters($coursestoload, $ignorefilters);
998 $this->courses = $courses;
999 $this->groups = $group;
1000 $this->users = $user;
1004 * Ensures the date for the calendar is correct and either sets it to now
1005 * or throws a moodle_exception if not
1007 * @param bool $defaultonow use current time
1008 * @throws moodle_exception
1009 * @return bool validation of checkdate
1011 public function checkdate($defaultonow = true) {
1012 if (!checkdate($this->month, $this->day, $this->year)) {
1014 $now = usergetdate(time());
1015 $this->day = intval($now['mday']);
1016 $this->month = intval($now['mon']);
1017 $this->year = intval($now['year']);
1020 throw new moodle_exception('invaliddate');
1027 * Gets todays timestamp for the calendar
1029 * @return int today timestamp
1031 public function timestamp_today() {
1035 * Gets tomorrows timestamp for the calendar
1037 * @return int tomorrow timestamp
1039 public function timestamp_tomorrow() {
1040 return strtotime('+1 day', $this->time);
1043 * Adds the pretend blocks for the calendar
1045 * @param core_calendar_renderer $renderer
1046 * @param bool $showfilters display filters, false is set as default
1047 * @param string|null $view preference view options (eg: day, month, upcoming)
1049 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
1051 $filters = new block_contents();
1052 $filters->content = $renderer->fake_block_filters($this->courseid, 0, 0, 0, $view, $this->courses);
1053 $filters->footer = '';
1054 $filters->title = get_string('eventskey', 'calendar');
1055 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
1057 $block = new block_contents;
1058 $block->content = $renderer->fake_block_threemonths($this);
1059 $block->footer = '';
1060 $block->title = get_string('monthlyview', 'calendar');
1061 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
1066 * Get calendar events.
1068 * @param int $tstart Start time of time range for events
1069 * @param int $tend End time of time range for events
1070 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
1071 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
1072 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
1073 * @param boolean $withduration whether only events starting within time range selected
1074 * or events in progress/already started selected as well
1075 * @param boolean $ignorehidden whether to select only visible events or all events
1076 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
1078 function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
1084 if (empty($users) && empty($groups) && empty($courses)) {
1088 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
1089 // Events from a number of users
1090 if(!empty($whereclause)) $whereclause .= ' OR';
1091 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED);
1092 $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0)";
1093 $params = array_merge($params, $inparamsusers);
1094 } else if($users === true) {
1095 // Events from ALL users
1096 if(!empty($whereclause)) $whereclause .= ' OR';
1097 $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0)';
1098 } else if($users === false) {
1099 // No user at all, do nothing
1102 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
1103 // Events from a number of groups
1104 if(!empty($whereclause)) $whereclause .= ' OR';
1105 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED);
1106 $whereclause .= " e.groupid $insqlgroups ";
1107 $params = array_merge($params, $inparamsgroups);
1108 } else if($groups === true) {
1109 // Events from ALL groups
1110 if(!empty($whereclause)) $whereclause .= ' OR ';
1111 $whereclause .= ' e.groupid != 0';
1113 // boolean false (no groups at all): we don't need to do anything
1115 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
1116 if(!empty($whereclause)) $whereclause .= ' OR';
1117 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED);
1118 $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
1119 $params = array_merge($params, $inparamscourses);
1120 } else if ($courses === true) {
1121 // Events from ALL courses
1122 if(!empty($whereclause)) $whereclause .= ' OR';
1123 $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
1126 // Security check: if, by now, we have NOTHING in $whereclause, then it means
1127 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
1128 // events no matter what. Allowing the code to proceed might return a completely
1129 // valid query with only time constraints, thus selecting ALL events in that time frame!
1130 if(empty($whereclause)) {
1135 $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1138 $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1140 if(!empty($whereclause)) {
1141 // We have additional constraints
1142 $whereclause = $timeclause.' AND ('.$whereclause.')';
1145 // Just basic time filtering
1146 $whereclause = $timeclause;
1149 if ($ignorehidden) {
1150 $whereclause .= ' AND e.visible = 1';
1155 LEFT JOIN {modules} m ON e.modulename = m.name
1156 -- Non visible modules will have a value of 0.
1157 WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
1158 ORDER BY e.timestart";
1159 $events = $DB->get_records_sql($sql, $params);
1161 if ($events === false) {
1168 * Return the days of the week.
1170 * @return array array of days
1172 function calendar_get_days() {
1173 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1174 return $calendartype->get_weekdays();
1178 * Get the subscription from a given id.
1181 * @param int $id id of the subscription
1182 * @return stdClass Subscription record from DB
1183 * @throws moodle_exception for an invalid id
1185 function calendar_get_subscription($id) {
1188 $cache = \cache::make('core', 'calendar_subscriptions');
1189 $subscription = $cache->get($id);
1190 if (empty($subscription)) {
1191 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
1192 $cache->set($id, $subscription);
1195 return $subscription;
1199 * Gets the first day of the week.
1201 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
1205 function calendar_get_starting_weekday() {
1206 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1207 return $calendartype->get_starting_weekday();
1211 * Generates the HTML for a miniature calendar.
1213 * @param array $courses list of course to list events from
1214 * @param array $groups list of group
1215 * @param array $users user's info
1216 * @param int|bool $calmonth calendar month in numeric, default is set to false
1217 * @param int|bool $calyear calendar month in numeric, default is set to false
1218 * @param string|bool $placement the place/page the calendar is set to appear - passed on the the controls function
1219 * @param int|bool $courseid id of the course the calendar is displayed on - passed on the the controls function
1220 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
1221 * and $calyear to support multiple calendars
1222 * @return string $content return html table for mini calendar
1224 function calendar_get_mini($courses, $groups, $users, $calmonth = false, $calyear = false, $placement = false,
1225 $courseid = false, $time = 0) {
1226 global $CFG, $OUTPUT;
1228 // Get the calendar type we are using.
1229 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1231 $display = new \stdClass;
1233 // Assume we are not displaying this month for now.
1234 $display->thismonth = false;
1238 // Do this check for backwards compatibility.
1239 // The core should be passing a timestamp rather than month and year.
1240 // If a month and year are passed they will be in Gregorian.
1241 if (!empty($calmonth) && !empty($calyear)) {
1242 // Ensure it is a valid date, else we will just set it to the current timestamp.
1243 if (checkdate($calmonth, 1, $calyear)) {
1244 $time = make_timestamp($calyear, $calmonth, 1);
1248 $date = usergetdate($time);
1249 if ($calmonth == $date['mon'] && $calyear == $date['year']) {
1250 $display->thismonth = true;
1252 // We can overwrite date now with the date used by the calendar type,
1253 // if it is not Gregorian, otherwise there is no need as it is already in Gregorian.
1254 if ($calendartype->get_name() != 'gregorian') {
1255 $date = $calendartype->timestamp_to_date_array($time);
1257 } else if (!empty($time)) {
1258 // Get the specified date in the calendar type being used.
1259 $date = $calendartype->timestamp_to_date_array($time);
1260 $thisdate = $calendartype->timestamp_to_date_array(time());
1261 if ($date['month'] == $thisdate['month'] && $date['year'] == $thisdate['year']) {
1262 $display->thismonth = true;
1263 // If we are the current month we want to set the date to the current date, not the start of the month.
1267 // Get the current date in the calendar type being used.
1269 $date = $calendartype->timestamp_to_date_array($time);
1270 $display->thismonth = true;
1273 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display.
1275 // Get Gregorian date for the start of the month.
1276 $gregoriandate = $calendartype->convert_to_gregorian($date['year'], $date['mon'], 1);
1278 // Store the gregorian date values to be used later.
1279 list($gy, $gm, $gd, $gh, $gmin) = array($gregoriandate['year'], $gregoriandate['month'], $gregoriandate['day'],
1280 $gregoriandate['hour'], $gregoriandate['minute']);
1282 // Get the max number of days in this month for this calendar type.
1283 $display->maxdays = calendar_days_in_month($m, $y);
1284 // Get the starting week day for this month.
1285 $startwday = dayofweek(1, $m, $y);
1286 // Get the days in a week.
1287 $daynames = calendar_get_days();
1288 // Store the number of days in a week.
1289 $numberofdaysinweek = $calendartype->get_num_weekdays();
1291 // Set the min and max weekday.
1292 $display->minwday = calendar_get_starting_weekday();
1293 $display->maxwday = $display->minwday + ($numberofdaysinweek - 1);
1295 // These are used for DB queries, so we want unixtime, so we need to use Gregorian dates.
1296 $display->tstart = make_timestamp($gy, $gm, $gd, $gh, $gmin, 0);
1297 $display->tend = $display->tstart + ($display->maxdays * DAYSECS) - 1;
1299 // Align the starting weekday to fall in our display range.
1300 // This is simple, not foolproof.
1301 if ($startwday < $display->minwday) {
1302 $startwday += $numberofdaysinweek;
1305 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ.
1306 $events = calendar_get_legacy_events($display->tstart, $display->tend, $users, $groups, $courses);
1308 // Set event course class for course events.
1309 if (!empty($events)) {
1310 foreach ($events as $eventid => $event) {
1311 if (!empty($event->modulename)) {
1312 $cm = get_coursemodule_from_instance($event->modulename, $event->instance);
1313 if (!\core_availability\info_module::is_user_visible($cm, 0, false)) {
1314 unset($events[$eventid]);
1320 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
1321 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
1322 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
1323 // arguments to this function.
1324 $hrefparams = array();
1325 if (!empty($courses)) {
1326 $courses = array_diff($courses, array(SITEID));
1327 if (count($courses) == 1) {
1328 $hrefparams['course'] = reset($courses);
1332 // We want to have easy access by day, since the display is on a per-day basis.
1333 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
1335 // Accessibility: added summary and <abbr> elements.
1336 $summary = get_string('calendarheading', 'calendar', userdate($display->tstart, get_string('strftimemonthyear')));
1338 $content .= '<table class="minicalendar calendartable" summary="' . $summary . '">';
1339 if (($placement !== false) && ($courseid !== false)) {
1340 $content .= '<caption>' . calendar_top_controls($placement,
1341 array('id' => $courseid, 'time' => $time)) . '</caption>';
1343 $content .= '<tr class="weekdays">'; // Header row: day names.
1345 // Print out the names of the weekdays.
1346 for ($i = $display->minwday; $i <= $display->maxwday; $i++) {
1347 $pos = $i % $numberofdaysinweek;
1348 $content .= '<th scope="col"><abbr title="' . $daynames[$pos]['fullname'] . '">' .
1349 $daynames[$pos]['shortname'] . "</abbr></th>\n";
1352 $content .= '</tr><tr>'; // End of day names; prepare for day numbers.
1354 // For the table display. $week is the row; $dayweek is the column.
1355 $dayweek = $startwday;
1357 // Padding (the first week may have blank days in the beginning).
1358 for ($i = $display->minwday; $i < $startwday; ++$i) {
1359 $content .= '<td class="dayblank"> </td>' ."\n";
1362 $weekend = CALENDAR_DEFAULT_WEEKEND;
1363 if (isset($CFG->calendar_weekend)) {
1364 $weekend = intval($CFG->calendar_weekend);
1367 // Now display all the calendar.
1368 $daytime = strtotime('-1 day', $display->tstart);
1369 for ($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
1370 $cellattributes = array();
1371 $daytime = strtotime('+1 day', $daytime);
1372 if ($dayweek > $display->maxwday) {
1373 // We need to change week (table row).
1374 $content .= '</tr><tr>';
1375 $dayweek = $display->minwday;
1379 if ($weekend & (1 << ($dayweek % $numberofdaysinweek))) {
1380 // Weekend. This is true no matter what the exact range is.
1381 $class = 'weekend day';
1383 // Normal working day.
1387 $eventids = array();
1388 if (!empty($eventsbyday[$day])) {
1389 $eventids = $eventsbyday[$day];
1392 if (!empty($durationbyday[$day])) {
1393 $eventids = array_unique(array_merge($eventids, $durationbyday[$day]));
1396 $finishclass = false;
1398 if (!empty($eventids)) {
1399 // There is at least one event on this day.
1400 $class .= ' hasevent';
1401 $hrefparams['view'] = 'day';
1402 $dayhref = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $hrefparams), 0, 0, 0, $daytime);
1405 foreach ($eventids as $eventid) {
1406 if (!isset($events[$eventid])) {
1409 $event = new \calendar_event($events[$eventid]);
1411 $component = 'moodle';
1412 if (!empty($event->modulename)) {
1413 $popupicon = 'icon';
1414 $popupalt = $event->modulename;
1415 $component = $event->modulename;
1416 } else if ($event->courseid == SITEID) { // Site event.
1417 $popupicon = 'i/siteevent';
1418 } else if ($event->courseid != 0 && $event->courseid != SITEID
1419 && $event->groupid == 0) { // Course event.
1420 $popupicon = 'i/courseevent';
1421 } else if ($event->groupid) { // Group event.
1422 $popupicon = 'i/groupevent';
1423 } else { // Must be a user event.
1424 $popupicon = 'i/userevent';
1427 if ($event->timeduration) {
1428 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
1429 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
1430 if ($enddate['mon'] == $m && $enddate['year'] == $y && $enddate['mday'] == $day) {
1431 $finishclass = true;
1435 $dayhref->set_anchor('event_' . $event->id);
1437 $popupcontent .= \html_writer::start_tag('div');
1438 $popupcontent .= $OUTPUT->pix_icon($popupicon, $popupalt, $component);
1439 // Show ical source if needed.
1440 if (!empty($event->subscription) && $CFG->calendar_showicalsource) {
1441 $a = new \stdClass();
1442 $a->name = format_string($event->name, true);
1443 $a->source = $event->subscription->name;
1444 $name = get_string('namewithsource', 'calendar', $a);
1447 $samedate = $startdate['mon'] == $enddate['mon'] &&
1448 $startdate['year'] == $enddate['year'] &&
1449 $startdate['mday'] == $enddate['mday'];
1452 $name = format_string($event->name, true);
1454 $name = format_string($event->name, true) . ' (' . get_string('eventendtime', 'calendar') . ')';
1457 $name = format_string($event->name, true);
1460 $popupcontent .= \html_writer::link($dayhref, $name);
1461 $popupcontent .= \html_writer::end_tag('div');
1464 if ($display->thismonth && $day == $d) {
1465 $popupdata = calendar_get_popup(true, $daytime, $popupcontent);
1467 $popupdata = calendar_get_popup(false, $daytime, $popupcontent);
1470 // Class and cell content.
1471 if (isset($typesbyday[$day]['startglobal'])) {
1472 $class .= ' calendar_event_global';
1473 } else if (isset($typesbyday[$day]['startcourse'])) {
1474 $class .= ' calendar_event_course';
1475 } else if (isset($typesbyday[$day]['startgroup'])) {
1476 $class .= ' calendar_event_group';
1477 } else if (isset($typesbyday[$day]['startuser'])) {
1478 $class .= ' calendar_event_user';
1481 $class .= ' duration_finish';
1486 'content' => $popupdata['data-core_calendar-popupcontent'],
1487 'title' => $popupdata['data-core_calendar-title']
1489 $cell = $OUTPUT->render_from_template('core_calendar/minicalendar_day_link', $data);
1494 $durationclass = false;
1495 if (isset($typesbyday[$day]['durationglobal'])) {
1496 $durationclass = ' duration_global';
1497 } else if (isset($typesbyday[$day]['durationcourse'])) {
1498 $durationclass = ' duration_course';
1499 } else if (isset($typesbyday[$day]['durationgroup'])) {
1500 $durationclass = ' duration_group';
1501 } else if (isset($typesbyday[$day]['durationuser'])) {
1502 $durationclass = ' duration_user';
1504 if ($durationclass) {
1505 $class .= ' duration ' . $durationclass;
1508 // If event has a class set then add it to the table day <td> tag.
1509 // Note: only one colour for minicalendar.
1510 if (isset($eventsbyday[$day])) {
1511 foreach ($eventsbyday[$day] as $eventid) {
1512 if (!isset($events[$eventid])) {
1515 $event = $events[$eventid];
1516 if (!empty($event->class)) {
1517 $class .= ' ' . $event->class;
1523 if ($display->thismonth && $day == $d) {
1524 // The current cell is for today - add appropriate classes and additional information for styling.
1526 $today = get_string('today', 'calendar') . ' ' . userdate(time(), get_string('strftimedayshort'));
1528 if (!isset($eventsbyday[$day]) && !isset($durationbyday[$day])) {
1529 $class .= ' eventnone';
1530 $popupdata = calendar_get_popup(true, false);
1534 'content' => $popupdata['data-core_calendar-popupcontent'],
1535 'title' => $popupdata['data-core_calendar-title']
1537 $cell = $OUTPUT->render_from_template('core_calendar/minicalendar_day_link', $data);
1539 $cell = get_accesshide($today . ' ') . $cell;
1543 $cellattributes['class'] = $class;
1544 $content .= \html_writer::tag('td', $cell, $cellattributes);
1547 // Padding (the last week may have blank days at the end).
1548 for ($i = $dayweek; $i <= $display->maxwday; ++$i) {
1549 $content .= '<td class="dayblank"> </td>';
1551 $content .= '</tr>'; // Last row ends.
1553 $content .= '</table>'; // Tabular display of days ends.
1558 * Gets the calendar popup.
1560 * It called at multiple points in from calendar_get_mini.
1561 * Copied and modified from calendar_get_mini.
1563 * @param bool $today false except when called on the current day.
1564 * @param mixed $timestart $events[$eventid]->timestart, OR false if there are no events.
1565 * @param string $popupcontent content for the popup window/layout.
1566 * @return string eventid for the calendar_tooltip popup window/layout.
1568 function calendar_get_popup($today = false, $timestart, $popupcontent = '') {
1571 $popupcaption = get_string('today', 'calendar') . ' ';
1574 if (false === $timestart) {
1575 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
1576 $popupcontent = get_string('eventnone', 'calendar');
1579 $popupcaption .= get_string('eventsfor', 'calendar', userdate($timestart, get_string('strftimedayshort')));
1583 'data-core_calendar-title' => $popupcaption,
1584 'data-core_calendar-popupcontent' => $popupcontent,
1589 * Gets the calendar upcoming event.
1591 * @param array $courses array of courses
1592 * @param array|int|bool $groups array of groups, group id or boolean for all/no group events
1593 * @param array|int|bool $users array of users, user id or boolean for all/no user events
1594 * @param int $daysinfuture number of days in the future we 'll look
1595 * @param int $maxevents maximum number of events
1596 * @param int $fromtime start time
1597 * @return array $output array of upcoming events
1599 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
1602 $display = new \stdClass;
1603 $display->range = $daysinfuture; // How many days in the future we 'll look.
1604 $display->maxevents = $maxevents;
1609 $now = time(); // We 'll need this later.
1610 $usermidnighttoday = usergetmidnight($now);
1613 $display->tstart = $fromtime;
1615 $display->tstart = $usermidnighttoday;
1618 // This works correctly with respect to the user's DST, but it is accurate
1619 // only because $fromtime is always the exact midnight of some day!
1620 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
1622 // Get the events matching our criteria.
1623 $events = calendar_get_legacy_events($display->tstart, $display->tend, $users, $groups, $courses);
1625 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
1626 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
1627 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
1628 // arguments to this function.
1629 $hrefparams = array();
1630 if (!empty($courses)) {
1631 $courses = array_diff($courses, array(SITEID));
1632 if (count($courses) == 1) {
1633 $hrefparams['course'] = reset($courses);
1637 if ($events !== false) {
1638 $modinfo = get_fast_modinfo($COURSE);
1639 foreach ($events as $event) {
1640 if (!empty($event->modulename)) {
1641 if ($event->courseid == $COURSE->id) {
1642 if (isset($modinfo->instances[$event->modulename][$event->instance])) {
1643 $cm = $modinfo->instances[$event->modulename][$event->instance];
1644 if (!$cm->uservisible) {
1649 if (!$cm = get_coursemodule_from_instance($event->modulename, $event->instance)) {
1652 if (!\core_availability\info_module::is_user_visible($cm, 0, false)) {
1658 if ($processed >= $display->maxevents) {
1662 $event->time = calendar_format_event_time($event, $now, $hrefparams);
1672 * Get a HTML link to a course.
1674 * @param int $courseid the course id
1675 * @return string a link to the course (as HTML); empty if the course id is invalid
1677 function calendar_get_courselink($courseid) {
1682 calendar_get_course_cached($coursecache, $courseid);
1683 $context = \context_course::instance($courseid);
1684 $fullname = format_string($coursecache[$courseid]->fullname, true, array('context' => $context));
1685 $url = new \moodle_url('/course/view.php', array('id' => $courseid));
1686 $link = \html_writer::link($url, $fullname);
1692 * Get current module cache.
1694 * @param array $modulecache in memory module cache
1695 * @param string $modulename name of the module
1696 * @param int $instance module instance number
1697 * @return stdClass|bool $module information
1699 function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
1700 if (!isset($modulecache[$modulename . '_' . $instance])) {
1701 $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
1704 return $modulecache[$modulename . '_' . $instance];
1708 * Get current course cache.
1710 * @param array $coursecache list of course cache
1711 * @param int $courseid id of the course
1712 * @return stdClass $coursecache[$courseid] return the specific course cache
1714 function calendar_get_course_cached(&$coursecache, $courseid) {
1715 if (!isset($coursecache[$courseid])) {
1716 $coursecache[$courseid] = get_course($courseid);
1718 return $coursecache[$courseid];
1722 * Get group from groupid for calendar display
1724 * @param int $groupid
1725 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1727 function calendar_get_group_cached($groupid) {
1728 static $groupscache = array();
1729 if (!isset($groupscache[$groupid])) {
1730 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1732 return $groupscache[$groupid];
1736 * Add calendar event metadata
1738 * @param stdClass $event event info
1739 * @return stdClass $event metadata
1741 function calendar_add_event_metadata($event) {
1742 global $CFG, $OUTPUT;
1744 // Support multilang in event->name.
1745 $event->name = format_string($event->name, true);
1747 if (!empty($event->modulename)) { // Activity event.
1748 // The module name is set. I will assume that it has to be displayed, and
1749 // also that it is an automatically-generated event. And of course that the
1750 // fields for get_coursemodule_from_instance are set correctly.
1751 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
1753 if ($module === false) {
1757 $modulename = get_string('modulename', $event->modulename);
1758 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
1759 // Will be used as alt text if the event icon.
1760 $eventtype = get_string($event->eventtype, $event->modulename);
1764 $icon = $OUTPUT->image_url('icon', $event->modulename) . '';
1766 $event->icon = '<img src="' . $icon . '" alt="' . $eventtype . '" title="' . $modulename . '" class="icon" />';
1767 $event->referer = '<a href="' . $CFG->wwwroot . '/mod/' . $event->modulename . '/view.php?id=' .
1768 $module->id . '">' . $event->name . '</a>';
1769 $event->courselink = calendar_get_courselink($module->course);
1770 $event->cmid = $module->id;
1771 } else if ($event->courseid == SITEID) { // Site event.
1772 $event->icon = '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
1773 get_string('globalevent', 'calendar') . '" class="icon" />';
1774 $event->cssclass = 'calendar_event_global';
1775 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event.
1776 $event->icon = '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
1777 get_string('courseevent', 'calendar') . '" class="icon" />';
1778 $event->courselink = calendar_get_courselink($event->courseid);
1779 $event->cssclass = 'calendar_event_course';
1780 } else if ($event->groupid) { // Group event.
1781 if ($group = calendar_get_group_cached($event->groupid)) {
1782 $groupname = format_string($group->name, true, \context_course::instance($group->courseid));
1786 $event->icon = \html_writer::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
1787 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
1788 $event->courselink = calendar_get_courselink($event->courseid) . ', ' . $groupname;
1789 $event->cssclass = 'calendar_event_group';
1790 } else if ($event->userid) { // User event.
1791 $event->icon = '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
1792 get_string('userevent', 'calendar') . '" class="icon" />';
1793 $event->cssclass = 'calendar_event_user';
1800 * Get calendar events by id.
1803 * @param array $eventids list of event ids
1804 * @return array Array of event entries, empty array if nothing found
1806 function calendar_get_events_by_id($eventids) {
1809 if (!is_array($eventids) || empty($eventids)) {
1813 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
1814 $wheresql = "id $wheresql";
1816 return $DB->get_records_select('event', $wheresql, $params);
1820 * Get control options for calendar.
1822 * @param string $type of calendar
1823 * @param array $data calendar information
1824 * @return string $content return available control for the calender in html
1826 function calendar_top_controls($type, $data) {
1827 global $PAGE, $OUTPUT;
1829 // Get the calendar type we are using.
1830 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1834 // Ensure course id passed if relevant.
1836 if (!empty($data['id'])) {
1837 $courseid = '&course=' . $data['id'];
1840 // If we are passing a month and year then we need to convert this to a timestamp to
1841 // support multiple calendars. No where in core should these be passed, this logic
1842 // here is for third party plugins that may use this function.
1843 if (!empty($data['m']) && !empty($date['y'])) {
1844 if (!isset($data['d'])) {
1847 if (!checkdate($data['m'], $data['d'], $data['y'])) {
1850 $time = make_timestamp($data['y'], $data['m'], $data['d']);
1852 } else if (!empty($data['time'])) {
1853 $time = $data['time'];
1858 // Get the date for the calendar type.
1859 $date = $calendartype->timestamp_to_date_array($time);
1861 $urlbase = $PAGE->url;
1863 // We need to get the previous and next months in certain cases.
1864 if ($type == 'frontpage' || $type == 'course' || $type == 'month') {
1865 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1866 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
1867 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
1868 $prevmonthtime['hour'], $prevmonthtime['minute']);
1870 $nextmonth = calendar_add_month($date['mon'], $date['year']);
1871 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
1872 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
1873 $nextmonthtime['hour'], $nextmonthtime['minute']);
1878 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1879 true, $prevmonthtime);
1880 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true,
1882 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1883 false, false, false, $time);
1885 if (!empty($data['id'])) {
1886 $calendarlink->param('course', $data['id']);
1891 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1892 $content .= $prevlink . '<span class="hide"> | </span>';
1893 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1894 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1895 ), array('class' => 'current'));
1896 $content .= '<span class="hide"> | </span>' . $right;
1897 $content .= "<span class=\"clearer\"><!-- --></span>\n";
1898 $content .= \html_writer::end_tag('div');
1902 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1903 true, $prevmonthtime);
1904 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false,
1905 true, $nextmonthtime);
1906 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1907 false, false, false, $time);
1909 if (!empty($data['id'])) {
1910 $calendarlink->param('course', $data['id']);
1913 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1914 $content .= $prevlink . '<span class="hide"> | </span>';
1915 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1916 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1917 ), array('class' => 'current'));
1918 $content .= '<span class="hide"> | </span>' . $nextlink;
1919 $content .= "<span class=\"clearer\"><!-- --></span>";
1920 $content .= \html_writer::end_tag('div');
1923 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'upcoming')),
1924 false, false, false, $time);
1925 if (!empty($data['id'])) {
1926 $calendarlink->param('course', $data['id']);
1928 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1929 $content .= \html_writer::tag('div', $calendarlink, array('class' => 'centered'));
1932 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1933 false, false, false, $time);
1934 if (!empty($data['id'])) {
1935 $calendarlink->param('course', $data['id']);
1937 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1938 $content .= \html_writer::tag('h3', $calendarlink);
1941 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1942 'view.php?view=month' . $courseid . '&', false, false, false, false, $prevmonthtime);
1943 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1944 'view.php?view=month' . $courseid . '&', false, false, false, false, $nextmonthtime);
1946 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1947 $content .= $prevlink . '<span class="hide"> | </span>';
1948 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1949 $content .= '<span class="hide"> | </span>' . $nextlink;
1950 $content .= '<span class="clearer"><!-- --></span>';
1951 $content .= \html_writer::end_tag('div')."\n";
1954 $days = calendar_get_days();
1956 $prevtimestamp = strtotime('-1 day', $time);
1957 $nexttimestamp = strtotime('+1 day', $time);
1959 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1960 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1962 $prevname = $days[$prevdate['wday']]['fullname'];
1963 $nextname = $days[$nextdate['wday']]['fullname'];
1964 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&', false, false,
1965 false, false, $prevtimestamp);
1966 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&', false, false, false,
1967 false, $nexttimestamp);
1969 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1970 $content .= $prevlink;
1971 $content .= '<span class="hide"> | </span><span class="current">' .userdate($time,
1972 get_string('strftimedaydate')) . '</span>';
1973 $content .= '<span class="hide"> | </span>' . $nextlink;
1974 $content .= "<span class=\"clearer\"><!-- --></span>";
1975 $content .= \html_writer::end_tag('div') . "\n";
1984 * Formats a filter control element.
1986 * @param moodle_url $url of the filter
1987 * @param int $type constant defining the type filter
1988 * @return string html content of the element
1990 function calendar_filter_controls_element(moodle_url $url, $type) {
1994 case CALENDAR_EVENT_GLOBAL:
1995 $typeforhumans = 'global';
1996 $class = 'calendar_event_global';
1998 case CALENDAR_EVENT_COURSE:
1999 $typeforhumans = 'course';
2000 $class = 'calendar_event_course';
2002 case CALENDAR_EVENT_GROUP:
2003 $typeforhumans = 'groups';
2004 $class = 'calendar_event_group';
2006 case CALENDAR_EVENT_USER:
2007 $typeforhumans = 'user';
2008 $class = 'calendar_event_user';
2012 if (calendar_show_event_type($type)) {
2013 $icon = $OUTPUT->pix_icon('t/hide', get_string('hide'));
2014 $str = get_string('hide' . $typeforhumans . 'events', 'calendar');
2016 $icon = $OUTPUT->pix_icon('t/show', get_string('show'));
2017 $str = get_string('show' . $typeforhumans . 'events', 'calendar');
2019 $content = \html_writer::start_tag('li', array('class' => 'calendar_event'));
2020 $content .= \html_writer::start_tag('a', array('href' => $url, 'rel' => 'nofollow'));
2021 $content .= \html_writer::tag('span', $icon, array('class' => $class));
2022 $content .= \html_writer::tag('span', $str, array('class' => 'eventname'));
2023 $content .= \html_writer::end_tag('a');
2024 $content .= \html_writer::end_tag('li');
2030 * Get the controls filter for calendar.
2032 * Filter is used to hide calendar info from the display page.
2035 * @param moodle_url $returnurl return-url for filter controls
2036 * @return string $content return filter controls in html
2038 function calendar_filter_controls(moodle_url $returnurl) {
2039 $groupevents = true;
2041 $seturl = new \moodle_url('/calendar/set.php', array('return' => base64_encode($returnurl->out_as_local_url(false)),
2042 'sesskey' => sesskey()));
2043 $content = \html_writer::start_tag('ul');
2045 $seturl->param('var', 'showglobal');
2046 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GLOBAL);
2048 $seturl->param('var', 'showcourses');
2049 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_COURSE);
2051 if (isloggedin() && !isguestuser()) {
2053 // This course MIGHT have group events defined, so show the filter.
2054 $seturl->param('var', 'showgroups');
2055 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GROUP);
2057 $seturl->param('var', 'showuser');
2058 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_USER);
2060 $content .= \html_writer::end_tag('ul');
2066 * Return the representation day.
2068 * @param int $tstamp Timestamp in GMT
2069 * @param int|bool $now current Unix timestamp
2070 * @param bool $usecommonwords
2071 * @return string the formatted date/time
2073 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
2074 static $shortformat;
2076 if (empty($shortformat)) {
2077 $shortformat = get_string('strftimedayshort');
2080 if ($now === false) {
2084 // To have it in one place, if a change is needed.
2085 $formal = userdate($tstamp, $shortformat);
2087 $datestamp = usergetdate($tstamp);
2088 $datenow = usergetdate($now);
2090 if ($usecommonwords == false) {
2091 // We don't want words, just a date.
2093 } else if ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
2094 return get_string('today', 'calendar');
2095 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
2096 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12
2097 && $datenow['yday'] == 1)) {
2098 return get_string('yesterday', 'calendar');
2099 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
2100 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12
2101 && $datestamp['yday'] == 1)) {
2102 return get_string('tomorrow', 'calendar');
2109 * return the formatted representation time.
2112 * @param int $time the timestamp in UTC, as obtained from the database
2113 * @return string the formatted date/time
2115 function calendar_time_representation($time) {
2116 static $langtimeformat = null;
2118 if ($langtimeformat === null) {
2119 $langtimeformat = get_string('strftimetime');
2122 $timeformat = get_user_preferences('calendar_timeformat');
2123 if (empty($timeformat)) {
2124 $timeformat = get_config(null, 'calendar_site_timeformat');
2127 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
2131 * Adds day, month, year arguments to a URL and returns a moodle_url object.
2133 * @param string|moodle_url $linkbase
2134 * @param int $d The number of the day.
2135 * @param int $m The number of the month.
2136 * @param int $y The number of the year.
2137 * @param int $time the unixtime, used for multiple calendar support. The values $d,
2138 * $m and $y are kept for backwards compatibility.
2139 * @return moodle_url|null $linkbase
2141 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
2142 if (empty($linkbase)) {
2146 if (!($linkbase instanceof \moodle_url)) {
2147 $linkbase = new \moodle_url($linkbase);
2150 // If a day, month and year were passed then convert it to a timestamp. If these were passed
2151 // then we can assume the day, month and year are passed as Gregorian, as no where in core
2152 // should we be passing these values rather than the time.
2153 if (!empty($d) && !empty($m) && !empty($y)) {
2154 if (checkdate($m, $d, $y)) {
2155 $time = make_timestamp($y, $m, $d);
2159 } else if (empty($time)) {
2163 $linkbase->param('time', $time);
2169 * Build and return a previous month HTML link, with an arrow.
2171 * @param string $text The text label.
2172 * @param string|moodle_url $linkbase The URL stub.
2173 * @param int $d The number of the date.
2174 * @param int $m The number of the month.
2175 * @param int $y year The number of the year.
2176 * @param bool $accesshide Default visible, or hide from all except screenreaders.
2177 * @param int $time the unixtime, used for multiple calendar support. The values $d,
2178 * $m and $y are kept for backwards compatibility.
2179 * @return string HTML string.
2181 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
2182 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
2188 return link_arrow_left($text, (string)$href, $accesshide, 'previous');
2192 * Build and return a next month HTML link, with an arrow.
2194 * @param string $text The text label.
2195 * @param string|moodle_url $linkbase The URL stub.
2196 * @param int $d the number of the Day
2197 * @param int $m The number of the month.
2198 * @param int $y The number of the year.
2199 * @param bool $accesshide Default visible, or hide from all except screenreaders.
2200 * @param int $time the unixtime, used for multiple calendar support. The values $d,
2201 * $m and $y are kept for backwards compatibility.
2202 * @return string HTML string.
2204 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
2205 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
2211 return link_arrow_right($text, (string)$href, $accesshide, 'next');
2215 * Return the number of days in month.
2217 * @param int $month the number of the month.
2218 * @param int $year the number of the year
2221 function calendar_days_in_month($month, $year) {
2222 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2223 return $calendartype->get_num_days_in_month($year, $month);
2227 * Get the next following month.
2229 * @param int $month the number of the month.
2230 * @param int $year the number of the year.
2231 * @return array the following month
2233 function calendar_add_month($month, $year) {
2234 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2235 return $calendartype->get_next_month($year, $month);
2239 * Get the previous month.
2241 * @param int $month the number of the month.
2242 * @param int $year the number of the year.
2243 * @return array previous month
2245 function calendar_sub_month($month, $year) {
2246 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2247 return $calendartype->get_prev_month($year, $month);
2251 * Get per-day basis events
2253 * @param array $events list of events
2254 * @param int $month the number of the month
2255 * @param int $year the number of the year
2256 * @param array $eventsbyday event on specific day
2257 * @param array $durationbyday duration of the event in days
2258 * @param array $typesbyday event type (eg: global, course, user, or group)
2259 * @param array $courses list of courses
2262 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
2263 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2265 $eventsbyday = array();
2266 $typesbyday = array();
2267 $durationbyday = array();
2269 if ($events === false) {
2273 foreach ($events as $event) {
2274 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
2275 if ($event->timeduration) {
2276 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
2278 $enddate = $startdate;
2281 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair.
2282 if (!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) &&
2283 ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
2287 $eventdaystart = intval($startdate['mday']);
2289 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2290 // Give the event to its day.
2291 $eventsbyday[$eventdaystart][] = $event->id;
2293 // Mark the day as having such an event.
2294 if ($event->courseid == SITEID && $event->groupid == 0) {
2295 $typesbyday[$eventdaystart]['startglobal'] = true;
2296 // Set event class for global event.
2297 $events[$event->id]->class = 'calendar_event_global';
2298 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
2299 $typesbyday[$eventdaystart]['startcourse'] = true;
2300 // Set event class for course event.
2301 $events[$event->id]->class = 'calendar_event_course';
2302 } else if ($event->groupid) {
2303 $typesbyday[$eventdaystart]['startgroup'] = true;
2304 // Set event class for group event.
2305 $events[$event->id]->class = 'calendar_event_group';
2306 } else if ($event->userid) {
2307 $typesbyday[$eventdaystart]['startuser'] = true;
2308 // Set event class for user event.
2309 $events[$event->id]->class = 'calendar_event_user';
2313 if ($event->timeduration == 0) {
2314 // Proceed with the next.
2318 // The event starts on $month $year or before.
2319 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2320 $lowerbound = intval($startdate['mday']);
2325 // Also, it ends on $month $year or later.
2326 if ($enddate['mon'] == $month && $enddate['year'] == $year) {
2327 $upperbound = intval($enddate['mday']);
2329 $upperbound = calendar_days_in_month($month, $year);
2332 // Mark all days between $lowerbound and $upperbound (inclusive) as duration.
2333 for ($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
2334 $durationbyday[$i][] = $event->id;
2335 if ($event->courseid == SITEID && $event->groupid == 0) {
2336 $typesbyday[$i]['durationglobal'] = true;
2337 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
2338 $typesbyday[$i]['durationcourse'] = true;
2339 } else if ($event->groupid) {
2340 $typesbyday[$i]['durationgroup'] = true;
2341 } else if ($event->userid) {
2342 $typesbyday[$i]['durationuser'] = true;
2351 * Returns the courses to load events for.
2353 * @param array $courseeventsfrom An array of courses to load calendar events for
2354 * @param bool $ignorefilters specify the use of filters, false is set as default
2355 * @return array An array of courses, groups, and user to load calendar events for based upon filters
2357 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
2360 // For backwards compatability we have to check whether the courses array contains
2361 // just id's in which case we need to load course objects.
2362 $coursestoload = array();
2363 foreach ($courseeventsfrom as $id => $something) {
2364 if (!is_object($something)) {
2365 $coursestoload[] = $id;
2366 unset($courseeventsfrom[$id]);
2374 // Get the capabilities that allow seeing group events from all groups.
2375 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
2377 $isloggedin = isloggedin();
2379 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
2380 $courses = array_keys($courseeventsfrom);
2382 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
2383 $courses[] = SITEID;
2385 $courses = array_unique($courses);
2388 if (!empty($courses) && in_array(SITEID, $courses)) {
2389 // Sort courses for consistent colour highlighting.
2390 // Effectively ignoring SITEID as setting as last course id.
2391 $key = array_search(SITEID, $courses);
2392 unset($courses[$key]);
2393 $courses[] = SITEID;
2396 if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
2400 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
2402 if (count($courseeventsfrom) == 1) {
2403 $course = reset($courseeventsfrom);
2404 if (has_any_capability($allgroupscaps, \context_course::instance($course->id))) {
2405 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
2406 $group = array_keys($coursegroups);
2409 if ($group === false) {
2410 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, \context_system::instance())) {
2412 } else if ($isloggedin) {
2413 $groupids = array();
2414 foreach ($courseeventsfrom as $courseid => $course) {
2415 // If the user is an editing teacher in there.
2416 if (!empty($USER->groupmember[$course->id])) {
2417 // We've already cached the users groups for this course so we can just use that.
2418 $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
2419 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2420 // If this course has groups, show events from all of those related to the current user.
2421 $coursegroups = groups_get_user_groups($course->id, $USER->id);
2422 $groupids = array_merge($groupids, $coursegroups['0']);
2425 if (!empty($groupids)) {
2431 if (empty($courses)) {
2435 return array($courses, $group, $user);
2439 * Return the capability for editing calendar event.
2441 * @param calendar_event $event event object
2442 * @return bool capability to edit event
2444 function calendar_edit_event_allowed($event) {
2447 // Must be logged in.
2448 if (!isloggedin()) {
2452 // Can not be using guest account.
2453 if (isguestuser()) {
2457 // You cannot edit URL based calendar subscription events presently.
2458 if (!empty($event->subscriptionid)) {
2459 if (!empty($event->subscription->url)) {
2460 // This event can be updated externally, so it cannot be edited.
2465 $sitecontext = \context_system::instance();
2467 // If user has manageentries at site level, return true.
2468 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2472 // If groupid is set, it's definitely a group event.
2473 if (!empty($event->groupid)) {
2474 // Allow users to add/edit group events if -
2475 // 1) They have manageentries for the course OR
2476 // 2) They have managegroupentries AND are in the group.
2477 $group = $DB->get_record('groups', array('id' => $event->groupid));
2479 has_capability('moodle/calendar:manageentries', $event->context) ||
2480 (has_capability('moodle/calendar:managegroupentries', $event->context)
2481 && groups_is_member($event->groupid)));
2482 } else if (!empty($event->courseid)) {
2483 // If groupid is not set, but course is set, it's definiely a course event.
2484 return has_capability('moodle/calendar:manageentries', $event->context);
2485 } else if (!empty($event->userid) && $event->userid == $USER->id) {
2486 // If course is not set, but userid id set, it's a user event.
2487 return (has_capability('moodle/calendar:manageownentries', $event->context));
2488 } else if (!empty($event->userid)) {
2489 return (has_capability('moodle/calendar:manageentries', $event->context));
2496 * Returns the default courses to display on the calendar when there isn't a specific
2497 * course to display.
2499 * @return array $courses Array of courses to display
2501 function calendar_get_default_courses() {
2504 if (!isloggedin()) {
2508 if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', \context_system::instance())) {
2509 $select = ', ' . \context_helper::get_preload_record_columns_sql('ctx');
2510 $join = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
2511 $sql = "SELECT c.* $select
2514 WHERE EXISTS (SELECT 1 FROM {event} e WHERE e.courseid = c.id)
2516 $courses = $DB->get_records_sql($sql, array('contextlevel' => CONTEXT_COURSE), 0, 20);
2517 foreach ($courses as $course) {
2518 \context_helper::preload_from_record($course);
2523 $courses = enrol_get_my_courses();
2529 * Get event format time.
2531 * @param calendar_event $event event object
2532 * @param int $now current time in gmt
2533 * @param array $linkparams list of params for event link
2534 * @param bool $usecommonwords the words as formatted date/time.
2535 * @param int $showtime determine the show time GMT timestamp
2536 * @return string $eventtime link/string for event time
2538 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
2539 $starttime = $event->timestart;
2540 $endtime = $event->timestart + $event->timeduration;
2542 if (empty($linkparams) || !is_array($linkparams)) {
2543 $linkparams = array();
2546 $linkparams['view'] = 'day';
2548 // OK, now to get a meaningful display.
2549 // Check if there is a duration for this event.
2550 if ($event->timeduration) {
2551 // Get the midnight of the day the event will start.
2552 $usermidnightstart = usergetmidnight($starttime);
2553 // Get the midnight of the day the event will end.
2554 $usermidnightend = usergetmidnight($endtime);
2555 // Check if we will still be on the same day.
2556 if ($usermidnightstart == $usermidnightend) {
2557 // Check if we are running all day.
2558 if ($event->timeduration == DAYSECS) {
2559 $time = get_string('allday', 'calendar');
2560 } else { // Specify the time we will be running this from.
2561 $datestart = calendar_time_representation($starttime);
2562 $dateend = calendar_time_representation($endtime);
2563 $time = $datestart . ' <strong>»</strong> ' . $dateend;
2566 // Set printable representation.
2568 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2569 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2570 $eventtime = \html_writer::link($url, $day) . ', ' . $time;
2574 } else { // It must spans two or more days.
2575 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
2576 if ($showtime == $usermidnightstart) {
2579 $timestart = calendar_time_representation($event->timestart);
2580 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
2581 if ($showtime == $usermidnightend) {
2584 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
2586 // Set printable representation.
2587 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2588 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2589 $eventtime = $timestart . ' <strong>»</strong> ' . \html_writer::link($url, $dayend) . $timeend;
2591 // The event is in the future, print start and end links.
2592 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2593 $eventtime = \html_writer::link($url, $daystart) . $timestart . ' <strong>»</strong> ';
2595 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2596 $eventtime .= \html_writer::link($url, $dayend) . $timeend;
2599 } else { // There is no time duration.
2600 $time = calendar_time_representation($event->timestart);
2601 // Set printable representation.
2603 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2604 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2605 $eventtime = \html_writer::link($url, $day) . ', ' . trim($time);
2611 // Check if It has expired.
2612 if ($event->timestart + $event->timeduration < $now) {
2613 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2620 * Checks to see if the requested type of event should be shown for the given user.
2622 * @param int $type The type to check the display for (default is to display all)
2623 * @param stdClass|int|null $user The user to check for - by default the current user
2624 * @return bool True if the tyep should be displayed false otherwise
2626 function calendar_show_event_type($type, $user = null) {
2627 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
2629 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2631 if (!isset($SESSION->calendarshoweventtype)) {
2632 $SESSION->calendarshoweventtype = $default;
2634 return $SESSION->calendarshoweventtype & $type;
2636 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2641 * Sets the display of the event type given $display.
2643 * If $display = true the event type will be shown.
2644 * If $display = false the event type will NOT be shown.
2645 * If $display = null the current value will be toggled and saved.
2647 * @param int $type object of CALENDAR_EVENT_XXX
2648 * @param bool $display option to display event type
2649 * @param stdClass|int $user moodle user object or id, null means current user
2651 function calendar_set_event_type_display($type, $display = null, $user = null) {
2652 $persist = get_user_preferences('calendar_persistflt', 0, $user);
2653 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
2654 if ($persist === 0) {
2656 if (!isset($SESSION->calendarshoweventtype)) {
2657 $SESSION->calendarshoweventtype = $default;
2659 $preference = $SESSION->calendarshoweventtype;
2661 $preference = get_user_preferences('calendar_savedflt', $default, $user);
2663 $current = $preference & $type;
2664 if ($display === null) {
2665 $display = !$current;
2667 if ($display && !$current) {
2668 $preference += $type;
2669 } else if (!$display && $current) {
2670 $preference -= $type;
2672 if ($persist === 0) {
2673 $SESSION->calendarshoweventtype = $preference;
2675 if ($preference == $default) {
2676 unset_user_preference('calendar_savedflt', $user);
2678 set_user_preference('calendar_savedflt', $preference, $user);
2684 * Get calendar's allowed types.
2686 * @param stdClass $allowed list of allowed edit for event type
2687 * @param stdClass|int $course object of a course or course id
2689 function calendar_get_allowed_types(&$allowed, $course = null) {
2692 $allowed = new \stdClass();
2693 $allowed->user = has_capability('moodle/calendar:manageownentries', \context_system::instance());
2694 $allowed->groups = false;
2695 $allowed->courses = false;
2696 $allowed->site = has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID));
2698 if (!empty($course)) {
2699 if (!is_object($course)) {
2700 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST);
2702 if ($course->id != SITEID) {
2703 $coursecontext = \context_course::instance($course->id);
2704 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
2706 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2707 $allowed->courses = array($course->id => 1);
2709 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2710 if (has_capability('moodle/site:accessallgroups', $coursecontext)) {
2711 $allowed->groups = groups_get_all_groups($course->id);
2713 $allowed->groups = groups_get_all_groups($course->id, $USER->id);
2716 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
2717 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2718 if (has_capability('moodle/site:accessallgroups', $coursecontext)) {
2719 $allowed->groups = groups_get_all_groups($course->id);
2721 $allowed->groups = groups_get_all_groups($course->id, $USER->id);
2730 * See if user can add calendar entries at all used to print the "New Event" button.
2732 * @param stdClass $course object of a course or course id
2733 * @return bool has the capability to add at least one event type
2735 function calendar_user_can_add_event($course) {
2736 if (!isloggedin() || isguestuser()) {
2740 calendar_get_allowed_types($allowed, $course);
2742 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);
2746 * Check wether the current user is permitted to add events.
2748 * @param stdClass $event object of event
2749 * @return bool has the capability to add event
2751 function calendar_add_event_allowed($event) {
2754 // Can not be using guest account.
2755 if (!isloggedin() or isguestuser()) {
2759 $sitecontext = \context_system::instance();
2761 // If user has manageentries at site level, always return true.
2762 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2766 switch ($event->eventtype) {
2768 return has_capability('moodle/calendar:manageentries', $event->context);
2770 // Allow users to add/edit group events if -
2771 // 1) They have manageentries (= entries for whole course).
2772 // 2) They have managegroupentries AND are in the group.
2773 $group = $DB->get_record('groups', array('id' => $event->groupid));
2775 has_capability('moodle/calendar:manageentries', $event->context) ||
2776 (has_capability('moodle/calendar:managegroupentries', $event->context)
2777 && groups_is_member($event->groupid)));
2779 if ($event->userid == $USER->id) {
2780 return (has_capability('moodle/calendar:manageownentries', $event->context));
2782 // There is intentionally no 'break'.
2784 return has_capability('moodle/calendar:manageentries', $event->context);
2786 return has_capability('moodle/calendar:manageentries', $event->context);
2791 * Returns option list for the poll interval setting.
2793 * @return array An array of poll interval options. Interval => description.
2795 function calendar_get_pollinterval_choices() {
2797 '0' => new \lang_string('never', 'calendar'),
2798 HOURSECS => new \lang_string('hourly', 'calendar'),
2799 DAYSECS => new \lang_string('daily', 'calendar'),
2800 WEEKSECS => new \lang_string('weekly', 'calendar'),
2801 '2628000' => new \lang_string('monthly', 'calendar'),
2802 YEARSECS => new \lang_string('annually', 'calendar')
2807 * Returns option list of available options for the calendar event type, given the current user and course.
2809 * @param int $courseid The id of the course
2810 * @return array An array containing the event types the user can create.
2812 function calendar_get_eventtype_choices($courseid) {
2814 $allowed = new \stdClass;
2815 calendar_get_allowed_types($allowed, $courseid);
2817 if ($allowed->user) {
2818 $choices['user'] = get_string('userevents', 'calendar');
2820 if ($allowed->site) {
2821 $choices['site'] = get_string('siteevents', 'calendar');
2823 if (!empty($allowed->courses)) {
2824 $choices['course'] = get_string('courseevents', 'calendar');
2826 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2827 $choices['group'] = get_string('group');
2830 return array($choices, $allowed->groups);
2834 * Add an iCalendar subscription to the database.
2836 * @param stdClass $sub The subscription object (e.g. from the form)
2837 * @return int The insert ID, if any.
2839 function calendar_add_subscription($sub) {
2840 global $DB, $USER, $SITE;
2842 if ($sub->eventtype === 'site') {
2843 $sub->courseid = $SITE->id;
2844 } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
2845 $sub->courseid = $sub->course;
2850 $sub->userid = $USER->id;
2852 // File subscriptions never update.
2853 if (empty($sub->url)) {
2854 $sub->pollinterval = 0;
2857 if (!empty($sub->name)) {
2858 if (empty($sub->id)) {
2859 $id = $DB->insert_record('event_subscriptions', $sub);
2860 // We cannot cache the data here because $sub is not complete.
2862 // Trigger event, calendar subscription added.
2863 $eventparams = array('objectid' => $sub->id,
2864 'context' => calendar_get_calendar_context($sub),
2865 'other' => array('eventtype' => $sub->eventtype, 'courseid' => $sub->courseid)
2867 $event = \core\event\calendar_subscription_created::create($eventparams);
2871 // Why are we doing an update here?
2872 calendar_update_subscription($sub);
2876 print_error('errorbadsubscription', 'importcalendar');
2881 * Add an iCalendar event to the Moodle calendar.
2883 * @param stdClass $event The RFC-2445 iCalendar event
2884 * @param int $courseid The course ID
2885 * @param int $subscriptionid The iCalendar subscription ID
2886 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2887 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2888 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2890 function calendar_add_icalendar_event($event, $courseid, $subscriptionid, $timezone='UTC') {
2893 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2894 if (empty($event->properties['SUMMARY'])) {
2898 $name = $event->properties['SUMMARY'][0]->value;
2899 $name = str_replace('\n', '<br />', $name);
2900 $name = str_replace('\\', '', $name);
2901 $name = preg_replace('/\s+/u', ' ', $name);
2903 $eventrecord = new \stdClass;
2904 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
2906 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2909 $description = $event->properties['DESCRIPTION'][0]->value;
2910 $description = clean_param($description, PARAM_NOTAGS);
2911 $description = str_replace('\n', '<br />', $description);
2912 $description = str_replace('\\', '', $description);
2913 $description = preg_replace('/\s+/u', ' ', $description);
2915 $eventrecord->description = $description;
2917 // Probably a repeating event with RRULE etc. TODO: skip for now.
2918 if (empty($event->properties['DTSTART'][0]->value)) {
2922 if (isset($event->properties['DTSTART'][0]->parameters['TZID'])) {
2923 $tz = $event->properties['DTSTART'][0]->parameters['TZID'];
2927 $tz = \core_date::normalise_timezone($tz);
2928 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value . ' ' . $tz);
2929 if (empty($event->properties['DTEND'])) {
2930 $eventrecord->timeduration = 0; // No duration if no end time specified.
2932 if (isset($event->properties['DTEND'][0]->parameters['TZID'])) {
2933 $endtz = $event->properties['DTEND'][0]->parameters['TZID'];
2937 $endtz = \core_date::normalise_timezone($endtz);
2938 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value . ' ' . $endtz) - $eventrecord->timestart;
2941 // Check to see if it should be treated as an all day event.
2942 if ($eventrecord->timeduration == DAYSECS) {
2943 // Check to see if the event started at Midnight on the imported calendar.
2944 date_default_timezone_set($timezone);
2945 if (date('H:i:s', $eventrecord->timestart) === "00:00:00") {
2946 // This event should be an all day event.
2947 $eventrecord->timeduration = 0;
2949 \core_date::set_default_server_timezone();
2952 $eventrecord->uuid = $event->properties['UID'][0]->value;
2953 $eventrecord->timemodified = time();
2955 // Add the iCal subscription details if required.
2956 // We should never do anything with an event without a subscription reference.
2957 $sub = calendar_get_subscription($subscriptionid);
2958 $eventrecord->subscriptionid = $subscriptionid;
2959 $eventrecord->userid = $sub->userid;
2960 $eventrecord->groupid = $sub->groupid;
2961 $eventrecord->courseid = $sub->courseid;
2962 $eventrecord->eventtype = $sub->eventtype;
2964 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid,
2965 'subscriptionid' => $eventrecord->subscriptionid))) {
2966 $eventrecord->id = $updaterecord->id;
2967 $return = CALENDAR_IMPORT_EVENT_UPDATED; // Update.
2969 $return = CALENDAR_IMPORT_EVENT_INSERTED; // Insert.
2971 if ($createdevent = \calendar_event::create($eventrecord, false)) {
2972 if (!empty($event->properties['RRULE'])) {
2973 // Repeating events.
2974 date_default_timezone_set($tz); // Change time zone to parse all events.
2975 $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
2976 $rrule->parse_rrule();
2977 $rrule->create_events($createdevent);
2978 \core_date::set_default_server_timezone(); // Change time zone back to what it was.
2987 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2989 * @param int $subscriptionid The ID of the subscription we are acting upon.
2990 * @param int $pollinterval The poll interval to use.
2991 * @param int $action The action to be performed. One of update or remove.
2992 * @throws dml_exception if invalid subscriptionid is provided
2993 * @return string A log of the import progress, including errors
2995 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2996 // Fetch the subscription from the database making sure it exists.
2997 $sub = calendar_get_subscription($subscriptionid);
2999 // Update or remove the subscription, based on action.
3001 case CALENDAR_SUBSCRIPTION_UPDATE:
3002 // Skip updating file subscriptions.
3003 if (empty($sub->url)) {
3006 $sub->pollinterval = $pollinterval;
3007 calendar_update_subscription($sub);
3009 // Update the events.
3010 return "<p>" . get_string('subscriptionupdated', 'calendar', $sub->name) . "</p>" .
3011 calendar_update_subscription_events($subscriptionid);
3012 case CALENDAR_SUBSCRIPTION_REMOVE:
3013 calendar_delete_subscription($subscriptionid);
3014 return get_string('subscriptionremoved', 'calendar', $sub->name);
3023 * Delete subscription and all related events.
3025 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
3027 function calendar_delete_subscription($subscription) {
3030 if (!is_object($subscription)) {
3031 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST);
3034 // Delete subscription and related events.
3035 $DB->delete_records('event', array('subscriptionid' => $subscription->id));
3036 $DB->delete_records('event_subscriptions', array('id' => $subscription->id));
3037 \cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id));
3039 // Trigger event, calendar subscription deleted.
3040 $eventparams = array('objectid' => $subscription->id,
3041 'context' => calendar_get_calendar_context($subscription),
3042 'other' => array('courseid' => $subscription->courseid)
3044 $event = \core\event\calendar_subscription_deleted::create($eventparams);
3049 * From a URL, fetch the calendar and return an iCalendar object.
3051 * @param string $url The iCalendar URL
3052 * @return iCalendar The iCalendar object
3054 function calendar_get_icalendar($url) {
3057 require_once($CFG->libdir . '/filelib.php');
3059 $curl = new \curl();
3060 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
3061 $calendar = $curl->get($url);
3063 // Http code validation should actually be the job of curl class.
3064 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
3065 throw new \moodle_exception('errorinvalidicalurl', 'calendar');
3068 $ical = new \iCalendar();
3069 $ical->unserialize($calendar);
3075 * Import events from an iCalendar object into a course calendar.
3077 * @param iCalendar $ical The iCalendar object.
3078 * @param int $courseid The course ID for the calendar.
3079 * @param int $subscriptionid The subscription ID.
3080 * @return string A log of the import progress, including errors.
3082 function calendar_import_icalendar_events($ical, $courseid, $subscriptionid = null) {
3089 // Large calendars take a while...
3091 \core_php_time_limit::raise(300);
3094 // Mark all events in a subscription with a zero timestamp.
3095 if (!empty($subscriptionid)) {
3096 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
3097 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3100 // Grab the timezone from the iCalendar file to be used later.
3101 if (isset($ical->properties['X-WR-TIMEZONE'][0]->value)) {
3102 $timezone = $ical->properties['X-WR-TIMEZONE'][0]->value;
3108 foreach ($ical->components['VEVENT'] as $event) {
3109 $res = calendar_add_icalendar_event($event, $courseid, $subscriptionid, $timezone);
3111 case CALENDAR_IMPORT_EVENT_UPDATED:
3114 case CALENDAR_IMPORT_EVENT_INSERTED:
3118 $return .= '<p>' . get_string('erroraddingevent', 'calendar') . ': ';
3119 if (empty($event->properties['SUMMARY'])) {
3120 $return .= '(' . get_string('notitle', 'calendar') . ')';
3122 $return .= $event->properties['SUMMARY'][0]->value;
3124 $return .= "</p>\n";
3129 $return .= "<p>" . get_string('eventsimported', 'calendar', $eventcount) . "</p> ";
3130 $return .= "<p>" . get_string('eventsupdated', 'calendar', $updatecount) . "</p>";
3132 // Delete remaining zero-marked events since they're not in remote calendar.
3133 if (!empty($subscriptionid)) {
3134 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3135 if (!empty($deletecount)) {
3136 $DB->delete_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3137 $return .= "<p> " . get_string('eventsdeleted', 'calendar') . ": {$deletecount} </p>\n";
3145 * Fetch a calendar subscription and update the events in the calendar.
3147 * @param int $subscriptionid The course ID for the calendar.
3148 * @return string A log of the import progress, including errors.
3150 function calendar_update_subscription_events($subscriptionid) {
3151 $sub = calendar_get_subscription($subscriptionid);
3153 // Don't update a file subscription.
3154 if (empty($sub->url)) {
3155 return 'File subscription not updated.';
3158 $ical = calendar_get_icalendar($sub->url);
3159 $return = calendar_import_icalendar_events($ical, $sub->courseid, $subscriptionid);
3160 $sub->lastupdated = time();
3162 calendar_update_subscription($sub);
3168 * Update a calendar subscription. Also updates the associated cache.
3170 * @param stdClass|array $subscription Subscription record.
3171 * @throws coding_exception If something goes wrong
3174 function calendar_update_subscription($subscription) {
3177 if (is_array($subscription)) {
3178 $subscription = (object)$subscription;
3180 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
3181 throw new \coding_exception('Cannot update a subscription without a valid id');
3184 $DB->update_record('event_subscriptions', $subscription);
3187 $cache = \cache::make('core', 'calendar_subscriptions');
3188 $cache->set($subscription->id, $subscription);
3190 // Trigger event, calendar subscription updated.
3191 $eventparams = array('userid' => $subscription->userid,
3192 'objectid' => $subscription->id,
3193 'context' => calendar_get_calendar_context($subscription),
3194 'other' => array('eventtype' => $subscription->eventtype, 'courseid' => $subscription->courseid)
3196 $event = \core\event\calendar_subscription_updated::create($eventparams);
3201 * Checks to see if the user can edit a given subscription feed.
3203 * @param mixed $subscriptionorid Subscription object or id
3204 * @return bool true if current user can edit the subscription else false
3206 function calendar_can_edit_subscription($subscriptionorid) {
3207 if (is_array($subscriptionorid)) {
3208 $subscription = (object)$subscriptionorid;
3209 } else if (is_object($subscriptionorid)) {
3210 $subscription = $subscriptionorid;
3212 $subscription = calendar_get_subscription($subscriptionorid);
3215 $allowed = new \stdClass;
3216 $courseid = $subscription->courseid;
3217 $groupid = $subscription->groupid;
3219 calendar_get_allowed_types($allowed, $courseid);
3220 switch ($subscription->eventtype) {
3222 return $allowed->user;
3224 if (isset($allowed->courses[$courseid])) {
3225 return $allowed->courses[$courseid];
3230 return $allowed->site;
3232 if (isset($allowed->groups[$groupid])) {
3233 return $allowed->groups[$groupid];
3243 * Helper function to determine the context of a calendar subscription.
3244 * Subscriptions can be created in two contexts COURSE, or USER.
3246 * @param stdClass $subscription
3247 * @return context instance
3249 function calendar_get_calendar_context($subscription) {
3250 // Determine context based on calendar type.
3251 if ($subscription->eventtype === 'site') {
3252 $context = \context_course::instance(SITEID);
3253 } else if ($subscription->eventtype === 'group' || $subscription->eventtype === 'course') {
3254 $context = \context_course::instance($subscription->courseid);
3256 $context = \context_user::instance($subscription->userid);
3262 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
3264 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3268 function core_calendar_user_preferences() {
3270 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED, 'default' => '0',
3271 'choices' => array('0', CALENDAR_TF_12, CALENDAR_TF_24)
3273 $preferences['calendar_startwday'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3274 'choices' => array(0, 1, 2, 3, 4, 5, 6));
3275 $preferences['calendar_maxevents'] = array('type' => PARAM_INT, 'choices' => range(1, 20));
3276 $preferences['calendar_lookahead'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 365,
3277 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3278 $preferences['calendar_persistflt'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3279 'choices' => array(0, 1));
3280 return $preferences;
3284 * Get legacy calendar events
3286 * @param int $tstart Start time of time range for events
3287 * @param int $tend End time of time range for events
3288 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3289 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3290 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3291 * @param boolean $withduration whether only events starting within time range selected
3292 * or events in progress/already started selected as well
3293 * @param boolean $ignorehidden whether to select only visible events or all events
3294 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3296 function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses, $withduration = true, $ignorehidden = true) {
3297 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3298 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3299 // parameters, but with the new API method, only null and arrays are accepted.
3300 list($userparam, $groupparam, $courseparam) = array_map(function($param) {
3301 // If parameter is true, return null.
3302 if ($param === true) {
3306 // If parameter is false, return an empty array.
3307 if ($param === false) {
3311 // If the parameter is a scalar value, enclose it in an array.
3312 if (!is_array($param)) {
3316 // No normalisation required.
3318 }, [$users, $groups, $courses]);
3320 $mapper = \core_calendar\local\event\container::get_event_mapper();
3321 $events = \core_calendar\local\api::get_events(
3337 return array_reduce($events, function($carry, $event) use ($mapper) {
3338 return $carry + [$event->get_id() => $mapper->from_event_to_stdclass($event)];