Merge branch 'MDL-57900_master' of git://github.com/dmonllao/moodle
[moodle.git] / calendar / lib.php
blob6ef434fb14f4bf955cb6e3705123c8dbb4ab3e49
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Calendar extension
20 * @package core_calendar
21 * @copyright 2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
22 * Avgoustos Tsinakos
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 if (!defined('MOODLE_INTERNAL')) {
27 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
30 /**
31 * These are read by the administration component to provide default values
34 /**
35 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
37 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
39 /**
40 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
42 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
44 /**
45 * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
47 define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
49 // This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
50 // Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
52 /**
53 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
55 define('CALENDAR_DEFAULT_WEEKEND', 65);
57 /**
58 * CALENDAR_URL - path to calendar's folder
60 define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
62 /**
63 * CALENDAR_TF_24 - Calendar time in 24 hours format
65 define('CALENDAR_TF_24', '%H:%M');
67 /**
68 * CALENDAR_TF_12 - Calendar time in 12 hours format
70 define('CALENDAR_TF_12', '%I:%M %p');
72 /**
73 * CALENDAR_EVENT_GLOBAL - Global calendar event types
75 define('CALENDAR_EVENT_GLOBAL', 1);
77 /**
78 * CALENDAR_EVENT_COURSE - Course calendar event types
80 define('CALENDAR_EVENT_COURSE', 2);
82 /**
83 * CALENDAR_EVENT_GROUP - group calendar event types
85 define('CALENDAR_EVENT_GROUP', 4);
87 /**
88 * CALENDAR_EVENT_USER - user calendar event types
90 define('CALENDAR_EVENT_USER', 8);
92 /**
93 * CALENDAR_EVENT_COURSECAT - Course category calendar event types
95 define('CALENDAR_EVENT_COURSECAT', 16);
97 /**
98 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
100 define('CALENDAR_IMPORT_FROM_FILE', 0);
103 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
105 define('CALENDAR_IMPORT_FROM_URL', 1);
108 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
110 define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
113 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
115 define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
118 * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
120 define('CALENDAR_SUBSCRIPTION_UPDATE', 1);
123 * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
125 define('CALENDAR_SUBSCRIPTION_REMOVE', 2);
128 * CALENDAR_EVENT_USER_OVERRIDE_PRIORITY - Constant for the user override priority.
130 define('CALENDAR_EVENT_USER_OVERRIDE_PRIORITY', 0);
133 * CALENDAR_EVENT_TYPE_STANDARD - Standard events.
135 define('CALENDAR_EVENT_TYPE_STANDARD', 0);
138 * CALENDAR_EVENT_TYPE_ACTION - Action events.
140 define('CALENDAR_EVENT_TYPE_ACTION', 1);
143 * Manage calendar events.
145 * This class provides the required functionality in order to manage calendar events.
146 * It was introduced as part of Moodle 2.0 and was created in order to provide a
147 * better framework for dealing with calendar events in particular regard to file
148 * handling through the new file API.
150 * @package core_calendar
151 * @category calendar
152 * @copyright 2009 Sam Hemelryk
153 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
155 * @property int $id The id within the event table
156 * @property string $name The name of the event
157 * @property string $description The description of the event
158 * @property int $format The format of the description FORMAT_?
159 * @property int $courseid The course the event is associated with (0 if none)
160 * @property int $groupid The group the event is associated with (0 if none)
161 * @property int $userid The user the event is associated with (0 if none)
162 * @property int $repeatid If this is a repeated event this will be set to the
163 * id of the original
164 * @property string $modulename If added by a module this will be the module name
165 * @property int $instance If added by a module this will be the module instance
166 * @property string $eventtype The event type
167 * @property int $timestart The start time as a timestamp
168 * @property int $timeduration The duration of the event in seconds
169 * @property int $visible 1 if the event is visible
170 * @property int $uuid ?
171 * @property int $sequence ?
172 * @property int $timemodified The time last modified as a timestamp
174 class calendar_event {
176 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
177 protected $properties = null;
179 /** @var string The converted event discription with file paths resolved.
180 * This gets populated when someone requests description for the first time */
181 protected $_description = null;
183 /** @var array The options to use with this description editor */
184 protected $editoroptions = array(
185 'subdirs' => false,
186 'forcehttps' => false,
187 'maxfiles' => -1,
188 'maxbytes' => null,
189 'trusttext' => false);
191 /** @var object The context to use with the description editor */
192 protected $editorcontext = null;
195 * Instantiates a new event and optionally populates its properties with the data provided.
197 * @param \stdClass $data Optional. An object containing the properties to for
198 * an event
200 public function __construct($data = null) {
201 global $CFG, $USER;
203 // First convert to object if it is not already (should either be object or assoc array).
204 if (!is_object($data)) {
205 $data = (object) $data;
208 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
210 $data->eventrepeats = 0;
212 if (empty($data->id)) {
213 $data->id = null;
216 if (!empty($data->subscriptionid)) {
217 $data->subscription = calendar_get_subscription($data->subscriptionid);
220 // Default to a user event.
221 if (empty($data->eventtype)) {
222 $data->eventtype = 'user';
225 // Default to the current user.
226 if (empty($data->userid)) {
227 $data->userid = $USER->id;
230 if (!empty($data->timeduration) && is_array($data->timeduration)) {
231 $data->timeduration = make_timestamp(
232 $data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'],
233 $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
236 if (!empty($data->description) && is_array($data->description)) {
237 $data->format = $data->description['format'];
238 $data->description = $data->description['text'];
239 } else if (empty($data->description)) {
240 $data->description = '';
241 $data->format = editors_get_preferred_format();
244 // Ensure form is defaulted correctly.
245 if (empty($data->format)) {
246 $data->format = editors_get_preferred_format();
249 $this->properties = $data;
253 * Magic set method.
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;
269 * Magic get method.
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
306 * the course event.
307 * Default value is set to CONTEXT_USER
309 * @return \stdClass The context object.
311 protected function calculate_context() {
312 global $USER, $DB;
314 $context = null;
315 if (isset($this->properties->categoryid) && $this->properties->categoryid > 0) {
316 $context = \context_coursecat::instance($this->properties->categoryid);
317 } else if (isset($this->properties->courseid) && $this->properties->courseid > 0) {
318 $context = \context_course::instance($this->properties->courseid);
319 } else if (isset($this->properties->course) && $this->properties->course > 0) {
320 $context = \context_course::instance($this->properties->course);
321 } else if (isset($this->properties->groupid) && $this->properties->groupid > 0) {
322 $group = $DB->get_record('groups', array('id' => $this->properties->groupid));
323 $context = \context_course::instance($group->courseid);
324 } else if (isset($this->properties->userid) && $this->properties->userid > 0
325 && $this->properties->userid == $USER->id) {
326 $context = \context_user::instance($this->properties->userid);
327 } else if (isset($this->properties->userid) && $this->properties->userid > 0
328 && $this->properties->userid != $USER->id &&
329 isset($this->properties->instance) && $this->properties->instance > 0) {
330 $cm = get_coursemodule_from_instance($this->properties->modulename, $this->properties->instance, 0,
331 false, MUST_EXIST);
332 $context = \context_course::instance($cm->course);
333 } else {
334 $context = \context_user::instance($this->properties->userid);
337 return $context;
341 * Returns the context for this event. The context is calculated
342 * the first time is is requested and then stored in a member
343 * variable to be returned each subsequent time.
345 * This is a magical getter function that will be called when
346 * ever the context property is accessed, e.g. $event->context.
348 * @return context
350 protected function get_context() {
351 if (!isset($this->properties->context)) {
352 $this->properties->context = $this->calculate_context();
355 return $this->properties->context;
359 * Returns an array of editoroptions for this event.
361 * @return array event editor options
363 protected function get_editoroptions() {
364 return $this->editoroptions;
368 * Returns an event description: Called by __get
369 * Please use $blah = $event->description;
371 * @return string event description
373 protected function get_description() {
374 global $CFG;
376 require_once($CFG->libdir . '/filelib.php');
378 if ($this->_description === null) {
379 // Check if we have already resolved the context for this event.
380 if ($this->editorcontext === null) {
381 // Switch on the event type to decide upon the appropriate context to use for this event.
382 $this->editorcontext = $this->get_context();
383 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
384 return clean_text($this->properties->description, $this->properties->format);
388 // Work out the item id for the editor, if this is a repeated event
389 // then the files will be associated with the original.
390 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
391 $itemid = $this->properties->repeatid;
392 } else {
393 $itemid = $this->properties->id;
396 // Convert file paths in the description so that things display correctly.
397 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php',
398 $this->editorcontext->id, 'calendar', 'event_description', $itemid);
399 // Clean the text so no nasties get through.
400 $this->_description = clean_text($this->_description, $this->properties->format);
403 // Finally return the description.
404 return $this->_description;
408 * Return the number of repeat events there are in this events series.
410 * @return int number of event repeated
412 public function count_repeats() {
413 global $DB;
414 if (!empty($this->properties->repeatid)) {
415 $this->properties->eventrepeats = $DB->count_records('event',
416 array('repeatid' => $this->properties->repeatid));
417 // We don't want to count ourselves.
418 $this->properties->eventrepeats--;
420 return $this->properties->eventrepeats;
424 * Update or create an event within the database
426 * Pass in a object containing the event properties and this function will
427 * insert it into the database and deal with any associated files
429 * Capability checking should be performed if the user is directly manipulating the event
430 * and no other capability has been tested. However if the event is not being manipulated
431 * directly by the user and another capability has been checked for them to do this then
432 * capabilites should not be checked.
434 * For example if a user is editing an event in the calendar the check should be true,
435 * but if you are updating an event in an activities settings are changed then the calendar
436 * capabilites should not be checked.
438 * @see self::create()
439 * @see self::update()
441 * @param \stdClass $data object of event
442 * @param bool $checkcapability If Moodle should check the user can manage the calendar events for this call or not.
443 * @return bool event updated
445 public function update($data, $checkcapability=true) {
446 global $DB, $USER;
448 foreach ($data as $key => $value) {
449 $this->properties->$key = $value;
452 $this->properties->timemodified = time();
453 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
455 // Prepare event data.
456 $eventargs = array(
457 'context' => $this->get_context(),
458 'objectid' => $this->properties->id,
459 'other' => array(
460 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
461 'timestart' => $this->properties->timestart,
462 'name' => $this->properties->name
466 if (empty($this->properties->id) || $this->properties->id < 1) {
467 if ($checkcapability) {
468 if (!calendar_add_event_allowed($this->properties)) {
469 print_error('nopermissiontoupdatecalendar');
473 if ($usingeditor) {
474 switch ($this->properties->eventtype) {
475 case 'user':
476 $this->properties->courseid = 0;
477 $this->properties->course = 0;
478 $this->properties->groupid = 0;
479 $this->properties->userid = $USER->id;
480 break;
481 case 'site':
482 $this->properties->courseid = SITEID;
483 $this->properties->course = SITEID;
484 $this->properties->groupid = 0;
485 $this->properties->userid = $USER->id;
486 break;
487 case 'course':
488 $this->properties->groupid = 0;
489 $this->properties->userid = $USER->id;
490 break;
491 case 'category':
492 $this->properties->groupid = 0;
493 $this->properties->category = 0;
494 $this->properties->userid = $USER->id;
495 break;
496 case 'group':
497 $this->properties->userid = $USER->id;
498 break;
499 default:
500 // We should NEVER get here, but just incase we do lets fail gracefully.
501 $usingeditor = false;
502 break;
505 // If we are actually using the editor, we recalculate the context because some default values
506 // were set when calculate_context() was called from the constructor.
507 if ($usingeditor) {
508 $this->properties->context = $this->calculate_context();
509 $this->editorcontext = $this->get_context();
512 $editor = $this->properties->description;
513 $this->properties->format = $this->properties->description['format'];
514 $this->properties->description = $this->properties->description['text'];
517 // Insert the event into the database.
518 $this->properties->id = $DB->insert_record('event', $this->properties);
520 if ($usingeditor) {
521 $this->properties->description = file_save_draft_area_files(
522 $editor['itemid'],
523 $this->editorcontext->id,
524 'calendar',
525 'event_description',
526 $this->properties->id,
527 $this->editoroptions,
528 $editor['text'],
529 $this->editoroptions['forcehttps']);
530 $DB->set_field('event', 'description', $this->properties->description,
531 array('id' => $this->properties->id));
534 // Log the event entry.
535 $eventargs['objectid'] = $this->properties->id;
536 $eventargs['context'] = $this->get_context();
537 $event = \core\event\calendar_event_created::create($eventargs);
538 $event->trigger();
540 $repeatedids = array();
542 if (!empty($this->properties->repeat)) {
543 $this->properties->repeatid = $this->properties->id;
544 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id' => $this->properties->id));
546 $eventcopy = clone($this->properties);
547 unset($eventcopy->id);
549 $timestart = new \DateTime('@' . $eventcopy->timestart);
550 $timestart->setTimezone(\core_date::get_user_timezone_object());
552 for ($i = 1; $i < $eventcopy->repeats; $i++) {
554 $timestart->add(new \DateInterval('P7D'));
555 $eventcopy->timestart = $timestart->getTimestamp();
557 // Get the event id for the log record.
558 $eventcopyid = $DB->insert_record('event', $eventcopy);
560 // If the context has been set delete all associated files.
561 if ($usingeditor) {
562 $fs = get_file_storage();
563 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description',
564 $this->properties->id);
565 foreach ($files as $file) {
566 $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
570 $repeatedids[] = $eventcopyid;
572 // Trigger an event.
573 $eventargs['objectid'] = $eventcopyid;
574 $eventargs['other']['timestart'] = $eventcopy->timestart;
575 $event = \core\event\calendar_event_created::create($eventargs);
576 $event->trigger();
580 return true;
581 } else {
583 if ($checkcapability) {
584 if (!calendar_edit_event_allowed($this->properties)) {
585 print_error('nopermissiontoupdatecalendar');
589 if ($usingeditor) {
590 if ($this->editorcontext !== null) {
591 $this->properties->description = file_save_draft_area_files(
592 $this->properties->description['itemid'],
593 $this->editorcontext->id,
594 'calendar',
595 'event_description',
596 $this->properties->id,
597 $this->editoroptions,
598 $this->properties->description['text'],
599 $this->editoroptions['forcehttps']);
600 } else {
601 $this->properties->format = $this->properties->description['format'];
602 $this->properties->description = $this->properties->description['text'];
606 $event = $DB->get_record('event', array('id' => $this->properties->id));
608 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
610 if ($updaterepeated) {
612 $sqlset = 'name = ?,
613 description = ?,
614 timeduration = ?,
615 timemodified = ?,
616 groupid = ?,
617 courseid = ?';
619 // Note: Group and course id may not be set. If not, keep their current values.
620 $params = [
621 $this->properties->name,
622 $this->properties->description,
623 $this->properties->timeduration,
624 time(),
625 isset($this->properties->groupid) ? $this->properties->groupid : $event->groupid,
626 isset($this->properties->courseid) ? $this->properties->courseid : $event->courseid,
629 // Note: Only update start date, if it was changed by the user.
630 if ($this->properties->timestart != $event->timestart) {
631 $timestartoffset = $this->properties->timestart - $event->timestart;
632 $sqlset .= ', timestart = timestart + ?';
633 $params[] = $timestartoffset;
636 // Note: Only update location, if it was changed by the user.
637 $updatelocation = (!empty($this->properties->location) && $this->properties->location !== $event->location);
638 if ($updatelocation) {
639 $sqlset .= ', location = ?';
640 $params[] = $this->properties->location;
643 // Update all.
644 $sql = "UPDATE {event}
645 SET $sqlset
646 WHERE repeatid = ?";
648 $params[] = $event->repeatid;
649 $DB->execute($sql, $params);
651 // Trigger an update event for each of the calendar event.
652 $events = $DB->get_records('event', array('repeatid' => $event->repeatid), '', '*');
653 foreach ($events as $calendarevent) {
654 $eventargs['objectid'] = $calendarevent->id;
655 $eventargs['other']['timestart'] = $calendarevent->timestart;
656 $event = \core\event\calendar_event_updated::create($eventargs);
657 $event->add_record_snapshot('event', $calendarevent);
658 $event->trigger();
660 } else {
661 $DB->update_record('event', $this->properties);
662 $event = self::load($this->properties->id);
663 $this->properties = $event->properties();
665 // Trigger an update event.
666 $event = \core\event\calendar_event_updated::create($eventargs);
667 $event->add_record_snapshot('event', $this->properties);
668 $event->trigger();
671 return true;
676 * Deletes an event and if selected an repeated events in the same series
678 * This function deletes an event, any associated events if $deleterepeated=true,
679 * and cleans up any files associated with the events.
681 * @see self::delete()
683 * @param bool $deleterepeated delete event repeatedly
684 * @return bool succession of deleting event
686 public function delete($deleterepeated = false) {
687 global $DB;
689 // If $this->properties->id is not set then something is wrong.
690 if (empty($this->properties->id)) {
691 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
692 return false;
694 $calevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
695 // Delete the event.
696 $DB->delete_records('event', array('id' => $this->properties->id));
698 // Trigger an event for the delete action.
699 $eventargs = array(
700 'context' => $this->get_context(),
701 'objectid' => $this->properties->id,
702 'other' => array(
703 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
704 'timestart' => $this->properties->timestart,
705 'name' => $this->properties->name
707 $event = \core\event\calendar_event_deleted::create($eventargs);
708 $event->add_record_snapshot('event', $calevent);
709 $event->trigger();
711 // If we are deleting parent of a repeated event series, promote the next event in the series as parent.
712 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
713 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC",
714 array($this->properties->id), IGNORE_MULTIPLE);
715 if (!empty($newparent)) {
716 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?",
717 array($newparent, $this->properties->id));
718 // Get all records where the repeatid is the same as the event being removed.
719 $events = $DB->get_records('event', array('repeatid' => $newparent));
720 // For each of the returned events trigger an update event.
721 foreach ($events as $calendarevent) {
722 // Trigger an event for the update.
723 $eventargs['objectid'] = $calendarevent->id;
724 $eventargs['other']['timestart'] = $calendarevent->timestart;
725 $event = \core\event\calendar_event_updated::create($eventargs);
726 $event->add_record_snapshot('event', $calendarevent);
727 $event->trigger();
732 // If the editor context hasn't already been set then set it now.
733 if ($this->editorcontext === null) {
734 $this->editorcontext = $this->get_context();
737 // If the context has been set delete all associated files.
738 if ($this->editorcontext !== null) {
739 $fs = get_file_storage();
740 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
741 foreach ($files as $file) {
742 $file->delete();
746 // If we need to delete repeated events then we will fetch them all and delete one by one.
747 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
748 // Get all records where the repeatid is the same as the event being removed.
749 $events = $DB->get_records('event', array('repeatid' => $this->properties->repeatid));
750 // For each of the returned events populate an event object and call delete.
751 // make sure the arg passed is false as we are already deleting all repeats.
752 foreach ($events as $event) {
753 $event = new calendar_event($event);
754 $event->delete(false);
758 return true;
762 * Fetch all event properties.
764 * This function returns all of the events properties as an object and optionally
765 * can prepare an editor for the description field at the same time. This is
766 * designed to work when the properties are going to be used to set the default
767 * values of a moodle forms form.
769 * @param bool $prepareeditor If set to true a editor is prepared for use with
770 * the mforms editor element. (for description)
771 * @return \stdClass Object containing event properties
773 public function properties($prepareeditor = false) {
774 global $DB;
776 // First take a copy of the properties. We don't want to actually change the
777 // properties or we'd forever be converting back and forwards between an
778 // editor formatted description and not.
779 $properties = clone($this->properties);
780 // Clean the description here.
781 $properties->description = clean_text($properties->description, $properties->format);
783 // If set to true we need to prepare the properties for use with an editor
784 // and prepare the file area.
785 if ($prepareeditor) {
787 // We may or may not have a property id. If we do then we need to work
788 // out the context so we can copy the existing files to the draft area.
789 if (!empty($properties->id)) {
791 if ($properties->eventtype === 'site') {
792 // Site context.
793 $this->editorcontext = $this->get_context();
794 } else if ($properties->eventtype === 'user') {
795 // User context.
796 $this->editorcontext = $this->get_context();
797 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
798 // First check the course is valid.
799 $course = $DB->get_record('course', array('id' => $properties->courseid));
800 if (!$course) {
801 print_error('invalidcourse');
803 // Course context.
804 $this->editorcontext = $this->get_context();
805 // We have a course and are within the course context so we had
806 // better use the courses max bytes value.
807 $this->editoroptions['maxbytes'] = $course->maxbytes;
808 } else if ($properties->eventtype === 'category') {
809 // First check the course is valid.
810 \core_course_category::get($properties->categoryid, MUST_EXIST, true);
811 // Course context.
812 $this->editorcontext = $this->get_context();
813 } else {
814 // If we get here we have a custom event type as used by some
815 // modules. In this case the event will have been added by
816 // code and we won't need the editor.
817 $this->editoroptions['maxbytes'] = 0;
818 $this->editoroptions['maxfiles'] = 0;
821 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
822 $contextid = false;
823 } else {
824 // Get the context id that is what we really want.
825 $contextid = $this->editorcontext->id;
827 } else {
829 // If we get here then this is a new event in which case we don't need a
830 // context as there is no existing files to copy to the draft area.
831 $contextid = null;
834 // If the contextid === false we don't support files so no preparing
835 // a draft area.
836 if ($contextid !== false) {
837 // Just encase it has already been submitted.
838 $draftiddescription = file_get_submitted_draft_itemid('description');
839 // Prepare the draft area, this copies existing files to the draft area as well.
840 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar',
841 'event_description', $properties->id, $this->editoroptions, $properties->description);
842 } else {
843 $draftiddescription = 0;
846 // Structure the description field as the editor requires.
847 $properties->description = array('text' => $properties->description, 'format' => $properties->format,
848 'itemid' => $draftiddescription);
851 // Finally return the properties.
852 return $properties;
856 * Toggles the visibility of an event
858 * @param null|bool $force If it is left null the events visibility is flipped,
859 * If it is false the event is made hidden, if it is true it
860 * is made visible.
861 * @return bool if event is successfully updated, toggle will be visible
863 public function toggle_visibility($force = null) {
864 global $DB;
866 // Set visible to the default if it is not already set.
867 if (empty($this->properties->visible)) {
868 $this->properties->visible = 1;
871 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
872 // Make this event visible.
873 $this->properties->visible = 1;
874 } else {
875 // Make this event hidden.
876 $this->properties->visible = 0;
879 // Update the database to reflect this change.
880 $success = $DB->set_field('event', 'visible', $this->properties->visible, array('id' => $this->properties->id));
881 $calendarevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
883 // Prepare event data.
884 $eventargs = array(
885 'context' => $this->get_context(),
886 'objectid' => $this->properties->id,
887 'other' => array(
888 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
889 'timestart' => $this->properties->timestart,
890 'name' => $this->properties->name
893 $event = \core\event\calendar_event_updated::create($eventargs);
894 $event->add_record_snapshot('event', $calendarevent);
895 $event->trigger();
897 return $success;
901 * Returns an event object when provided with an event id.
903 * This function makes use of MUST_EXIST, if the event id passed in is invalid
904 * it will result in an exception being thrown.
906 * @param int|object $param event object or event id
907 * @return calendar_event
909 public static function load($param) {
910 global $DB;
911 if (is_object($param)) {
912 $event = new calendar_event($param);
913 } else {
914 $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST);
915 $event = new calendar_event($event);
917 return $event;
921 * Creates a new event and returns an event object.
923 * Capability checking should be performed if the user is directly creating the event
924 * and no other capability has been tested. However if the event is not being created
925 * directly by the user and another capability has been checked for them to do this then
926 * capabilites should not be checked.
928 * For example if a user is creating an event in the calendar the check should be true,
929 * but if you are creating an event in an activity when it is created then the calendar
930 * capabilites should not be checked.
932 * @param \stdClass|array $properties An object containing event properties
933 * @param bool $checkcapability If Moodle should check the user can manage the calendar events for this call or not.
934 * @throws \coding_exception
936 * @return calendar_event|bool The event object or false if it failed
938 public static function create($properties, $checkcapability = true) {
939 if (is_array($properties)) {
940 $properties = (object)$properties;
942 if (!is_object($properties)) {
943 throw new \coding_exception('When creating an event properties should be either an object or an assoc array');
945 $event = new calendar_event($properties);
946 if ($event->update($properties, $checkcapability)) {
947 return $event;
948 } else {
949 return false;
954 * Format the text using the external API.
956 * This function should we used when text formatting is required in external functions.
958 * @return array an array containing the text formatted and the text format
960 public function format_external_text() {
962 if ($this->editorcontext === null) {
963 // Switch on the event type to decide upon the appropriate context to use for this event.
964 $this->editorcontext = $this->get_context();
966 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
967 // We don't have a context here, do a normal format_text.
968 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id);
972 // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
973 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
974 $itemid = $this->properties->repeatid;
975 } else {
976 $itemid = $this->properties->id;
979 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id,
980 'calendar', 'event_description', $itemid);
985 * Calendar information class
987 * This class is used simply to organise the information pertaining to a calendar
988 * and is used primarily to make information easily available.
990 * @package core_calendar
991 * @category calendar
992 * @copyright 2010 Sam Hemelryk
993 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
995 class calendar_information {
998 * @var int The timestamp
1000 * Rather than setting the day, month and year we will set a timestamp which will be able
1001 * to be used by multiple calendars.
1003 public $time;
1005 /** @var int A course id */
1006 public $courseid = null;
1008 /** @var array An array of categories */
1009 public $categories = array();
1011 /** @var int The current category */
1012 public $categoryid = null;
1014 /** @var array An array of courses */
1015 public $courses = array();
1017 /** @var array An array of groups */
1018 public $groups = array();
1020 /** @var array An array of users */
1021 public $users = array();
1023 /** @var context The anticipated context that the calendar is viewed in */
1024 public $context = null;
1027 * Creates a new instance
1029 * @param int $day the number of the day
1030 * @param int $month the number of the month
1031 * @param int $year the number of the year
1032 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
1033 * and $calyear to support multiple calendars
1035 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
1036 // If a day, month and year were passed then convert it to a timestamp. If these were passed
1037 // then we can assume the day, month and year are passed as Gregorian, as no where in core
1038 // should we be passing these values rather than the time. This is done for BC.
1039 if (!empty($day) || !empty($month) || !empty($year)) {
1040 $date = usergetdate(time());
1041 if (empty($day)) {
1042 $day = $date['mday'];
1044 if (empty($month)) {
1045 $month = $date['mon'];
1047 if (empty($year)) {
1048 $year = $date['year'];
1050 if (checkdate($month, $day, $year)) {
1051 $time = make_timestamp($year, $month, $day);
1052 } else {
1053 $time = time();
1057 $this->set_time($time);
1061 * Creates and set up a instance.
1063 * @param int $time the unixtimestamp representing the date we want to view.
1064 * @param int $courseid The ID of the course the user wishes to view.
1065 * @param int $categoryid The ID of the category the user wishes to view
1066 * If a courseid is specified, this value is ignored.
1067 * @return calendar_information
1069 public static function create($time, int $courseid, int $categoryid = null) : calendar_information {
1070 $calendar = new static(0, 0, 0, $time);
1071 if ($courseid != SITEID && !empty($courseid)) {
1072 // Course ID must be valid and existing.
1073 $course = get_course($courseid);
1074 $calendar->context = context_course::instance($course->id);
1076 if (!$course->visible && !is_role_switched($course->id)) {
1077 require_capability('moodle/course:viewhiddencourses', $calendar->context);
1080 $courses = [$course->id => $course];
1081 $category = (\core_course_category::get($course->category, MUST_EXIST, true))->get_db_record();
1082 } else if (!empty($categoryid)) {
1083 $course = get_site();
1084 $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1086 // Filter available courses to those within this category or it's children.
1087 $ids = [$categoryid];
1088 $category = \core_course_category::get($categoryid);
1089 $ids = array_merge($ids, array_keys($category->get_children()));
1090 $courses = array_filter($courses, function($course) use ($ids) {
1091 return array_search($course->category, $ids) !== false;
1093 $category = $category->get_db_record();
1095 $calendar->context = context_coursecat::instance($categoryid);
1096 } else {
1097 $course = get_site();
1098 $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1099 $category = null;
1101 $calendar->context = context_system::instance();
1104 $calendar->set_sources($course, $courses, $category);
1106 return $calendar;
1110 * Set the time period of this instance.
1112 * @param int $time the unixtimestamp representing the date we want to view.
1113 * @return $this
1115 public function set_time($time = null) {
1116 if (empty($time)) {
1117 $this->time = time();
1118 } else {
1119 $this->time = $time;
1122 return $this;
1126 * Initialize calendar information
1128 * @deprecated 3.4
1129 * @param stdClass $course object
1130 * @param array $coursestoload An array of courses [$course->id => $course]
1131 * @param bool $ignorefilters options to use filter
1133 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
1134 debugging('The prepare_for_view() function has been deprecated. Please update your code to use set_sources()',
1135 DEBUG_DEVELOPER);
1136 $this->set_sources($course, $coursestoload);
1140 * Set the sources for events within the calendar.
1142 * If no category is provided, then the category path for the current
1143 * course will be used.
1145 * @param stdClass $course The current course being viewed.
1146 * @param stdClass[] $courses The list of all courses currently accessible.
1147 * @param stdClass $category The current category to show.
1149 public function set_sources(stdClass $course, array $courses, stdClass $category = null) {
1150 global $USER;
1152 // A cousre must always be specified.
1153 $this->course = $course;
1154 $this->courseid = $course->id;
1156 list($courseids, $group, $user) = calendar_set_filters($courses);
1157 $this->courses = $courseids;
1158 $this->groups = $group;
1159 $this->users = $user;
1161 // Do not show category events by default.
1162 $this->categoryid = null;
1163 $this->categories = null;
1165 // Determine the correct category information to show.
1166 // When called with a course, the category of that course is usually included too.
1167 // When a category was specifically requested, it should be requested with the site id.
1168 if (SITEID !== $this->courseid) {
1169 // A specific course was requested.
1170 // Fetch the category that this course is in, along with all parents.
1171 // Do not include child categories of this category, as the user many not have enrolments in those siblings or children.
1172 $category = \core_course_category::get($course->category, MUST_EXIST, true);
1173 $this->categoryid = $category->id;
1175 $this->categories = $category->get_parents();
1176 $this->categories[] = $category->id;
1177 } else if (null !== $category && $category->id > 0) {
1178 // A specific category was requested.
1179 // Fetch all parents of this category, along with all children too.
1180 $category = \core_course_category::get($category->id);
1181 $this->categoryid = $category->id;
1183 // Build the category list.
1184 // This includes the current category.
1185 $this->categories = $category->get_parents();
1186 $this->categories[] = $category->id;
1187 $this->categories = array_merge($this->categories, $category->get_all_children_ids());
1188 } else if (SITEID === $this->courseid) {
1189 // The site was requested.
1190 // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
1192 // Grab the list of categories that this user has courses in.
1193 $coursecategories = array_flip(array_map(function($course) {
1194 return $course->category;
1195 }, $courses));
1197 $calcatcache = cache::make('core', 'calendar_categories');
1198 $this->categories = $calcatcache->get('site');
1199 if ($this->categories === false) {
1200 // Use the category id as the key in the following array. That way we do not have to remove duplicates.
1201 $categories = [];
1202 foreach (\core_course_category::get_all() as $category) {
1203 if (isset($coursecategories[$category->id]) ||
1204 has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
1205 // If the user has access to a course in this category or can manage the category,
1206 // then they can see all parent categories too.
1207 $categories[$category->id] = true;
1208 foreach ($category->get_parents() as $catid) {
1209 $categories[$catid] = true;
1213 $this->categories = array_keys($categories);
1214 $calcatcache->set('site', $this->categories);
1220 * Ensures the date for the calendar is correct and either sets it to now
1221 * or throws a moodle_exception if not
1223 * @param bool $defaultonow use current time
1224 * @throws moodle_exception
1225 * @return bool validation of checkdate
1227 public function checkdate($defaultonow = true) {
1228 if (!checkdate($this->month, $this->day, $this->year)) {
1229 if ($defaultonow) {
1230 $now = usergetdate(time());
1231 $this->day = intval($now['mday']);
1232 $this->month = intval($now['mon']);
1233 $this->year = intval($now['year']);
1234 return true;
1235 } else {
1236 throw new moodle_exception('invaliddate');
1239 return true;
1243 * Gets todays timestamp for the calendar
1245 * @return int today timestamp
1247 public function timestamp_today() {
1248 return $this->time;
1251 * Gets tomorrows timestamp for the calendar
1253 * @return int tomorrow timestamp
1255 public function timestamp_tomorrow() {
1256 return strtotime('+1 day', $this->time);
1259 * Adds the pretend blocks for the calendar
1261 * @param core_calendar_renderer $renderer
1262 * @param bool $showfilters display filters, false is set as default
1263 * @param string|null $view preference view options (eg: day, month, upcoming)
1265 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
1266 if ($showfilters) {
1267 $filters = new block_contents();
1268 $filters->content = $renderer->event_filter();
1269 $filters->footer = '';
1270 $filters->title = get_string('eventskey', 'calendar');
1271 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
1273 $block = new block_contents;
1274 $block->content = $renderer->fake_block_threemonths($this);
1275 $block->footer = '';
1276 $block->title = get_string('monthlyview', 'calendar');
1277 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
1282 * Get calendar events.
1284 * @param int $tstart Start time of time range for events
1285 * @param int $tend End time of time range for events
1286 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
1287 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
1288 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
1289 * @param boolean $withduration whether only events starting within time range selected
1290 * or events in progress/already started selected as well
1291 * @param boolean $ignorehidden whether to select only visible events or all events
1292 * @param array|int|boolean $categories array of categories, category id or boolean for all/no course events
1293 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
1295 function calendar_get_events($tstart, $tend, $users, $groups, $courses,
1296 $withduration = true, $ignorehidden = true, $categories = []) {
1297 global $DB;
1299 $whereclause = '';
1300 $params = array();
1301 // Quick test.
1302 if (empty($users) && empty($groups) && empty($courses) && empty($categories)) {
1303 return array();
1306 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
1307 // Events from a number of users
1308 if(!empty($whereclause)) $whereclause .= ' OR';
1309 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED);
1310 $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)";
1311 $params = array_merge($params, $inparamsusers);
1312 } else if($users === true) {
1313 // Events from ALL users
1314 if(!empty($whereclause)) $whereclause .= ' OR';
1315 $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)';
1316 } else if($users === false) {
1317 // No user at all, do nothing
1320 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
1321 // Events from a number of groups
1322 if(!empty($whereclause)) $whereclause .= ' OR';
1323 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED);
1324 $whereclause .= " e.groupid $insqlgroups ";
1325 $params = array_merge($params, $inparamsgroups);
1326 } else if($groups === true) {
1327 // Events from ALL groups
1328 if(!empty($whereclause)) $whereclause .= ' OR ';
1329 $whereclause .= ' e.groupid != 0';
1331 // boolean false (no groups at all): we don't need to do anything
1333 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
1334 if(!empty($whereclause)) $whereclause .= ' OR';
1335 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED);
1336 $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
1337 $params = array_merge($params, $inparamscourses);
1338 } else if ($courses === true) {
1339 // Events from ALL courses
1340 if(!empty($whereclause)) $whereclause .= ' OR';
1341 $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
1344 if ((is_array($categories) && !empty($categories)) || is_numeric($categories)) {
1345 if (!empty($whereclause)) {
1346 $whereclause .= ' OR';
1348 list($insqlcategories, $inparamscategories) = $DB->get_in_or_equal($categories, SQL_PARAMS_NAMED);
1349 $whereclause .= " (e.groupid = 0 AND e.courseid = 0 AND e.categoryid $insqlcategories)";
1350 $params = array_merge($params, $inparamscategories);
1351 } else if ($categories === true) {
1352 // Events from ALL categories.
1353 if (!empty($whereclause)) {
1354 $whereclause .= ' OR';
1356 $whereclause .= ' (e.groupid = 0 AND e.courseid = 0 AND e.categoryid != 0)';
1359 // Security check: if, by now, we have NOTHING in $whereclause, then it means
1360 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
1361 // events no matter what. Allowing the code to proceed might return a completely
1362 // valid query with only time constraints, thus selecting ALL events in that time frame!
1363 if(empty($whereclause)) {
1364 return array();
1367 if($withduration) {
1368 $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1370 else {
1371 $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1373 if(!empty($whereclause)) {
1374 // We have additional constraints
1375 $whereclause = $timeclause.' AND ('.$whereclause.')';
1377 else {
1378 // Just basic time filtering
1379 $whereclause = $timeclause;
1382 if ($ignorehidden) {
1383 $whereclause .= ' AND e.visible = 1';
1386 $sql = "SELECT e.*
1387 FROM {event} e
1388 LEFT JOIN {modules} m ON e.modulename = m.name
1389 -- Non visible modules will have a value of 0.
1390 WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
1391 ORDER BY e.timestart";
1392 $events = $DB->get_records_sql($sql, $params);
1394 if ($events === false) {
1395 $events = array();
1397 return $events;
1401 * Return the days of the week.
1403 * @return array array of days
1405 function calendar_get_days() {
1406 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1407 return $calendartype->get_weekdays();
1411 * Get the subscription from a given id.
1413 * @since Moodle 2.5
1414 * @param int $id id of the subscription
1415 * @return stdClass Subscription record from DB
1416 * @throws moodle_exception for an invalid id
1418 function calendar_get_subscription($id) {
1419 global $DB;
1421 $cache = \cache::make('core', 'calendar_subscriptions');
1422 $subscription = $cache->get($id);
1423 if (empty($subscription)) {
1424 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
1425 $cache->set($id, $subscription);
1428 return $subscription;
1432 * Gets the first day of the week.
1434 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
1436 * @return int
1438 function calendar_get_starting_weekday() {
1439 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1440 return $calendartype->get_starting_weekday();
1444 * Get a HTML link to a course.
1446 * @param int|stdClass $course the course id or course object
1447 * @return string a link to the course (as HTML); empty if the course id is invalid
1449 function calendar_get_courselink($course) {
1450 if (!$course) {
1451 return '';
1454 if (!is_object($course)) {
1455 $course = calendar_get_course_cached($coursecache, $course);
1457 $context = \context_course::instance($course->id);
1458 $fullname = format_string($course->fullname, true, array('context' => $context));
1459 $url = new \moodle_url('/course/view.php', array('id' => $course->id));
1460 $link = \html_writer::link($url, $fullname);
1462 return $link;
1466 * Get current module cache.
1468 * Only use this method if you do not know courseid. Otherwise use:
1469 * get_fast_modinfo($courseid)->instances[$modulename][$instance]
1471 * @param array $modulecache in memory module cache
1472 * @param string $modulename name of the module
1473 * @param int $instance module instance number
1474 * @return stdClass|bool $module information
1476 function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
1477 if (!isset($modulecache[$modulename . '_' . $instance])) {
1478 $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
1481 return $modulecache[$modulename . '_' . $instance];
1485 * Get current course cache.
1487 * @param array $coursecache list of course cache
1488 * @param int $courseid id of the course
1489 * @return stdClass $coursecache[$courseid] return the specific course cache
1491 function calendar_get_course_cached(&$coursecache, $courseid) {
1492 if (!isset($coursecache[$courseid])) {
1493 $coursecache[$courseid] = get_course($courseid);
1495 return $coursecache[$courseid];
1499 * Get group from groupid for calendar display
1501 * @param int $groupid
1502 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1504 function calendar_get_group_cached($groupid) {
1505 static $groupscache = array();
1506 if (!isset($groupscache[$groupid])) {
1507 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1509 return $groupscache[$groupid];
1513 * Add calendar event metadata
1515 * @param stdClass $event event info
1516 * @return stdClass $event metadata
1518 function calendar_add_event_metadata($event) {
1519 global $CFG, $OUTPUT;
1521 // Support multilang in event->name.
1522 $event->name = format_string($event->name, true);
1524 if (!empty($event->modulename)) { // Activity event.
1525 // The module name is set. I will assume that it has to be displayed, and
1526 // also that it is an automatically-generated event. And of course that the
1527 // instace id and modulename are set correctly.
1528 $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
1529 if (!array_key_exists($event->instance, $instances)) {
1530 return;
1532 $module = $instances[$event->instance];
1534 $modulename = $module->get_module_type_name(false);
1535 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
1536 // Will be used as alt text if the event icon.
1537 $eventtype = get_string($event->eventtype, $event->modulename);
1538 } else {
1539 $eventtype = '';
1542 $event->icon = '<img src="' . s($module->get_icon_url()) . '" alt="' . s($eventtype) .
1543 '" title="' . s($modulename) . '" class="icon" />';
1544 $event->referer = html_writer::link($module->url, $event->name);
1545 $event->courselink = calendar_get_courselink($module->get_course());
1546 $event->cmid = $module->id;
1547 } else if ($event->courseid == SITEID) { // Site event.
1548 $event->icon = '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
1549 get_string('globalevent', 'calendar') . '" class="icon" />';
1550 $event->cssclass = 'calendar_event_global';
1551 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event.
1552 $event->icon = '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
1553 get_string('courseevent', 'calendar') . '" class="icon" />';
1554 $event->courselink = calendar_get_courselink($event->courseid);
1555 $event->cssclass = 'calendar_event_course';
1556 } else if ($event->groupid) { // Group event.
1557 if ($group = calendar_get_group_cached($event->groupid)) {
1558 $groupname = format_string($group->name, true, \context_course::instance($group->courseid));
1559 } else {
1560 $groupname = '';
1562 $event->icon = \html_writer::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
1563 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
1564 $event->courselink = calendar_get_courselink($event->courseid) . ', ' . $groupname;
1565 $event->cssclass = 'calendar_event_group';
1566 } else if ($event->userid) { // User event.
1567 $event->icon = '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
1568 get_string('userevent', 'calendar') . '" class="icon" />';
1569 $event->cssclass = 'calendar_event_user';
1572 return $event;
1576 * Get calendar events by id.
1578 * @since Moodle 2.5
1579 * @param array $eventids list of event ids
1580 * @return array Array of event entries, empty array if nothing found
1582 function calendar_get_events_by_id($eventids) {
1583 global $DB;
1585 if (!is_array($eventids) || empty($eventids)) {
1586 return array();
1589 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
1590 $wheresql = "id $wheresql";
1592 return $DB->get_records_select('event', $wheresql, $params);
1596 * Get control options for calendar.
1598 * @param string $type of calendar
1599 * @param array $data calendar information
1600 * @return string $content return available control for the calender in html
1602 function calendar_top_controls($type, $data) {
1603 global $PAGE, $OUTPUT;
1605 // Get the calendar type we are using.
1606 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1608 $content = '';
1610 // Ensure course id passed if relevant.
1611 $courseid = '';
1612 if (!empty($data['id'])) {
1613 $courseid = '&amp;course=' . $data['id'];
1616 // If we are passing a month and year then we need to convert this to a timestamp to
1617 // support multiple calendars. No where in core should these be passed, this logic
1618 // here is for third party plugins that may use this function.
1619 if (!empty($data['m']) && !empty($date['y'])) {
1620 if (!isset($data['d'])) {
1621 $data['d'] = 1;
1623 if (!checkdate($data['m'], $data['d'], $data['y'])) {
1624 $time = time();
1625 } else {
1626 $time = make_timestamp($data['y'], $data['m'], $data['d']);
1628 } else if (!empty($data['time'])) {
1629 $time = $data['time'];
1630 } else {
1631 $time = time();
1634 // Get the date for the calendar type.
1635 $date = $calendartype->timestamp_to_date_array($time);
1637 $urlbase = $PAGE->url;
1639 // We need to get the previous and next months in certain cases.
1640 if ($type == 'frontpage' || $type == 'course' || $type == 'month') {
1641 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1642 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
1643 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
1644 $prevmonthtime['hour'], $prevmonthtime['minute']);
1646 $nextmonth = calendar_add_month($date['mon'], $date['year']);
1647 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
1648 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
1649 $nextmonthtime['hour'], $nextmonthtime['minute']);
1652 switch ($type) {
1653 case 'frontpage':
1654 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1655 true, $prevmonthtime);
1656 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true,
1657 $nextmonthtime);
1658 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1659 false, false, false, $time);
1661 if (!empty($data['id'])) {
1662 $calendarlink->param('course', $data['id']);
1665 $right = $nextlink;
1667 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1668 $content .= $prevlink . '<span class="hide"> | </span>';
1669 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1670 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1671 ), array('class' => 'current'));
1672 $content .= '<span class="hide"> | </span>' . $right;
1673 $content .= "<span class=\"clearer\"><!-- --></span>\n";
1674 $content .= \html_writer::end_tag('div');
1676 break;
1677 case 'course':
1678 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1679 true, $prevmonthtime);
1680 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false,
1681 true, $nextmonthtime);
1682 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1683 false, false, false, $time);
1685 if (!empty($data['id'])) {
1686 $calendarlink->param('course', $data['id']);
1689 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1690 $content .= $prevlink . '<span class="hide"> | </span>';
1691 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1692 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1693 ), array('class' => 'current'));
1694 $content .= '<span class="hide"> | </span>' . $nextlink;
1695 $content .= "<span class=\"clearer\"><!-- --></span>";
1696 $content .= \html_writer::end_tag('div');
1697 break;
1698 case 'upcoming':
1699 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'upcoming')),
1700 false, false, false, $time);
1701 if (!empty($data['id'])) {
1702 $calendarlink->param('course', $data['id']);
1704 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1705 $content .= \html_writer::tag('div', $calendarlink, array('class' => 'centered'));
1706 break;
1707 case 'display':
1708 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1709 false, false, false, $time);
1710 if (!empty($data['id'])) {
1711 $calendarlink->param('course', $data['id']);
1713 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1714 $content .= \html_writer::tag('h3', $calendarlink);
1715 break;
1716 case 'month':
1717 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1718 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $prevmonthtime);
1719 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1720 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $nextmonthtime);
1722 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1723 $content .= $prevlink . '<span class="hide"> | </span>';
1724 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1725 $content .= '<span class="hide"> | </span>' . $nextlink;
1726 $content .= '<span class="clearer"><!-- --></span>';
1727 $content .= \html_writer::end_tag('div')."\n";
1728 break;
1729 case 'day':
1730 $days = calendar_get_days();
1732 $prevtimestamp = strtotime('-1 day', $time);
1733 $nexttimestamp = strtotime('+1 day', $time);
1735 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1736 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1738 $prevname = $days[$prevdate['wday']]['fullname'];
1739 $nextname = $days[$nextdate['wday']]['fullname'];
1740 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&amp;', false, false,
1741 false, false, $prevtimestamp);
1742 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&amp;', false, false, false,
1743 false, $nexttimestamp);
1745 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1746 $content .= $prevlink;
1747 $content .= '<span class="hide"> | </span><span class="current">' .userdate($time,
1748 get_string('strftimedaydate')) . '</span>';
1749 $content .= '<span class="hide"> | </span>' . $nextlink;
1750 $content .= "<span class=\"clearer\"><!-- --></span>";
1751 $content .= \html_writer::end_tag('div') . "\n";
1753 break;
1756 return $content;
1760 * Return the representation day.
1762 * @param int $tstamp Timestamp in GMT
1763 * @param int|bool $now current Unix timestamp
1764 * @param bool $usecommonwords
1765 * @return string the formatted date/time
1767 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1768 static $shortformat;
1770 if (empty($shortformat)) {
1771 $shortformat = get_string('strftimedayshort');
1774 if ($now === false) {
1775 $now = time();
1778 // To have it in one place, if a change is needed.
1779 $formal = userdate($tstamp, $shortformat);
1781 $datestamp = usergetdate($tstamp);
1782 $datenow = usergetdate($now);
1784 if ($usecommonwords == false) {
1785 // We don't want words, just a date.
1786 return $formal;
1787 } else if ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1788 return get_string('today', 'calendar');
1789 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1790 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12
1791 && $datenow['yday'] == 1)) {
1792 return get_string('yesterday', 'calendar');
1793 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1794 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12
1795 && $datestamp['yday'] == 1)) {
1796 return get_string('tomorrow', 'calendar');
1797 } else {
1798 return $formal;
1803 * return the formatted representation time.
1806 * @param int $time the timestamp in UTC, as obtained from the database
1807 * @return string the formatted date/time
1809 function calendar_time_representation($time) {
1810 static $langtimeformat = null;
1812 if ($langtimeformat === null) {
1813 $langtimeformat = get_string('strftimetime');
1816 $timeformat = get_user_preferences('calendar_timeformat');
1817 if (empty($timeformat)) {
1818 $timeformat = get_config(null, 'calendar_site_timeformat');
1821 // Allow language customization of selected time format.
1822 if ($timeformat === CALENDAR_TF_12) {
1823 $timeformat = get_string('strftimetime12', 'langconfig');
1824 } else if ($timeformat === CALENDAR_TF_24) {
1825 $timeformat = get_string('strftimetime24', 'langconfig');
1828 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
1832 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1834 * @param string|moodle_url $linkbase
1835 * @param int $d The number of the day.
1836 * @param int $m The number of the month.
1837 * @param int $y The number of the year.
1838 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1839 * $m and $y are kept for backwards compatibility.
1840 * @return moodle_url|null $linkbase
1842 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1843 if (empty($linkbase)) {
1844 return null;
1847 if (!($linkbase instanceof \moodle_url)) {
1848 $linkbase = new \moodle_url($linkbase);
1851 $linkbase->param('time', calendar_get_timestamp($d, $m, $y, $time));
1853 return $linkbase;
1857 * Build and return a previous month HTML link, with an arrow.
1859 * @param string $text The text label.
1860 * @param string|moodle_url $linkbase The URL stub.
1861 * @param int $d The number of the date.
1862 * @param int $m The number of the month.
1863 * @param int $y year The number of the year.
1864 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1865 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1866 * $m and $y are kept for backwards compatibility.
1867 * @return string HTML string.
1869 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1870 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1872 if (empty($href)) {
1873 return $text;
1876 $attrs = [
1877 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1878 'data-drop-zone' => 'nav-link',
1881 return link_arrow_left($text, $href->out(false), $accesshide, 'previous', $attrs);
1885 * Build and return a next month HTML link, with an arrow.
1887 * @param string $text The text label.
1888 * @param string|moodle_url $linkbase The URL stub.
1889 * @param int $d the number of the Day
1890 * @param int $m The number of the month.
1891 * @param int $y The number of the year.
1892 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1893 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1894 * $m and $y are kept for backwards compatibility.
1895 * @return string HTML string.
1897 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1898 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1900 if (empty($href)) {
1901 return $text;
1904 $attrs = [
1905 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1906 'data-drop-zone' => 'nav-link',
1909 return link_arrow_right($text, $href->out(false), $accesshide, 'next', $attrs);
1913 * Return the number of days in month.
1915 * @param int $month the number of the month.
1916 * @param int $year the number of the year
1917 * @return int
1919 function calendar_days_in_month($month, $year) {
1920 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1921 return $calendartype->get_num_days_in_month($year, $month);
1925 * Get the next following month.
1927 * @param int $month the number of the month.
1928 * @param int $year the number of the year.
1929 * @return array the following month
1931 function calendar_add_month($month, $year) {
1932 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1933 return $calendartype->get_next_month($year, $month);
1937 * Get the previous month.
1939 * @param int $month the number of the month.
1940 * @param int $year the number of the year.
1941 * @return array previous month
1943 function calendar_sub_month($month, $year) {
1944 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1945 return $calendartype->get_prev_month($year, $month);
1949 * Get per-day basis events
1951 * @param array $events list of events
1952 * @param int $month the number of the month
1953 * @param int $year the number of the year
1954 * @param array $eventsbyday event on specific day
1955 * @param array $durationbyday duration of the event in days
1956 * @param array $typesbyday event type (eg: global, course, user, or group)
1957 * @param array $courses list of courses
1958 * @return void
1960 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1961 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1963 $eventsbyday = array();
1964 $typesbyday = array();
1965 $durationbyday = array();
1967 if ($events === false) {
1968 return;
1971 foreach ($events as $event) {
1972 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
1973 if ($event->timeduration) {
1974 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
1975 } else {
1976 $enddate = $startdate;
1979 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair.
1980 if (!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) &&
1981 ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1982 continue;
1985 $eventdaystart = intval($startdate['mday']);
1987 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
1988 // Give the event to its day.
1989 $eventsbyday[$eventdaystart][] = $event->id;
1991 // Mark the day as having such an event.
1992 if ($event->courseid == SITEID && $event->groupid == 0) {
1993 $typesbyday[$eventdaystart]['startglobal'] = true;
1994 // Set event class for global event.
1995 $events[$event->id]->class = 'calendar_event_global';
1996 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1997 $typesbyday[$eventdaystart]['startcourse'] = true;
1998 // Set event class for course event.
1999 $events[$event->id]->class = 'calendar_event_course';
2000 } else if ($event->groupid) {
2001 $typesbyday[$eventdaystart]['startgroup'] = true;
2002 // Set event class for group event.
2003 $events[$event->id]->class = 'calendar_event_group';
2004 } else if ($event->userid) {
2005 $typesbyday[$eventdaystart]['startuser'] = true;
2006 // Set event class for user event.
2007 $events[$event->id]->class = 'calendar_event_user';
2011 if ($event->timeduration == 0) {
2012 // Proceed with the next.
2013 continue;
2016 // The event starts on $month $year or before.
2017 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2018 $lowerbound = intval($startdate['mday']);
2019 } else {
2020 $lowerbound = 0;
2023 // Also, it ends on $month $year or later.
2024 if ($enddate['mon'] == $month && $enddate['year'] == $year) {
2025 $upperbound = intval($enddate['mday']);
2026 } else {
2027 $upperbound = calendar_days_in_month($month, $year);
2030 // Mark all days between $lowerbound and $upperbound (inclusive) as duration.
2031 for ($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
2032 $durationbyday[$i][] = $event->id;
2033 if ($event->courseid == SITEID && $event->groupid == 0) {
2034 $typesbyday[$i]['durationglobal'] = true;
2035 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
2036 $typesbyday[$i]['durationcourse'] = true;
2037 } else if ($event->groupid) {
2038 $typesbyday[$i]['durationgroup'] = true;
2039 } else if ($event->userid) {
2040 $typesbyday[$i]['durationuser'] = true;
2045 return;
2049 * Returns the courses to load events for.
2051 * @param array $courseeventsfrom An array of courses to load calendar events for
2052 * @param bool $ignorefilters specify the use of filters, false is set as default
2053 * @param stdClass $user The user object. This defaults to the global $USER object.
2054 * @return array An array of courses, groups, and user to load calendar events for based upon filters
2056 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false, stdClass $user = null) {
2057 global $CFG, $USER;
2059 if (is_null($user)) {
2060 $user = $USER;
2063 $courses = array();
2064 $userid = false;
2065 $group = false;
2067 // Get the capabilities that allow seeing group events from all groups.
2068 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
2070 $isvaliduser = !empty($user->id);
2072 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE, $user)) {
2073 $courses = array_keys($courseeventsfrom);
2075 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL, $user)) {
2076 $courses[] = SITEID;
2078 $courses = array_unique($courses);
2079 sort($courses);
2081 if (!empty($courses) && in_array(SITEID, $courses)) {
2082 // Sort courses for consistent colour highlighting.
2083 // Effectively ignoring SITEID as setting as last course id.
2084 $key = array_search(SITEID, $courses);
2085 unset($courses[$key]);
2086 $courses[] = SITEID;
2089 if ($ignorefilters || ($isvaliduser && calendar_show_event_type(CALENDAR_EVENT_USER, $user))) {
2090 $userid = $user->id;
2093 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP, $user) || $ignorefilters)) {
2095 if (count($courseeventsfrom) == 1) {
2096 $course = reset($courseeventsfrom);
2097 if (has_any_capability($allgroupscaps, \context_course::instance($course->id))) {
2098 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
2099 $group = array_keys($coursegroups);
2102 if ($group === false) {
2103 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, \context_system::instance())) {
2104 $group = true;
2105 } else if ($isvaliduser) {
2106 $groupids = array();
2107 foreach ($courseeventsfrom as $courseid => $course) {
2108 // If the user is an editing teacher in there.
2109 if (!empty($user->groupmember[$course->id])) {
2110 // We've already cached the users groups for this course so we can just use that.
2111 $groupids = array_merge($groupids, $user->groupmember[$course->id]);
2112 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2113 // If this course has groups, show events from all of those related to the current user.
2114 $coursegroups = groups_get_user_groups($course->id, $user->id);
2115 $groupids = array_merge($groupids, $coursegroups['0']);
2118 if (!empty($groupids)) {
2119 $group = $groupids;
2124 if (empty($courses)) {
2125 $courses = false;
2128 return array($courses, $group, $userid);
2132 * Return the capability for viewing a calendar event.
2134 * @param calendar_event $event event object
2135 * @return boolean
2137 function calendar_view_event_allowed(calendar_event $event) {
2138 global $USER;
2140 // Anyone can see site events.
2141 if ($event->courseid && $event->courseid == SITEID) {
2142 return true;
2145 // If a user can manage events at the site level they can see any event.
2146 $sitecontext = \context_system::instance();
2147 // If user has manageentries at site level, return true.
2148 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2149 return true;
2152 if (!empty($event->groupid)) {
2153 // If it is a group event we need to be able to manage events in the course, or be in the group.
2154 if (has_capability('moodle/calendar:manageentries', $event->context) ||
2155 has_capability('moodle/calendar:managegroupentries', $event->context)) {
2156 return true;
2159 $mycourses = enrol_get_my_courses('id');
2160 return isset($mycourses[$event->courseid]) && groups_is_member($event->groupid);
2161 } else if ($event->modulename) {
2162 // If this is a module event we need to be able to see the module.
2163 $coursemodules = [];
2164 $courseid = 0;
2165 // Override events do not have the courseid set.
2166 if ($event->courseid) {
2167 $courseid = $event->courseid;
2168 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2169 } else {
2170 $cmraw = get_coursemodule_from_instance($event->modulename, $event->instance, 0, false, MUST_EXIST);
2171 $courseid = $cmraw->course;
2172 $coursemodules = get_fast_modinfo($cmraw->course)->instances;
2174 $hasmodule = isset($coursemodules[$event->modulename]);
2175 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2177 // If modinfo doesn't know about the module, return false to be safe.
2178 if (!$hasmodule || !$hasinstance) {
2179 return false;
2182 // Must be able to see the course and the module - MDL-59304.
2183 $cm = $coursemodules[$event->modulename][$event->instance];
2184 if (!$cm->uservisible) {
2185 return false;
2187 $mycourses = enrol_get_my_courses('id');
2188 return isset($mycourses[$courseid]);
2189 } else if ($event->categoryid) {
2190 // If this is a category we need to be able to see the category.
2191 $cat = \core_course_category::get($event->categoryid, IGNORE_MISSING);
2192 if (!$cat) {
2193 return false;
2195 return true;
2196 } else if (!empty($event->courseid)) {
2197 // If it is a course event we need to be able to manage events in the course, or be in the course.
2198 if (has_capability('moodle/calendar:manageentries', $event->context)) {
2199 return true;
2201 $mycourses = enrol_get_my_courses('id');
2202 return isset($mycourses[$event->courseid]);
2203 } else if ($event->userid) {
2204 if ($event->userid != $USER->id) {
2205 // No-one can ever see another users events.
2206 return false;
2208 return true;
2209 } else {
2210 throw new moodle_exception('unknown event type');
2213 return false;
2217 * Return the capability for editing calendar event.
2219 * @param calendar_event $event event object
2220 * @param bool $manualedit is the event being edited manually by the user
2221 * @return bool capability to edit event
2223 function calendar_edit_event_allowed($event, $manualedit = false) {
2224 global $USER, $DB;
2226 // Must be logged in.
2227 if (!isloggedin()) {
2228 return false;
2231 // Can not be using guest account.
2232 if (isguestuser()) {
2233 return false;
2236 if ($manualedit && !empty($event->modulename)) {
2237 $hascallback = component_callback_exists(
2238 'mod_' . $event->modulename,
2239 'core_calendar_event_timestart_updated'
2242 if (!$hascallback) {
2243 // If the activity hasn't implemented the correct callback
2244 // to handle changes to it's events then don't allow any
2245 // manual changes to them.
2246 return false;
2249 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2250 $hasmodule = isset($coursemodules[$event->modulename]);
2251 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2253 // If modinfo doesn't know about the module, return false to be safe.
2254 if (!$hasmodule || !$hasinstance) {
2255 return false;
2258 $coursemodule = $coursemodules[$event->modulename][$event->instance];
2259 $context = context_module::instance($coursemodule->id);
2260 // This is the capability that allows a user to modify the activity
2261 // settings. Since the activity generated this event we need to check
2262 // that the current user has the same capability before allowing them
2263 // to update the event because the changes to the event will be
2264 // reflected within the activity.
2265 return has_capability('moodle/course:manageactivities', $context);
2268 // You cannot edit URL based calendar subscription events presently.
2269 if (!empty($event->subscriptionid)) {
2270 if (!empty($event->subscription->url)) {
2271 // This event can be updated externally, so it cannot be edited.
2272 return false;
2276 $sitecontext = \context_system::instance();
2278 // If user has manageentries at site level, return true.
2279 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2280 return true;
2283 // If groupid is set, it's definitely a group event.
2284 if (!empty($event->groupid)) {
2285 // Allow users to add/edit group events if -
2286 // 1) They have manageentries for the course OR
2287 // 2) They have managegroupentries AND are in the group.
2288 $group = $DB->get_record('groups', array('id' => $event->groupid));
2289 return $group && (
2290 has_capability('moodle/calendar:manageentries', $event->context) ||
2291 (has_capability('moodle/calendar:managegroupentries', $event->context)
2292 && groups_is_member($event->groupid)));
2293 } else if (!empty($event->courseid)) {
2294 // If groupid is not set, but course is set, it's definitely a course event.
2295 return has_capability('moodle/calendar:manageentries', $event->context);
2296 } else if (!empty($event->categoryid)) {
2297 // If groupid is not set, but category is set, it's definitely a category event.
2298 return has_capability('moodle/calendar:manageentries', $event->context);
2299 } else if (!empty($event->userid) && $event->userid == $USER->id) {
2300 // If course is not set, but userid id set, it's a user event.
2301 return (has_capability('moodle/calendar:manageownentries', $event->context));
2302 } else if (!empty($event->userid)) {
2303 return (has_capability('moodle/calendar:manageentries', $event->context));
2306 return false;
2310 * Return the capability for deleting a calendar event.
2312 * @param calendar_event $event The event object
2313 * @return bool Whether the user has permission to delete the event or not.
2315 function calendar_delete_event_allowed($event) {
2316 // Only allow delete if you have capabilities and it is not an module event.
2317 return (calendar_edit_event_allowed($event) && empty($event->modulename));
2321 * Returns the default courses to display on the calendar when there isn't a specific
2322 * course to display.
2324 * @param int $courseid (optional) If passed, an additional course can be returned for admins (the current course).
2325 * @param string $fields Comma separated list of course fields to return.
2326 * @param bool $canmanage If true, this will return the list of courses the user can create events in, rather
2327 * than the list of courses they see events from (an admin can always add events in a course
2328 * calendar, even if they are not enrolled in the course).
2329 * @param int $userid (optional) The user which this function returns the default courses for.
2330 * By default the current user.
2331 * @return array $courses Array of courses to display
2333 function calendar_get_default_courses($courseid = null, $fields = '*', $canmanage = false, int $userid = null) {
2334 global $CFG, $USER;
2336 if (!$userid) {
2337 if (!isloggedin()) {
2338 return array();
2340 $userid = $USER->id;
2343 if ((!empty($CFG->calendar_adminseesall) || $canmanage) &&
2344 has_capability('moodle/calendar:manageentries', context_system::instance(), $userid)) {
2346 // Add a c. prefix to every field as expected by get_courses function.
2347 $fieldlist = explode(',', $fields);
2349 $prefixedfields = array_map(function($value) {
2350 return 'c.' . trim(strtolower($value));
2351 }, $fieldlist);
2352 if (!in_array('c.visible', $prefixedfields) && !in_array('c.*', $prefixedfields)) {
2353 $prefixedfields[] = 'c.visible';
2355 $courses = get_courses('all', 'c.shortname', implode(',', $prefixedfields));
2356 } else {
2357 $courses = enrol_get_users_courses($userid, true, $fields);
2360 if ($courseid && $courseid != SITEID) {
2361 if (empty($courses[$courseid]) && has_capability('moodle/calendar:manageentries', context_system::instance(), $userid)) {
2362 // Allow a site admin to see calendars from courses he is not enrolled in.
2363 // This will come from $COURSE.
2364 $courses[$courseid] = get_course($courseid);
2368 return $courses;
2372 * Get event format time.
2374 * @param calendar_event $event event object
2375 * @param int $now current time in gmt
2376 * @param array $linkparams list of params for event link
2377 * @param bool $usecommonwords the words as formatted date/time.
2378 * @param int $showtime determine the show time GMT timestamp
2379 * @return string $eventtime link/string for event time
2381 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
2382 $starttime = $event->timestart;
2383 $endtime = $event->timestart + $event->timeduration;
2385 if (empty($linkparams) || !is_array($linkparams)) {
2386 $linkparams = array();
2389 $linkparams['view'] = 'day';
2391 // OK, now to get a meaningful display.
2392 // Check if there is a duration for this event.
2393 if ($event->timeduration) {
2394 // Get the midnight of the day the event will start.
2395 $usermidnightstart = usergetmidnight($starttime);
2396 // Get the midnight of the day the event will end.
2397 $usermidnightend = usergetmidnight($endtime);
2398 // Check if we will still be on the same day.
2399 if ($usermidnightstart == $usermidnightend) {
2400 // Check if we are running all day.
2401 if ($event->timeduration == DAYSECS) {
2402 $time = get_string('allday', 'calendar');
2403 } else { // Specify the time we will be running this from.
2404 $datestart = calendar_time_representation($starttime);
2405 $dateend = calendar_time_representation($endtime);
2406 $time = $datestart . ' <strong>&raquo;</strong> ' . $dateend;
2409 // Set printable representation.
2410 if (!$showtime) {
2411 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2412 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2413 $eventtime = \html_writer::link($url, $day) . ', ' . $time;
2414 } else {
2415 $eventtime = $time;
2417 } else { // It must spans two or more days.
2418 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
2419 if ($showtime == $usermidnightstart) {
2420 $daystart = '';
2422 $timestart = calendar_time_representation($event->timestart);
2423 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
2424 if ($showtime == $usermidnightend) {
2425 $dayend = '';
2427 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
2429 // Set printable representation.
2430 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2431 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2432 $eventtime = $timestart . ' <strong>&raquo;</strong> ' . \html_writer::link($url, $dayend) . $timeend;
2433 } else {
2434 // The event is in the future, print start and end links.
2435 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2436 $eventtime = \html_writer::link($url, $daystart) . $timestart . ' <strong>&raquo;</strong> ';
2438 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2439 $eventtime .= \html_writer::link($url, $dayend) . $timeend;
2442 } else { // There is no time duration.
2443 $time = calendar_time_representation($event->timestart);
2444 // Set printable representation.
2445 if (!$showtime) {
2446 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2447 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2448 $eventtime = \html_writer::link($url, $day) . ', ' . trim($time);
2449 } else {
2450 $eventtime = $time;
2454 // Check if It has expired.
2455 if ($event->timestart + $event->timeduration < $now) {
2456 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2459 return $eventtime;
2463 * Checks to see if the requested type of event should be shown for the given user.
2465 * @param int $type The type to check the display for (default is to display all)
2466 * @param stdClass|int|null $user The user to check for - by default the current user
2467 * @return bool True if the tyep should be displayed false otherwise
2469 function calendar_show_event_type($type, $user = null) {
2470 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
2472 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2473 global $SESSION;
2474 if (!isset($SESSION->calendarshoweventtype)) {
2475 $SESSION->calendarshoweventtype = $default;
2477 return $SESSION->calendarshoweventtype & $type;
2478 } else {
2479 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2484 * Sets the display of the event type given $display.
2486 * If $display = true the event type will be shown.
2487 * If $display = false the event type will NOT be shown.
2488 * If $display = null the current value will be toggled and saved.
2490 * @param int $type object of CALENDAR_EVENT_XXX
2491 * @param bool $display option to display event type
2492 * @param stdClass|int $user moodle user object or id, null means current user
2494 function calendar_set_event_type_display($type, $display = null, $user = null) {
2495 $persist = get_user_preferences('calendar_persistflt', 0, $user);
2496 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP
2497 + CALENDAR_EVENT_USER + CALENDAR_EVENT_COURSECAT;
2498 if ($persist === 0) {
2499 global $SESSION;
2500 if (!isset($SESSION->calendarshoweventtype)) {
2501 $SESSION->calendarshoweventtype = $default;
2503 $preference = $SESSION->calendarshoweventtype;
2504 } else {
2505 $preference = get_user_preferences('calendar_savedflt', $default, $user);
2507 $current = $preference & $type;
2508 if ($display === null) {
2509 $display = !$current;
2511 if ($display && !$current) {
2512 $preference += $type;
2513 } else if (!$display && $current) {
2514 $preference -= $type;
2516 if ($persist === 0) {
2517 $SESSION->calendarshoweventtype = $preference;
2518 } else {
2519 if ($preference == $default) {
2520 unset_user_preference('calendar_savedflt', $user);
2521 } else {
2522 set_user_preference('calendar_savedflt', $preference, $user);
2528 * Get calendar's allowed types.
2530 * @param stdClass $allowed list of allowed edit for event type
2531 * @param stdClass|int $course object of a course or course id
2532 * @param array $groups array of groups for the given course
2533 * @param stdClass|int $category object of a category
2535 function calendar_get_allowed_types(&$allowed, $course = null, $groups = null, $category = null) {
2536 global $USER, $DB;
2538 $allowed = new \stdClass();
2539 $allowed->user = has_capability('moodle/calendar:manageownentries', \context_system::instance());
2540 $allowed->groups = false;
2541 $allowed->courses = false;
2542 $allowed->categories = false;
2543 $allowed->site = has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID));
2544 $getgroupsfunc = function($course, $context, $user) use ($groups) {
2545 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2546 if (has_capability('moodle/site:accessallgroups', $context)) {
2547 return is_null($groups) ? groups_get_all_groups($course->id) : $groups;
2548 } else {
2549 if (is_null($groups)) {
2550 return groups_get_all_groups($course->id, $user->id);
2551 } else {
2552 return array_filter($groups, function($group) use ($user) {
2553 return isset($group->members[$user->id]);
2559 return false;
2562 if (!empty($course)) {
2563 if (!is_object($course)) {
2564 $course = $DB->get_record('course', array('id' => $course), 'id, groupmode, groupmodeforce', MUST_EXIST);
2566 if ($course->id != SITEID) {
2567 $coursecontext = \context_course::instance($course->id);
2568 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
2570 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2571 $allowed->courses = array($course->id => 1);
2572 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2573 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
2574 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2579 if (!empty($category)) {
2580 $catcontext = \context_coursecat::instance($category->id);
2581 if (has_capability('moodle/category:manage', $catcontext)) {
2582 $allowed->categories = [$category->id => 1];
2588 * See if user can add calendar entries at all used to print the "New Event" button.
2590 * @param stdClass $course object of a course or course id
2591 * @return bool has the capability to add at least one event type
2593 function calendar_user_can_add_event($course) {
2594 if (!isloggedin() || isguestuser()) {
2595 return false;
2598 calendar_get_allowed_types($allowed, $course);
2600 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->categories || $allowed->site);
2604 * Check wether the current user is permitted to add events.
2606 * @param stdClass $event object of event
2607 * @return bool has the capability to add event
2609 function calendar_add_event_allowed($event) {
2610 global $USER, $DB;
2612 // Can not be using guest account.
2613 if (!isloggedin() or isguestuser()) {
2614 return false;
2617 $sitecontext = \context_system::instance();
2619 // If user has manageentries at site level, always return true.
2620 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2621 return true;
2624 switch ($event->eventtype) {
2625 case 'category':
2626 return has_capability('moodle/category:manage', $event->context);
2627 case 'course':
2628 return has_capability('moodle/calendar:manageentries', $event->context);
2629 case 'group':
2630 // Allow users to add/edit group events if -
2631 // 1) They have manageentries (= entries for whole course).
2632 // 2) They have managegroupentries AND are in the group.
2633 $group = $DB->get_record('groups', array('id' => $event->groupid));
2634 return $group && (
2635 has_capability('moodle/calendar:manageentries', $event->context) ||
2636 (has_capability('moodle/calendar:managegroupentries', $event->context)
2637 && groups_is_member($event->groupid)));
2638 case 'user':
2639 if ($event->userid == $USER->id) {
2640 return (has_capability('moodle/calendar:manageownentries', $event->context));
2642 // There is intentionally no 'break'.
2643 case 'site':
2644 return has_capability('moodle/calendar:manageentries', $event->context);
2645 default:
2646 return has_capability('moodle/calendar:manageentries', $event->context);
2651 * Returns option list for the poll interval setting.
2653 * @return array An array of poll interval options. Interval => description.
2655 function calendar_get_pollinterval_choices() {
2656 return array(
2657 '0' => new \lang_string('never', 'calendar'),
2658 HOURSECS => new \lang_string('hourly', 'calendar'),
2659 DAYSECS => new \lang_string('daily', 'calendar'),
2660 WEEKSECS => new \lang_string('weekly', 'calendar'),
2661 '2628000' => new \lang_string('monthly', 'calendar'),
2662 YEARSECS => new \lang_string('annually', 'calendar')
2667 * Returns option list of available options for the calendar event type, given the current user and course.
2669 * @param int $courseid The id of the course
2670 * @return array An array containing the event types the user can create.
2672 function calendar_get_eventtype_choices($courseid) {
2673 $choices = array();
2674 $allowed = new \stdClass;
2675 calendar_get_allowed_types($allowed, $courseid);
2677 if ($allowed->user) {
2678 $choices['user'] = get_string('userevents', 'calendar');
2680 if ($allowed->site) {
2681 $choices['site'] = get_string('siteevents', 'calendar');
2683 if (!empty($allowed->courses)) {
2684 $choices['course'] = get_string('courseevents', 'calendar');
2686 if (!empty($allowed->categories)) {
2687 $choices['category'] = get_string('categoryevents', 'calendar');
2689 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2690 $choices['group'] = get_string('group');
2693 return array($choices, $allowed->groups);
2697 * Add an iCalendar subscription to the database.
2699 * @param stdClass $sub The subscription object (e.g. from the form)
2700 * @return int The insert ID, if any.
2702 function calendar_add_subscription($sub) {
2703 global $DB, $USER, $SITE;
2705 // Undo the form definition work around to allow us to have two different
2706 // course selectors present depending on which event type the user selects.
2707 if (!empty($sub->groupcourseid)) {
2708 $sub->courseid = $sub->groupcourseid;
2709 unset($sub->groupcourseid);
2712 // Default course id if none is set.
2713 if (empty($sub->courseid)) {
2714 if ($sub->eventtype === 'site') {
2715 $sub->courseid = SITEID;
2716 } else {
2717 $sub->courseid = 0;
2721 if ($sub->eventtype === 'site') {
2722 $sub->courseid = $SITE->id;
2723 } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
2724 $sub->courseid = $sub->courseid;
2725 } else if ($sub->eventtype === 'category') {
2726 $sub->categoryid = $sub->categoryid;
2727 } else {
2728 // User events.
2729 $sub->courseid = 0;
2731 $sub->userid = $USER->id;
2733 // File subscriptions never update.
2734 if (empty($sub->url)) {
2735 $sub->pollinterval = 0;
2738 if (!empty($sub->name)) {
2739 if (empty($sub->id)) {
2740 $id = $DB->insert_record('event_subscriptions', $sub);
2741 // We cannot cache the data here because $sub is not complete.
2742 $sub->id = $id;
2743 // Trigger event, calendar subscription added.
2744 $eventparams = array('objectid' => $sub->id,
2745 'context' => calendar_get_calendar_context($sub),
2746 'other' => array(
2747 'eventtype' => $sub->eventtype,
2750 switch ($sub->eventtype) {
2751 case 'category':
2752 $eventparams['other']['categoryid'] = $sub->categoryid;
2753 break;
2754 case 'course':
2755 $eventparams['other']['courseid'] = $sub->courseid;
2756 break;
2757 case 'group':
2758 $eventparams['other']['courseid'] = $sub->courseid;
2759 $eventparams['other']['groupid'] = $sub->groupid;
2760 break;
2761 default:
2762 $eventparams['other']['courseid'] = $sub->courseid;
2765 $event = \core\event\calendar_subscription_created::create($eventparams);
2766 $event->trigger();
2767 return $id;
2768 } else {
2769 // Why are we doing an update here?
2770 calendar_update_subscription($sub);
2771 return $sub->id;
2773 } else {
2774 print_error('errorbadsubscription', 'importcalendar');
2779 * Add an iCalendar event to the Moodle calendar.
2781 * @param stdClass $event The RFC-2445 iCalendar event
2782 * @param int $unused Deprecated
2783 * @param int $subscriptionid The iCalendar subscription ID
2784 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2785 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2786 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2788 function calendar_add_icalendar_event($event, $unused = null, $subscriptionid, $timezone='UTC') {
2789 global $DB;
2791 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2792 if (empty($event->properties['SUMMARY'])) {
2793 return 0;
2796 $name = $event->properties['SUMMARY'][0]->value;
2797 $name = str_replace('\n', '<br />', $name);
2798 $name = str_replace('\\', '', $name);
2799 $name = preg_replace('/\s+/u', ' ', $name);
2801 $eventrecord = new \stdClass;
2802 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
2804 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2805 $description = '';
2806 } else {
2807 $description = $event->properties['DESCRIPTION'][0]->value;
2808 $description = clean_param($description, PARAM_NOTAGS);
2809 $description = str_replace('\n', '<br />', $description);
2810 $description = str_replace('\\', '', $description);
2811 $description = preg_replace('/\s+/u', ' ', $description);
2813 $eventrecord->description = $description;
2815 // Probably a repeating event with RRULE etc. TODO: skip for now.
2816 if (empty($event->properties['DTSTART'][0]->value)) {
2817 return 0;
2820 if (isset($event->properties['DTSTART'][0]->parameters['TZID'])) {
2821 $tz = $event->properties['DTSTART'][0]->parameters['TZID'];
2822 } else {
2823 $tz = $timezone;
2825 $tz = \core_date::normalise_timezone($tz);
2826 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value . ' ' . $tz);
2827 if (empty($event->properties['DTEND'])) {
2828 $eventrecord->timeduration = 0; // No duration if no end time specified.
2829 } else {
2830 if (isset($event->properties['DTEND'][0]->parameters['TZID'])) {
2831 $endtz = $event->properties['DTEND'][0]->parameters['TZID'];
2832 } else {
2833 $endtz = $timezone;
2835 $endtz = \core_date::normalise_timezone($endtz);
2836 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value . ' ' . $endtz) - $eventrecord->timestart;
2839 // Check to see if it should be treated as an all day event.
2840 if ($eventrecord->timeduration == DAYSECS) {
2841 // Check to see if the event started at Midnight on the imported calendar.
2842 date_default_timezone_set($timezone);
2843 if (date('H:i:s', $eventrecord->timestart) === "00:00:00") {
2844 // This event should be an all day event. This is not correct, we don't do anything differently for all day events.
2845 // See MDL-56227.
2846 $eventrecord->timeduration = 0;
2848 \core_date::set_default_server_timezone();
2851 $eventrecord->location = empty($event->properties['LOCATION'][0]->value) ? '' :
2852 str_replace('\\', '', $event->properties['LOCATION'][0]->value);
2853 $eventrecord->uuid = $event->properties['UID'][0]->value;
2854 $eventrecord->timemodified = time();
2856 // Add the iCal subscription details if required.
2857 // We should never do anything with an event without a subscription reference.
2858 $sub = calendar_get_subscription($subscriptionid);
2859 $eventrecord->subscriptionid = $subscriptionid;
2860 $eventrecord->userid = $sub->userid;
2861 $eventrecord->groupid = $sub->groupid;
2862 $eventrecord->courseid = $sub->courseid;
2863 $eventrecord->categoryid = $sub->categoryid;
2864 $eventrecord->eventtype = $sub->eventtype;
2866 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid,
2867 'subscriptionid' => $eventrecord->subscriptionid))) {
2868 $eventrecord->id = $updaterecord->id;
2869 $return = CALENDAR_IMPORT_EVENT_UPDATED; // Update.
2870 } else {
2871 $return = CALENDAR_IMPORT_EVENT_INSERTED; // Insert.
2873 if ($createdevent = \calendar_event::create($eventrecord, false)) {
2874 if (!empty($event->properties['RRULE'])) {
2875 // Repeating events.
2876 date_default_timezone_set($tz); // Change time zone to parse all events.
2877 $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
2878 $rrule->parse_rrule();
2879 $rrule->create_events($createdevent);
2880 \core_date::set_default_server_timezone(); // Change time zone back to what it was.
2882 return $return;
2883 } else {
2884 return 0;
2889 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2891 * @param int $subscriptionid The ID of the subscription we are acting upon.
2892 * @param int $pollinterval The poll interval to use.
2893 * @param int $action The action to be performed. One of update or remove.
2894 * @throws dml_exception if invalid subscriptionid is provided
2895 * @return string A log of the import progress, including errors
2897 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2898 // Fetch the subscription from the database making sure it exists.
2899 $sub = calendar_get_subscription($subscriptionid);
2901 // Update or remove the subscription, based on action.
2902 switch ($action) {
2903 case CALENDAR_SUBSCRIPTION_UPDATE:
2904 // Skip updating file subscriptions.
2905 if (empty($sub->url)) {
2906 break;
2908 $sub->pollinterval = $pollinterval;
2909 calendar_update_subscription($sub);
2911 // Update the events.
2912 return "<p>" . get_string('subscriptionupdated', 'calendar', $sub->name) . "</p>" .
2913 calendar_update_subscription_events($subscriptionid);
2914 case CALENDAR_SUBSCRIPTION_REMOVE:
2915 calendar_delete_subscription($subscriptionid);
2916 return get_string('subscriptionremoved', 'calendar', $sub->name);
2917 break;
2918 default:
2919 break;
2921 return '';
2925 * Delete subscription and all related events.
2927 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
2929 function calendar_delete_subscription($subscription) {
2930 global $DB;
2932 if (!is_object($subscription)) {
2933 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST);
2936 // Delete subscription and related events.
2937 $DB->delete_records('event', array('subscriptionid' => $subscription->id));
2938 $DB->delete_records('event_subscriptions', array('id' => $subscription->id));
2939 \cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id));
2941 // Trigger event, calendar subscription deleted.
2942 $eventparams = array('objectid' => $subscription->id,
2943 'context' => calendar_get_calendar_context($subscription),
2944 'other' => array(
2945 'eventtype' => $subscription->eventtype,
2948 switch ($subscription->eventtype) {
2949 case 'category':
2950 $eventparams['other']['categoryid'] = $subscription->categoryid;
2951 break;
2952 case 'course':
2953 $eventparams['other']['courseid'] = $subscription->courseid;
2954 break;
2955 case 'group':
2956 $eventparams['other']['courseid'] = $subscription->courseid;
2957 $eventparams['other']['groupid'] = $subscription->groupid;
2958 break;
2959 default:
2960 $eventparams['other']['courseid'] = $subscription->courseid;
2962 $event = \core\event\calendar_subscription_deleted::create($eventparams);
2963 $event->trigger();
2967 * From a URL, fetch the calendar and return an iCalendar object.
2969 * @param string $url The iCalendar URL
2970 * @return iCalendar The iCalendar object
2972 function calendar_get_icalendar($url) {
2973 global $CFG;
2975 require_once($CFG->libdir . '/filelib.php');
2977 $curl = new \curl();
2978 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
2979 $calendar = $curl->get($url);
2981 // Http code validation should actually be the job of curl class.
2982 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
2983 throw new \moodle_exception('errorinvalidicalurl', 'calendar');
2986 $ical = new \iCalendar();
2987 $ical->unserialize($calendar);
2989 return $ical;
2993 * Import events from an iCalendar object into a course calendar.
2995 * @param iCalendar $ical The iCalendar object.
2996 * @param int $courseid The course ID for the calendar.
2997 * @param int $subscriptionid The subscription ID.
2998 * @return string A log of the import progress, including errors.
3000 function calendar_import_icalendar_events($ical, $unused = null, $subscriptionid = null) {
3001 global $DB;
3003 $return = '';
3004 $eventcount = 0;
3005 $updatecount = 0;
3007 // Large calendars take a while...
3008 if (!CLI_SCRIPT) {
3009 \core_php_time_limit::raise(300);
3012 // Mark all events in a subscription with a zero timestamp.
3013 if (!empty($subscriptionid)) {
3014 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
3015 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3018 // Grab the timezone from the iCalendar file to be used later.
3019 if (isset($ical->properties['X-WR-TIMEZONE'][0]->value)) {
3020 $timezone = $ical->properties['X-WR-TIMEZONE'][0]->value;
3021 } else {
3022 $timezone = 'UTC';
3025 $return = '';
3026 foreach ($ical->components['VEVENT'] as $event) {
3027 $res = calendar_add_icalendar_event($event, null, $subscriptionid, $timezone);
3028 switch ($res) {
3029 case CALENDAR_IMPORT_EVENT_UPDATED:
3030 $updatecount++;
3031 break;
3032 case CALENDAR_IMPORT_EVENT_INSERTED:
3033 $eventcount++;
3034 break;
3035 case 0:
3036 $return .= '<p>' . get_string('erroraddingevent', 'calendar') . ': ';
3037 if (empty($event->properties['SUMMARY'])) {
3038 $return .= '(' . get_string('notitle', 'calendar') . ')';
3039 } else {
3040 $return .= $event->properties['SUMMARY'][0]->value;
3042 $return .= "</p>\n";
3043 break;
3047 $return .= "<p>" . get_string('eventsimported', 'calendar', $eventcount) . "</p> ";
3048 $return .= "<p>" . get_string('eventsupdated', 'calendar', $updatecount) . "</p>";
3050 // Delete remaining zero-marked events since they're not in remote calendar.
3051 if (!empty($subscriptionid)) {
3052 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3053 if (!empty($deletecount)) {
3054 $DB->delete_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3055 $return .= "<p> " . get_string('eventsdeleted', 'calendar') . ": {$deletecount} </p>\n";
3059 return $return;
3063 * Fetch a calendar subscription and update the events in the calendar.
3065 * @param int $subscriptionid The course ID for the calendar.
3066 * @return string A log of the import progress, including errors.
3068 function calendar_update_subscription_events($subscriptionid) {
3069 $sub = calendar_get_subscription($subscriptionid);
3071 // Don't update a file subscription.
3072 if (empty($sub->url)) {
3073 return 'File subscription not updated.';
3076 $ical = calendar_get_icalendar($sub->url);
3077 $return = calendar_import_icalendar_events($ical, null, $subscriptionid);
3078 $sub->lastupdated = time();
3080 calendar_update_subscription($sub);
3082 return $return;
3086 * Update a calendar subscription. Also updates the associated cache.
3088 * @param stdClass|array $subscription Subscription record.
3089 * @throws coding_exception If something goes wrong
3090 * @since Moodle 2.5
3092 function calendar_update_subscription($subscription) {
3093 global $DB;
3095 if (is_array($subscription)) {
3096 $subscription = (object)$subscription;
3098 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
3099 throw new \coding_exception('Cannot update a subscription without a valid id');
3102 $DB->update_record('event_subscriptions', $subscription);
3104 // Update cache.
3105 $cache = \cache::make('core', 'calendar_subscriptions');
3106 $cache->set($subscription->id, $subscription);
3108 // Trigger event, calendar subscription updated.
3109 $eventparams = array('userid' => $subscription->userid,
3110 'objectid' => $subscription->id,
3111 'context' => calendar_get_calendar_context($subscription),
3112 'other' => array(
3113 'eventtype' => $subscription->eventtype,
3116 switch ($subscription->eventtype) {
3117 case 'category':
3118 $eventparams['other']['categoryid'] = $subscription->categoryid;
3119 break;
3120 case 'course':
3121 $eventparams['other']['courseid'] = $subscription->courseid;
3122 break;
3123 case 'group':
3124 $eventparams['other']['courseid'] = $subscription->courseid;
3125 $eventparams['other']['groupid'] = $subscription->groupid;
3126 break;
3127 default:
3128 $eventparams['other']['courseid'] = $subscription->courseid;
3130 $event = \core\event\calendar_subscription_updated::create($eventparams);
3131 $event->trigger();
3135 * Checks to see if the user can edit a given subscription feed.
3137 * @param mixed $subscriptionorid Subscription object or id
3138 * @return bool true if current user can edit the subscription else false
3140 function calendar_can_edit_subscription($subscriptionorid) {
3141 if (is_array($subscriptionorid)) {
3142 $subscription = (object)$subscriptionorid;
3143 } else if (is_object($subscriptionorid)) {
3144 $subscription = $subscriptionorid;
3145 } else {
3146 $subscription = calendar_get_subscription($subscriptionorid);
3149 $allowed = new \stdClass;
3150 $courseid = $subscription->courseid;
3151 $categoryid = $subscription->categoryid;
3152 $groupid = $subscription->groupid;
3153 $category = null;
3155 if (!empty($categoryid)) {
3156 $category = \core_course_category::get($categoryid);
3158 calendar_get_allowed_types($allowed, $courseid, null, $category);
3159 switch ($subscription->eventtype) {
3160 case 'user':
3161 return $allowed->user;
3162 case 'course':
3163 if (isset($allowed->courses[$courseid])) {
3164 return $allowed->courses[$courseid];
3165 } else {
3166 return false;
3168 case 'category':
3169 if (isset($allowed->categories[$categoryid])) {
3170 return $allowed->categories[$categoryid];
3171 } else {
3172 return false;
3174 case 'site':
3175 return $allowed->site;
3176 case 'group':
3177 if (isset($allowed->groups[$groupid])) {
3178 return $allowed->groups[$groupid];
3179 } else {
3180 return false;
3182 default:
3183 return false;
3188 * Helper function to determine the context of a calendar subscription.
3189 * Subscriptions can be created in two contexts COURSE, or USER.
3191 * @param stdClass $subscription
3192 * @return context instance
3194 function calendar_get_calendar_context($subscription) {
3195 // Determine context based on calendar type.
3196 if ($subscription->eventtype === 'site') {
3197 $context = \context_course::instance(SITEID);
3198 } else if ($subscription->eventtype === 'group' || $subscription->eventtype === 'course') {
3199 $context = \context_course::instance($subscription->courseid);
3200 } else {
3201 $context = \context_user::instance($subscription->userid);
3203 return $context;
3207 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
3209 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3211 * @return array
3213 function core_calendar_user_preferences() {
3214 $preferences = [];
3215 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED, 'default' => '0',
3216 'choices' => array('0', CALENDAR_TF_12, CALENDAR_TF_24)
3218 $preferences['calendar_startwday'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3219 'choices' => array(0, 1, 2, 3, 4, 5, 6));
3220 $preferences['calendar_maxevents'] = array('type' => PARAM_INT, 'choices' => range(1, 20));
3221 $preferences['calendar_lookahead'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 365,
3222 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3223 $preferences['calendar_persistflt'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3224 'choices' => array(0, 1));
3225 return $preferences;
3229 * Get legacy calendar events
3231 * @param int $tstart Start time of time range for events
3232 * @param int $tend End time of time range for events
3233 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3234 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3235 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3236 * @param boolean $withduration whether only events starting within time range selected
3237 * or events in progress/already started selected as well
3238 * @param boolean $ignorehidden whether to select only visible events or all events
3239 * @param array $categories array of category ids and/or objects.
3240 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3242 function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses,
3243 $withduration = true, $ignorehidden = true, $categories = []) {
3244 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3245 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3246 // parameters, but with the new API method, only null and arrays are accepted.
3247 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3248 // If parameter is true, return null.
3249 if ($param === true) {
3250 return null;
3253 // If parameter is false, return an empty array.
3254 if ($param === false) {
3255 return [];
3258 // If the parameter is a scalar value, enclose it in an array.
3259 if (!is_array($param)) {
3260 return [$param];
3263 // No normalisation required.
3264 return $param;
3265 }, [$users, $groups, $courses, $categories]);
3267 // If a single user is provided, we can use that for capability checks.
3268 // Otherwise current logged in user is used - See MDL-58768.
3269 if (is_array($userparam) && count($userparam) == 1) {
3270 \core_calendar\local\event\container::set_requesting_user($userparam[0]);
3272 $mapper = \core_calendar\local\event\container::get_event_mapper();
3273 $events = \core_calendar\local\api::get_events(
3274 $tstart,
3275 $tend,
3276 null,
3277 null,
3278 null,
3279 null,
3281 null,
3282 $userparam,
3283 $groupparam,
3284 $courseparam,
3285 $categoryparam,
3286 $withduration,
3287 $ignorehidden
3290 return array_reduce($events, function($carry, $event) use ($mapper) {
3291 return $carry + [$event->get_id() => $mapper->from_event_to_stdclass($event)];
3292 }, []);
3297 * Get the calendar view output.
3299 * @param \calendar_information $calendar The calendar being represented
3300 * @param string $view The type of calendar to have displayed
3301 * @param bool $includenavigation Whether to include navigation
3302 * @param bool $skipevents Whether to load the events or not
3303 * @param int $lookahead Overwrites site and users's lookahead setting.
3304 * @return array[array, string]
3306 function calendar_get_view(\calendar_information $calendar, $view, $includenavigation = true, bool $skipevents = false,
3307 ?int $lookahead = null) {
3308 global $PAGE, $CFG;
3310 $renderer = $PAGE->get_renderer('core_calendar');
3311 $type = \core_calendar\type_factory::get_calendar_instance();
3313 // Calculate the bounds of the month.
3314 $calendardate = $type->timestamp_to_date_array($calendar->time);
3316 $date = new \DateTime('now', core_date::get_user_timezone_object(99));
3317 $eventlimit = 200;
3319 if ($view === 'day') {
3320 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday']);
3321 $date->setTimestamp($tstart);
3322 $date->modify('+1 day');
3323 } else if ($view === 'upcoming' || $view === 'upcoming_mini') {
3324 // Number of days in the future that will be used to fetch events.
3325 if (!$lookahead) {
3326 if (isset($CFG->calendar_lookahead)) {
3327 $defaultlookahead = intval($CFG->calendar_lookahead);
3328 } else {
3329 $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD;
3331 $lookahead = get_user_preferences('calendar_lookahead', $defaultlookahead);
3334 // Maximum number of events to be displayed on upcoming view.
3335 $defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS;
3336 if (isset($CFG->calendar_maxevents)) {
3337 $defaultmaxevents = intval($CFG->calendar_maxevents);
3339 $eventlimit = get_user_preferences('calendar_maxevents', $defaultmaxevents);
3341 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday'],
3342 $calendardate['hours']);
3343 $date->setTimestamp($tstart);
3344 $date->modify('+' . $lookahead . ' days');
3345 } else {
3346 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], 1);
3347 $monthdays = $type->get_num_days_in_month($calendardate['year'], $calendardate['mon']);
3348 $date->setTimestamp($tstart);
3349 $date->modify('+' . $monthdays . ' days');
3351 if ($view === 'mini' || $view === 'minithree') {
3352 $template = 'core_calendar/calendar_mini';
3353 } else {
3354 $template = 'core_calendar/calendar_month';
3358 // We need to extract 1 second to ensure that we don't get into the next day.
3359 $date->modify('-1 second');
3360 $tend = $date->getTimestamp();
3362 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3363 // If parameter is true, return null.
3364 if ($param === true) {
3365 return null;
3368 // If parameter is false, return an empty array.
3369 if ($param === false) {
3370 return [];
3373 // If the parameter is a scalar value, enclose it in an array.
3374 if (!is_array($param)) {
3375 return [$param];
3378 // No normalisation required.
3379 return $param;
3380 }, [$calendar->users, $calendar->groups, $calendar->courses, $calendar->categories]);
3382 if ($skipevents) {
3383 $events = [];
3384 } else {
3385 $events = \core_calendar\local\api::get_events(
3386 $tstart,
3387 $tend,
3388 null,
3389 null,
3390 null,
3391 null,
3392 $eventlimit,
3393 null,
3394 $userparam,
3395 $groupparam,
3396 $courseparam,
3397 $categoryparam,
3398 true,
3399 true,
3400 function ($event) {
3401 if ($proxy = $event->get_course_module()) {
3402 $cminfo = $proxy->get_proxied_instance();
3403 return $cminfo->uservisible;
3406 if ($proxy = $event->get_category()) {
3407 $category = $proxy->get_proxied_instance();
3409 return $category->is_uservisible();
3412 return true;
3417 $related = [
3418 'events' => $events,
3419 'cache' => new \core_calendar\external\events_related_objects_cache($events),
3420 'type' => $type,
3423 $data = [];
3424 if ($view == "month" || $view == "mini" || $view == "minithree") {
3425 $month = new \core_calendar\external\month_exporter($calendar, $type, $related);
3426 $month->set_includenavigation($includenavigation);
3427 $month->set_initialeventsloaded(!$skipevents);
3428 $month->set_showcoursefilter($view == "month");
3429 $data = $month->export($renderer);
3430 } else if ($view == "day") {
3431 $day = new \core_calendar\external\calendar_day_exporter($calendar, $related);
3432 $data = $day->export($renderer);
3433 $template = 'core_calendar/calendar_day';
3434 } else if ($view == "upcoming" || $view == "upcoming_mini") {
3435 $upcoming = new \core_calendar\external\calendar_upcoming_exporter($calendar, $related);
3436 $data = $upcoming->export($renderer);
3438 if ($view == "upcoming") {
3439 $template = 'core_calendar/calendar_upcoming';
3440 } else if ($view == "upcoming_mini") {
3441 $template = 'core_calendar/calendar_upcoming_mini';
3445 return [$data, $template];
3449 * Request and render event form fragment.
3451 * @param array $args The fragment arguments.
3452 * @return string The rendered mform fragment.
3454 function calendar_output_fragment_event_form($args) {
3455 global $CFG, $OUTPUT, $USER;
3456 require_once($CFG->libdir . '/grouplib.php');
3457 $html = '';
3458 $data = [];
3459 $eventid = isset($args['eventid']) ? clean_param($args['eventid'], PARAM_INT) : null;
3460 $starttime = isset($args['starttime']) ? clean_param($args['starttime'], PARAM_INT) : null;
3461 $courseid = (isset($args['courseid']) && $args['courseid'] != SITEID) ? clean_param($args['courseid'], PARAM_INT) : null;
3462 $categoryid = isset($args['categoryid']) ? clean_param($args['categoryid'], PARAM_INT) : null;
3463 $event = null;
3464 $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
3465 $context = \context_user::instance($USER->id);
3466 $editoroptions = \core_calendar\local\event\forms\create::build_editor_options($context);
3467 $formoptions = ['editoroptions' => $editoroptions, 'courseid' => $courseid];
3468 $draftitemid = 0;
3470 if ($hasformdata) {
3471 parse_str(clean_param($args['formdata'], PARAM_TEXT), $data);
3472 if (isset($data['description']['itemid'])) {
3473 $draftitemid = $data['description']['itemid'];
3477 if ($starttime) {
3478 $formoptions['starttime'] = $starttime;
3481 if (is_null($eventid)) {
3482 if (!empty($courseid)) {
3483 $groupcoursedata = groups_get_course_data($courseid);
3484 $formoptions['groups'] = [];
3485 foreach ($groupcoursedata->groups as $groupid => $groupdata) {
3486 $formoptions['groups'][$groupid] = $groupdata->name;
3489 $mform = new \core_calendar\local\event\forms\create(
3490 null,
3491 $formoptions,
3492 'post',
3494 null,
3495 true,
3496 $data
3499 // Let's check first which event types user can add.
3500 $eventtypes = calendar_get_allowed_event_types($courseid);
3502 // If the user is on course context and is allowed to add course events set the event type default to course.
3503 if ($courseid != SITEID && !empty($eventtypes['course'])) {
3504 $data['eventtype'] = 'course';
3505 $data['courseid'] = $courseid;
3506 $data['groupcourseid'] = $courseid;
3507 } else if (!empty($categoryid) && !empty($eventtypes['category'])) {
3508 $data['eventtype'] = 'category';
3509 $data['categoryid'] = $categoryid;
3510 } else if (!empty($groupcoursedata) && !empty($eventtypes['group'])) {
3511 $data['groupcourseid'] = $courseid;
3512 $data['groups'] = $groupcoursedata->groups;
3514 $mform->set_data($data);
3515 } else {
3516 $event = calendar_event::load($eventid);
3518 if (!calendar_edit_event_allowed($event)) {
3519 print_error('nopermissiontoupdatecalendar');
3522 $mapper = new \core_calendar\local\event\mappers\create_update_form_mapper();
3523 $eventdata = $mapper->from_legacy_event_to_data($event);
3524 $data = array_merge((array) $eventdata, $data);
3525 $event->count_repeats();
3526 $formoptions['event'] = $event;
3528 if (!empty($event->courseid)) {
3529 $groupcoursedata = groups_get_course_data($event->courseid);
3530 $formoptions['groups'] = [];
3531 foreach ($groupcoursedata->groups as $groupid => $groupdata) {
3532 $formoptions['groups'][$groupid] = $groupdata->name;
3536 $data['description']['text'] = file_prepare_draft_area(
3537 $draftitemid,
3538 $event->context->id,
3539 'calendar',
3540 'event_description',
3541 $event->id,
3542 null,
3543 $data['description']['text']
3545 $data['description']['itemid'] = $draftitemid;
3547 $mform = new \core_calendar\local\event\forms\update(
3548 null,
3549 $formoptions,
3550 'post',
3552 null,
3553 true,
3554 $data
3556 $mform->set_data($data);
3558 // Check to see if this event is part of a subscription or import.
3559 // If so display a warning on edit.
3560 if (isset($event->subscriptionid) && ($event->subscriptionid != null)) {
3561 $renderable = new \core\output\notification(
3562 get_string('eventsubscriptioneditwarning', 'calendar'),
3563 \core\output\notification::NOTIFY_INFO
3566 $html .= $OUTPUT->render($renderable);
3570 if ($hasformdata) {
3571 $mform->is_validated();
3574 $html .= $mform->render();
3575 return $html;
3579 * Calculate the timestamp from the supplied Gregorian Year, Month, and Day.
3581 * @param int $d The day
3582 * @param int $m The month
3583 * @param int $y The year
3584 * @param int $time The timestamp to use instead of a separate y/m/d.
3585 * @return int The timestamp
3587 function calendar_get_timestamp($d, $m, $y, $time = 0) {
3588 // If a day, month and year were passed then convert it to a timestamp. If these were passed
3589 // then we can assume the day, month and year are passed as Gregorian, as no where in core
3590 // should we be passing these values rather than the time.
3591 if (!empty($d) && !empty($m) && !empty($y)) {
3592 if (checkdate($m, $d, $y)) {
3593 $time = make_timestamp($y, $m, $d);
3594 } else {
3595 $time = time();
3597 } else if (empty($time)) {
3598 $time = time();
3601 return $time;
3605 * Get the calendar footer options.
3607 * @param calendar_information $calendar The calendar information object.
3608 * @return array The data for template and template name.
3610 function calendar_get_footer_options($calendar) {
3611 global $CFG, $USER, $DB, $PAGE;
3613 // Generate hash for iCal link.
3614 $rawhash = $USER->id . $DB->get_field('user', 'password', ['id' => $USER->id]) . $CFG->calendar_exportsalt;
3615 $authtoken = sha1($rawhash);
3617 $renderer = $PAGE->get_renderer('core_calendar');
3618 $footer = new \core_calendar\external\footer_options_exporter($calendar, $USER->id, $authtoken);
3619 $data = $footer->export($renderer);
3620 $template = 'core_calendar/footer_options';
3622 return [$data, $template];
3626 * Get the list of potential calendar filter types as a type => name
3627 * combination.
3629 * @return array
3631 function calendar_get_filter_types() {
3632 $types = [
3633 'site',
3634 'category',
3635 'course',
3636 'group',
3637 'user',
3640 return array_map(function($type) {
3641 return [
3642 'eventtype' => $type,
3643 'name' => get_string("eventtype{$type}", "calendar"),
3645 }, $types);
3649 * Check whether the specified event type is valid.
3651 * @param string $type
3652 * @return bool
3654 function calendar_is_valid_eventtype($type) {
3655 $validtypes = [
3656 'user',
3657 'group',
3658 'course',
3659 'category',
3660 'site',
3662 return in_array($type, $validtypes);
3666 * Get event types the user can create event based on categories, courses and groups
3667 * the logged in user belongs to.
3669 * @param int|null $courseid The course id.
3670 * @return array The array of allowed types.
3672 function calendar_get_allowed_event_types(int $courseid = null) {
3673 global $DB, $CFG, $USER;
3675 $types = [
3676 'user' => false,
3677 'site' => false,
3678 'course' => false,
3679 'group' => false,
3680 'category' => false
3683 if (!empty($courseid) && $courseid != SITEID) {
3684 $context = \context_course::instance($courseid);
3685 $groups = groups_get_all_groups($courseid);
3687 $types['user'] = has_capability('moodle/calendar:manageownentries', $context);
3689 if (has_capability('moodle/calendar:manageentries', $context) || !empty($CFG->calendar_adminseesall)) {
3690 $types['course'] = true;
3692 $types['group'] = (!empty($groups) && has_capability('moodle/site:accessallgroups', $context))
3693 || array_filter($groups, function($group) use ($USER) {
3694 return groups_is_member($group->id);
3696 } else if (has_capability('moodle/calendar:managegroupentries', $context)) {
3697 $types['group'] = (!empty($groups) && has_capability('moodle/site:accessallgroups', $context))
3698 || array_filter($groups, function($group) use ($USER) {
3699 return groups_is_member($group->id);
3704 if (has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID))) {
3705 $types['site'] = true;
3708 if (has_capability('moodle/calendar:manageownentries', \context_system::instance())) {
3709 $types['user'] = true;
3711 if (core_course_category::has_manage_capability_on_any()) {
3712 $types['category'] = true;
3715 // We still don't know if the user can create group and course events, so iterate over the courses to find out
3716 // if the user has capabilities in one of the courses.
3717 if ($types['course'] == false || $types['group'] == false) {
3718 if ($CFG->calendar_adminseesall && has_capability('moodle/calendar:manageentries', context_system::instance())) {
3719 $sql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3720 FROM {course} c
3721 JOIN {context} ctx ON ctx.contextlevel = ? AND ctx.instanceid = c.id
3722 WHERE c.id IN (
3723 SELECT DISTINCT courseid FROM {groups}
3725 $courseswithgroups = $DB->get_recordset_sql($sql, [CONTEXT_COURSE]);
3726 foreach ($courseswithgroups as $course) {
3727 context_helper::preload_from_record($course);
3728 $context = context_course::instance($course->id);
3730 if (has_capability('moodle/calendar:manageentries', $context)) {
3731 if (has_any_capability(['moodle/site:accessallgroups', 'moodle/calendar:managegroupentries'], $context)) {
3732 // The user can manage group entries or access any group.
3733 $types['group'] = true;
3734 $types['course'] = true;
3735 break;
3739 $courseswithgroups->close();
3741 if (false === $types['course']) {
3742 // Course is still not confirmed. There may have been no courses with a group in them.
3743 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
3744 $sql = "SELECT
3745 c.id, c.visible, {$ctxfields}
3746 FROM {course} c
3747 JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
3748 $params = [
3749 'contextlevel' => CONTEXT_COURSE,
3751 $courses = $DB->get_recordset_sql($sql, $params);
3752 foreach ($courses as $course) {
3753 context_helper::preload_from_record($course);
3754 $context = context_course::instance($course->id);
3755 if (has_capability('moodle/calendar:manageentries', $context)) {
3756 $types['course'] = true;
3757 break;
3760 $courses->close();
3763 } else {
3764 $courses = calendar_get_default_courses(null, 'id');
3765 if (empty($courses)) {
3766 return $types;
3769 $courseids = array_map(function($c) {
3770 return $c->id;
3771 }, $courses);
3773 // Check whether the user has access to create events within courses which have groups.
3774 list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
3775 $sql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3776 FROM {course} c
3777 JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3778 WHERE c.id $insql
3779 AND c.id IN (SELECT DISTINCT courseid FROM {groups})";
3780 $params['contextlevel'] = CONTEXT_COURSE;
3781 $courseswithgroups = $DB->get_recordset_sql($sql, $params);
3782 foreach ($courseswithgroups as $coursewithgroup) {
3783 context_helper::preload_from_record($coursewithgroup);
3784 $context = context_course::instance($coursewithgroup->id);
3786 if (has_capability('moodle/calendar:manageentries', $context)) {
3787 // The user has access to manage calendar entries for the whole course.
3788 // This includes groups if they have the accessallgroups capability.
3789 $types['course'] = true;
3790 if (has_capability('moodle/site:accessallgroups', $context)) {
3791 // The user also has access to all groups so they can add calendar entries to any group.
3792 // The manageentries capability overrides the managegroupentries capability.
3793 $types['group'] = true;
3794 break;
3797 if (empty($types['group']) && has_capability('moodle/calendar:managegroupentries', $context)) {
3798 // The user has the managegroupentries capability.
3799 // If they have access to _any_ group, then they can create calendar entries within that group.
3800 $types['group'] = !empty(groups_get_all_groups($coursewithgroup->id, $USER->id));
3804 // Okay, course and group event types are allowed, no need to keep the loop iteration.
3805 if ($types['course'] == true && $types['group'] == true) {
3806 break;
3809 $courseswithgroups->close();
3811 if (false === $types['course']) {
3812 list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
3813 $contextsql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3814 FROM {course} c
3815 JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3816 WHERE c.id $insql";
3817 $params['contextlevel'] = CONTEXT_COURSE;
3818 $contextrecords = $DB->get_recordset_sql($contextsql, $params);
3819 foreach ($contextrecords as $course) {
3820 context_helper::preload_from_record($course);
3821 $coursecontext = context_course::instance($course->id);
3822 if (has_capability('moodle/calendar:manageentries', $coursecontext)
3823 && ($courseid == $course->id || empty($courseid))) {
3824 $types['course'] = true;
3825 break;
3828 $contextrecords->close();
3834 return $types;