Merge branch 'MDL-61715-34' of https://github.com/lethevinh/moodle into MOODLE_34_STABLE
[moodle.git] / calendar / lib.php
blob96c25a0e6d8c6cb3f01d6574740dd0127398baa9
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 require_once($CFG->libdir . '/coursecatlib.php');
32 /**
33 * These are read by the administration component to provide default values
36 /**
37 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
39 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
41 /**
42 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
44 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
46 /**
47 * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
49 define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
51 // This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
52 // Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
54 /**
55 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
57 define('CALENDAR_DEFAULT_WEEKEND', 65);
59 /**
60 * CALENDAR_URL - path to calendar's folder
62 define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
64 /**
65 * CALENDAR_TF_24 - Calendar time in 24 hours format
67 define('CALENDAR_TF_24', '%H:%M');
69 /**
70 * CALENDAR_TF_12 - Calendar time in 12 hours format
72 define('CALENDAR_TF_12', '%I:%M %p');
74 /**
75 * CALENDAR_EVENT_GLOBAL - Global calendar event types
77 define('CALENDAR_EVENT_GLOBAL', 1);
79 /**
80 * CALENDAR_EVENT_COURSE - Course calendar event types
82 define('CALENDAR_EVENT_COURSE', 2);
84 /**
85 * CALENDAR_EVENT_GROUP - group calendar event types
87 define('CALENDAR_EVENT_GROUP', 4);
89 /**
90 * CALENDAR_EVENT_USER - user calendar event types
92 define('CALENDAR_EVENT_USER', 8);
94 /**
95 * CALENDAR_EVENT_COURSECAT - Course category calendar event types
97 define('CALENDAR_EVENT_COURSECAT', 16);
99 /**
100 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
102 define('CALENDAR_IMPORT_FROM_FILE', 0);
105 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
107 define('CALENDAR_IMPORT_FROM_URL', 1);
110 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
112 define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
115 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
117 define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
120 * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
122 define('CALENDAR_SUBSCRIPTION_UPDATE', 1);
125 * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
127 define('CALENDAR_SUBSCRIPTION_REMOVE', 2);
130 * CALENDAR_EVENT_USER_OVERRIDE_PRIORITY - Constant for the user override priority.
132 define('CALENDAR_EVENT_USER_OVERRIDE_PRIORITY', 0);
135 * CALENDAR_EVENT_TYPE_STANDARD - Standard events.
137 define('CALENDAR_EVENT_TYPE_STANDARD', 0);
140 * CALENDAR_EVENT_TYPE_ACTION - Action events.
142 define('CALENDAR_EVENT_TYPE_ACTION', 1);
145 * Manage calendar events.
147 * This class provides the required functionality in order to manage calendar events.
148 * It was introduced as part of Moodle 2.0 and was created in order to provide a
149 * better framework for dealing with calendar events in particular regard to file
150 * handling through the new file API.
152 * @package core_calendar
153 * @category calendar
154 * @copyright 2009 Sam Hemelryk
155 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
157 * @property int $id The id within the event table
158 * @property string $name The name of the event
159 * @property string $description The description of the event
160 * @property int $format The format of the description FORMAT_?
161 * @property int $courseid The course the event is associated with (0 if none)
162 * @property int $groupid The group the event is associated with (0 if none)
163 * @property int $userid The user the event is associated with (0 if none)
164 * @property int $repeatid If this is a repeated event this will be set to the
165 * id of the original
166 * @property string $modulename If added by a module this will be the module name
167 * @property int $instance If added by a module this will be the module instance
168 * @property string $eventtype The event type
169 * @property int $timestart The start time as a timestamp
170 * @property int $timeduration The duration of the event in seconds
171 * @property int $visible 1 if the event is visible
172 * @property int $uuid ?
173 * @property int $sequence ?
174 * @property int $timemodified The time last modified as a timestamp
176 class calendar_event {
178 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
179 protected $properties = null;
181 /** @var string The converted event discription with file paths resolved.
182 * This gets populated when someone requests description for the first time */
183 protected $_description = null;
185 /** @var array The options to use with this description editor */
186 protected $editoroptions = array(
187 'subdirs' => false,
188 'forcehttps' => false,
189 'maxfiles' => -1,
190 'maxbytes' => null,
191 'trusttext' => false);
193 /** @var object The context to use with the description editor */
194 protected $editorcontext = null;
197 * Instantiates a new event and optionally populates its properties with the data provided.
199 * @param \stdClass $data Optional. An object containing the properties to for
200 * an event
202 public function __construct($data = null) {
203 global $CFG, $USER;
205 // First convert to object if it is not already (should either be object or assoc array).
206 if (!is_object($data)) {
207 $data = (object) $data;
210 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
212 $data->eventrepeats = 0;
214 if (empty($data->id)) {
215 $data->id = null;
218 if (!empty($data->subscriptionid)) {
219 $data->subscription = calendar_get_subscription($data->subscriptionid);
222 // Default to a user event.
223 if (empty($data->eventtype)) {
224 $data->eventtype = 'user';
227 // Default to the current user.
228 if (empty($data->userid)) {
229 $data->userid = $USER->id;
232 if (!empty($data->timeduration) && is_array($data->timeduration)) {
233 $data->timeduration = make_timestamp(
234 $data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'],
235 $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
238 if (!empty($data->description) && is_array($data->description)) {
239 $data->format = $data->description['format'];
240 $data->description = $data->description['text'];
241 } else if (empty($data->description)) {
242 $data->description = '';
243 $data->format = editors_get_preferred_format();
246 // Ensure form is defaulted correctly.
247 if (empty($data->format)) {
248 $data->format = editors_get_preferred_format();
251 $this->properties = $data;
253 if (empty($data->context)) {
254 $this->properties->context = $this->calculate_context();
259 * Magic set method.
261 * Attempts to call a set_$key method if one exists otherwise falls back
262 * to simply set the property.
264 * @param string $key property name
265 * @param mixed $value value of the property
267 public function __set($key, $value) {
268 if (method_exists($this, 'set_'.$key)) {
269 $this->{'set_'.$key}($value);
271 $this->properties->{$key} = $value;
275 * Magic get method.
277 * Attempts to call a get_$key method to return the property and ralls over
278 * to return the raw property.
280 * @param string $key property name
281 * @return mixed property value
282 * @throws \coding_exception
284 public function __get($key) {
285 if (method_exists($this, 'get_'.$key)) {
286 return $this->{'get_'.$key}();
288 if (!property_exists($this->properties, $key)) {
289 throw new \coding_exception('Undefined property requested');
291 return $this->properties->{$key};
295 * Magic isset method.
297 * PHP needs an isset magic method if you use the get magic method and
298 * still want empty calls to work.
300 * @param string $key $key property name
301 * @return bool|mixed property value, false if property is not exist
303 public function __isset($key) {
304 return !empty($this->properties->{$key});
308 * Calculate the context value needed for an event.
310 * Event's type can be determine by the available value store in $data
311 * It is important to check for the existence of course/courseid to determine
312 * the course event.
313 * Default value is set to CONTEXT_USER
315 * @return \stdClass The context object.
317 protected function calculate_context() {
318 global $USER, $DB;
320 $context = null;
321 if (isset($this->properties->categoryid) && $this->properties->categoryid > 0) {
322 $context = \context_coursecat::instance($this->properties->categoryid);
323 } else if (isset($this->properties->courseid) && $this->properties->courseid > 0) {
324 $context = \context_course::instance($this->properties->courseid);
325 } else if (isset($this->properties->course) && $this->properties->course > 0) {
326 $context = \context_course::instance($this->properties->course);
327 } else if (isset($this->properties->groupid) && $this->properties->groupid > 0) {
328 $group = $DB->get_record('groups', array('id' => $this->properties->groupid));
329 $context = \context_course::instance($group->courseid);
330 } else if (isset($this->properties->userid) && $this->properties->userid > 0
331 && $this->properties->userid == $USER->id) {
332 $context = \context_user::instance($this->properties->userid);
333 } else if (isset($this->properties->userid) && $this->properties->userid > 0
334 && $this->properties->userid != $USER->id &&
335 isset($this->properties->instance) && $this->properties->instance > 0) {
336 $cm = get_coursemodule_from_instance($this->properties->modulename, $this->properties->instance, 0,
337 false, MUST_EXIST);
338 $context = \context_course::instance($cm->course);
339 } else {
340 $context = \context_user::instance($this->properties->userid);
343 return $context;
347 * Returns an array of editoroptions for this event.
349 * @return array event editor options
351 protected function get_editoroptions() {
352 return $this->editoroptions;
356 * Returns an event description: Called by __get
357 * Please use $blah = $event->description;
359 * @return string event description
361 protected function get_description() {
362 global $CFG;
364 require_once($CFG->libdir . '/filelib.php');
366 if ($this->_description === null) {
367 // Check if we have already resolved the context for this event.
368 if ($this->editorcontext === null) {
369 // Switch on the event type to decide upon the appropriate context to use for this event.
370 $this->editorcontext = $this->properties->context;
371 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
372 return clean_text($this->properties->description, $this->properties->format);
376 // Work out the item id for the editor, if this is a repeated event
377 // then the files will be associated with the original.
378 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
379 $itemid = $this->properties->repeatid;
380 } else {
381 $itemid = $this->properties->id;
384 // Convert file paths in the description so that things display correctly.
385 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php',
386 $this->editorcontext->id, 'calendar', 'event_description', $itemid);
387 // Clean the text so no nasties get through.
388 $this->_description = clean_text($this->_description, $this->properties->format);
391 // Finally return the description.
392 return $this->_description;
396 * Return the number of repeat events there are in this events series.
398 * @return int number of event repeated
400 public function count_repeats() {
401 global $DB;
402 if (!empty($this->properties->repeatid)) {
403 $this->properties->eventrepeats = $DB->count_records('event',
404 array('repeatid' => $this->properties->repeatid));
405 // We don't want to count ourselves.
406 $this->properties->eventrepeats--;
408 return $this->properties->eventrepeats;
412 * Update or create an event within the database
414 * Pass in a object containing the event properties and this function will
415 * insert it into the database and deal with any associated files
417 * @see self::create()
418 * @see self::update()
420 * @param \stdClass $data object of event
421 * @param bool $checkcapability if moodle should check calendar managing capability or not
422 * @return bool event updated
424 public function update($data, $checkcapability=true) {
425 global $DB, $USER;
427 foreach ($data as $key => $value) {
428 $this->properties->$key = $value;
431 $this->properties->timemodified = time();
432 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
434 // Prepare event data.
435 $eventargs = array(
436 'context' => $this->properties->context,
437 'objectid' => $this->properties->id,
438 'other' => array(
439 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
440 'timestart' => $this->properties->timestart,
441 'name' => $this->properties->name
445 if (empty($this->properties->id) || $this->properties->id < 1) {
446 if ($checkcapability) {
447 if (!calendar_add_event_allowed($this->properties)) {
448 print_error('nopermissiontoupdatecalendar');
452 if ($usingeditor) {
453 switch ($this->properties->eventtype) {
454 case 'user':
455 $this->properties->courseid = 0;
456 $this->properties->course = 0;
457 $this->properties->groupid = 0;
458 $this->properties->userid = $USER->id;
459 break;
460 case 'site':
461 $this->properties->courseid = SITEID;
462 $this->properties->course = SITEID;
463 $this->properties->groupid = 0;
464 $this->properties->userid = $USER->id;
465 break;
466 case 'course':
467 $this->properties->groupid = 0;
468 $this->properties->userid = $USER->id;
469 break;
470 case 'category':
471 $this->properties->groupid = 0;
472 $this->properties->category = 0;
473 $this->properties->userid = $USER->id;
474 break;
475 case 'group':
476 $this->properties->userid = $USER->id;
477 break;
478 default:
479 // We should NEVER get here, but just incase we do lets fail gracefully.
480 $usingeditor = false;
481 break;
484 // If we are actually using the editor, we recalculate the context because some default values
485 // were set when calculate_context() was called from the constructor.
486 if ($usingeditor) {
487 $this->properties->context = $this->calculate_context();
488 $this->editorcontext = $this->properties->context;
491 $editor = $this->properties->description;
492 $this->properties->format = $this->properties->description['format'];
493 $this->properties->description = $this->properties->description['text'];
496 // Insert the event into the database.
497 $this->properties->id = $DB->insert_record('event', $this->properties);
499 if ($usingeditor) {
500 $this->properties->description = file_save_draft_area_files(
501 $editor['itemid'],
502 $this->editorcontext->id,
503 'calendar',
504 'event_description',
505 $this->properties->id,
506 $this->editoroptions,
507 $editor['text'],
508 $this->editoroptions['forcehttps']);
509 $DB->set_field('event', 'description', $this->properties->description,
510 array('id' => $this->properties->id));
513 // Log the event entry.
514 $eventargs['objectid'] = $this->properties->id;
515 $eventargs['context'] = $this->properties->context;
516 $event = \core\event\calendar_event_created::create($eventargs);
517 $event->trigger();
519 $repeatedids = array();
521 if (!empty($this->properties->repeat)) {
522 $this->properties->repeatid = $this->properties->id;
523 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id' => $this->properties->id));
525 $eventcopy = clone($this->properties);
526 unset($eventcopy->id);
528 $timestart = new \DateTime('@' . $eventcopy->timestart);
529 $timestart->setTimezone(\core_date::get_user_timezone_object());
531 for ($i = 1; $i < $eventcopy->repeats; $i++) {
533 $timestart->add(new \DateInterval('P7D'));
534 $eventcopy->timestart = $timestart->getTimestamp();
536 // Get the event id for the log record.
537 $eventcopyid = $DB->insert_record('event', $eventcopy);
539 // If the context has been set delete all associated files.
540 if ($usingeditor) {
541 $fs = get_file_storage();
542 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description',
543 $this->properties->id);
544 foreach ($files as $file) {
545 $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
549 $repeatedids[] = $eventcopyid;
551 // Trigger an event.
552 $eventargs['objectid'] = $eventcopyid;
553 $eventargs['other']['timestart'] = $eventcopy->timestart;
554 $event = \core\event\calendar_event_created::create($eventargs);
555 $event->trigger();
559 return true;
560 } else {
562 if ($checkcapability) {
563 if (!calendar_edit_event_allowed($this->properties)) {
564 print_error('nopermissiontoupdatecalendar');
568 if ($usingeditor) {
569 if ($this->editorcontext !== null) {
570 $this->properties->description = file_save_draft_area_files(
571 $this->properties->description['itemid'],
572 $this->editorcontext->id,
573 'calendar',
574 'event_description',
575 $this->properties->id,
576 $this->editoroptions,
577 $this->properties->description['text'],
578 $this->editoroptions['forcehttps']);
579 } else {
580 $this->properties->format = $this->properties->description['format'];
581 $this->properties->description = $this->properties->description['text'];
585 $event = $DB->get_record('event', array('id' => $this->properties->id));
587 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
589 if ($updaterepeated) {
590 // Update all.
591 if ($this->properties->timestart != $event->timestart) {
592 $timestartoffset = $this->properties->timestart - $event->timestart;
593 $sql = "UPDATE {event}
594 SET name = ?,
595 description = ?,
596 timestart = timestart + ?,
597 timeduration = ?,
598 timemodified = ?,
599 groupid = ?,
600 courseid = ?
601 WHERE repeatid = ?";
602 // Note: Group and course id may not be set. If not, keep their current values.
603 $params = [
604 $this->properties->name,
605 $this->properties->description,
606 $timestartoffset,
607 $this->properties->timeduration,
608 time(),
609 isset($this->properties->groupid) ? $this->properties->groupid : $event->groupid,
610 isset($this->properties->courseid) ? $this->properties->courseid : $event->courseid,
611 $event->repeatid
613 } else {
614 $sql = "UPDATE {event}
615 SET name = ?,
616 description = ?,
617 timeduration = ?,
618 timemodified = ?,
619 groupid = ?,
620 courseid = ?
621 WHERE repeatid = ?";
622 // Note: Group and course id may not be set. If not, keep their current values.
623 $params = [
624 $this->properties->name,
625 $this->properties->description,
626 $this->properties->timeduration,
627 time(),
628 isset($this->properties->groupid) ? $this->properties->groupid : $event->groupid,
629 isset($this->properties->courseid) ? $this->properties->courseid : $event->courseid,
630 $event->repeatid
633 $DB->execute($sql, $params);
635 // Trigger an update event for each of the calendar event.
636 $events = $DB->get_records('event', array('repeatid' => $event->repeatid), '', '*');
637 foreach ($events as $calendarevent) {
638 $eventargs['objectid'] = $calendarevent->id;
639 $eventargs['other']['timestart'] = $calendarevent->timestart;
640 $event = \core\event\calendar_event_updated::create($eventargs);
641 $event->add_record_snapshot('event', $calendarevent);
642 $event->trigger();
644 } else {
645 $DB->update_record('event', $this->properties);
646 $event = self::load($this->properties->id);
647 $this->properties = $event->properties();
649 // Trigger an update event.
650 $event = \core\event\calendar_event_updated::create($eventargs);
651 $event->add_record_snapshot('event', $this->properties);
652 $event->trigger();
655 return true;
660 * Deletes an event and if selected an repeated events in the same series
662 * This function deletes an event, any associated events if $deleterepeated=true,
663 * and cleans up any files associated with the events.
665 * @see self::delete()
667 * @param bool $deleterepeated delete event repeatedly
668 * @return bool succession of deleting event
670 public function delete($deleterepeated = false) {
671 global $DB;
673 // If $this->properties->id is not set then something is wrong.
674 if (empty($this->properties->id)) {
675 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
676 return false;
678 $calevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
679 // Delete the event.
680 $DB->delete_records('event', array('id' => $this->properties->id));
682 // Trigger an event for the delete action.
683 $eventargs = array(
684 'context' => $this->properties->context,
685 'objectid' => $this->properties->id,
686 'other' => array(
687 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
688 'timestart' => $this->properties->timestart,
689 'name' => $this->properties->name
691 $event = \core\event\calendar_event_deleted::create($eventargs);
692 $event->add_record_snapshot('event', $calevent);
693 $event->trigger();
695 // If we are deleting parent of a repeated event series, promote the next event in the series as parent.
696 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
697 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC",
698 array($this->properties->id), IGNORE_MULTIPLE);
699 if (!empty($newparent)) {
700 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?",
701 array($newparent, $this->properties->id));
702 // Get all records where the repeatid is the same as the event being removed.
703 $events = $DB->get_records('event', array('repeatid' => $newparent));
704 // For each of the returned events trigger an update event.
705 foreach ($events as $calendarevent) {
706 // Trigger an event for the update.
707 $eventargs['objectid'] = $calendarevent->id;
708 $eventargs['other']['timestart'] = $calendarevent->timestart;
709 $event = \core\event\calendar_event_updated::create($eventargs);
710 $event->add_record_snapshot('event', $calendarevent);
711 $event->trigger();
716 // If the editor context hasn't already been set then set it now.
717 if ($this->editorcontext === null) {
718 $this->editorcontext = $this->properties->context;
721 // If the context has been set delete all associated files.
722 if ($this->editorcontext !== null) {
723 $fs = get_file_storage();
724 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
725 foreach ($files as $file) {
726 $file->delete();
730 // If we need to delete repeated events then we will fetch them all and delete one by one.
731 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
732 // Get all records where the repeatid is the same as the event being removed.
733 $events = $DB->get_records('event', array('repeatid' => $this->properties->repeatid));
734 // For each of the returned events populate an event object and call delete.
735 // make sure the arg passed is false as we are already deleting all repeats.
736 foreach ($events as $event) {
737 $event = new calendar_event($event);
738 $event->delete(false);
742 return true;
746 * Fetch all event properties.
748 * This function returns all of the events properties as an object and optionally
749 * can prepare an editor for the description field at the same time. This is
750 * designed to work when the properties are going to be used to set the default
751 * values of a moodle forms form.
753 * @param bool $prepareeditor If set to true a editor is prepared for use with
754 * the mforms editor element. (for description)
755 * @return \stdClass Object containing event properties
757 public function properties($prepareeditor = false) {
758 global $DB;
760 // First take a copy of the properties. We don't want to actually change the
761 // properties or we'd forever be converting back and forwards between an
762 // editor formatted description and not.
763 $properties = clone($this->properties);
764 // Clean the description here.
765 $properties->description = clean_text($properties->description, $properties->format);
767 // If set to true we need to prepare the properties for use with an editor
768 // and prepare the file area.
769 if ($prepareeditor) {
771 // We may or may not have a property id. If we do then we need to work
772 // out the context so we can copy the existing files to the draft area.
773 if (!empty($properties->id)) {
775 if ($properties->eventtype === 'site') {
776 // Site context.
777 $this->editorcontext = $this->properties->context;
778 } else if ($properties->eventtype === 'user') {
779 // User context.
780 $this->editorcontext = $this->properties->context;
781 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
782 // First check the course is valid.
783 $course = $DB->get_record('course', array('id' => $properties->courseid));
784 if (!$course) {
785 print_error('invalidcourse');
787 // Course context.
788 $this->editorcontext = $this->properties->context;
789 // We have a course and are within the course context so we had
790 // better use the courses max bytes value.
791 $this->editoroptions['maxbytes'] = $course->maxbytes;
792 } else if ($properties->eventtype === 'category') {
793 // First check the course is valid.
794 \coursecat::get($properties->categoryid, MUST_EXIST, true);
795 // Course context.
796 $this->editorcontext = $this->properties->context;
797 } else {
798 // If we get here we have a custom event type as used by some
799 // modules. In this case the event will have been added by
800 // code and we won't need the editor.
801 $this->editoroptions['maxbytes'] = 0;
802 $this->editoroptions['maxfiles'] = 0;
805 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
806 $contextid = false;
807 } else {
808 // Get the context id that is what we really want.
809 $contextid = $this->editorcontext->id;
811 } else {
813 // If we get here then this is a new event in which case we don't need a
814 // context as there is no existing files to copy to the draft area.
815 $contextid = null;
818 // If the contextid === false we don't support files so no preparing
819 // a draft area.
820 if ($contextid !== false) {
821 // Just encase it has already been submitted.
822 $draftiddescription = file_get_submitted_draft_itemid('description');
823 // Prepare the draft area, this copies existing files to the draft area as well.
824 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar',
825 'event_description', $properties->id, $this->editoroptions, $properties->description);
826 } else {
827 $draftiddescription = 0;
830 // Structure the description field as the editor requires.
831 $properties->description = array('text' => $properties->description, 'format' => $properties->format,
832 'itemid' => $draftiddescription);
835 // Finally return the properties.
836 return $properties;
840 * Toggles the visibility of an event
842 * @param null|bool $force If it is left null the events visibility is flipped,
843 * If it is false the event is made hidden, if it is true it
844 * is made visible.
845 * @return bool if event is successfully updated, toggle will be visible
847 public function toggle_visibility($force = null) {
848 global $DB;
850 // Set visible to the default if it is not already set.
851 if (empty($this->properties->visible)) {
852 $this->properties->visible = 1;
855 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
856 // Make this event visible.
857 $this->properties->visible = 1;
858 } else {
859 // Make this event hidden.
860 $this->properties->visible = 0;
863 // Update the database to reflect this change.
864 $success = $DB->set_field('event', 'visible', $this->properties->visible, array('id' => $this->properties->id));
865 $calendarevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
867 // Prepare event data.
868 $eventargs = array(
869 'context' => $this->properties->context,
870 'objectid' => $this->properties->id,
871 'other' => array(
872 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
873 'timestart' => $this->properties->timestart,
874 'name' => $this->properties->name
877 $event = \core\event\calendar_event_updated::create($eventargs);
878 $event->add_record_snapshot('event', $calendarevent);
879 $event->trigger();
881 return $success;
885 * Returns an event object when provided with an event id.
887 * This function makes use of MUST_EXIST, if the event id passed in is invalid
888 * it will result in an exception being thrown.
890 * @param int|object $param event object or event id
891 * @return calendar_event
893 public static function load($param) {
894 global $DB;
895 if (is_object($param)) {
896 $event = new calendar_event($param);
897 } else {
898 $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST);
899 $event = new calendar_event($event);
901 return $event;
905 * Creates a new event and returns an event object
907 * @param \stdClass|array $properties An object containing event properties
908 * @param bool $checkcapability Check caps or not
909 * @throws \coding_exception
911 * @return calendar_event|bool The event object or false if it failed
913 public static function create($properties, $checkcapability = true) {
914 if (is_array($properties)) {
915 $properties = (object)$properties;
917 if (!is_object($properties)) {
918 throw new \coding_exception('When creating an event properties should be either an object or an assoc array');
920 $event = new calendar_event($properties);
921 if ($event->update($properties, $checkcapability)) {
922 return $event;
923 } else {
924 return false;
929 * Format the text using the external API.
931 * This function should we used when text formatting is required in external functions.
933 * @return array an array containing the text formatted and the text format
935 public function format_external_text() {
937 if ($this->editorcontext === null) {
938 // Switch on the event type to decide upon the appropriate context to use for this event.
939 $this->editorcontext = $this->properties->context;
941 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
942 // We don't have a context here, do a normal format_text.
943 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id);
947 // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
948 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
949 $itemid = $this->properties->repeatid;
950 } else {
951 $itemid = $this->properties->id;
954 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id,
955 'calendar', 'event_description', $itemid);
960 * Calendar information class
962 * This class is used simply to organise the information pertaining to a calendar
963 * and is used primarily to make information easily available.
965 * @package core_calendar
966 * @category calendar
967 * @copyright 2010 Sam Hemelryk
968 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
970 class calendar_information {
973 * @var int The timestamp
975 * Rather than setting the day, month and year we will set a timestamp which will be able
976 * to be used by multiple calendars.
978 public $time;
980 /** @var int A course id */
981 public $courseid = null;
983 /** @var array An array of categories */
984 public $categories = array();
986 /** @var int The current category */
987 public $categoryid = null;
989 /** @var array An array of courses */
990 public $courses = array();
992 /** @var array An array of groups */
993 public $groups = array();
995 /** @var array An array of users */
996 public $users = array();
998 /** @var context The anticipated context that the calendar is viewed in */
999 public $context = null;
1002 * Creates a new instance
1004 * @param int $day the number of the day
1005 * @param int $month the number of the month
1006 * @param int $year the number of the year
1007 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
1008 * and $calyear to support multiple calendars
1010 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
1011 // If a day, month and year were passed then convert it to a timestamp. If these were passed
1012 // then we can assume the day, month and year are passed as Gregorian, as no where in core
1013 // should we be passing these values rather than the time. This is done for BC.
1014 if (!empty($day) || !empty($month) || !empty($year)) {
1015 $date = usergetdate(time());
1016 if (empty($day)) {
1017 $day = $date['mday'];
1019 if (empty($month)) {
1020 $month = $date['mon'];
1022 if (empty($year)) {
1023 $year = $date['year'];
1025 if (checkdate($month, $day, $year)) {
1026 $time = make_timestamp($year, $month, $day);
1027 } else {
1028 $time = time();
1032 $this->set_time($time);
1036 * Creates and set up a instance.
1038 * @param int $time the unixtimestamp representing the date we want to view.
1039 * @param int $courseid The ID of the course the user wishes to view.
1040 * @param int $categoryid The ID of the category the user wishes to view
1041 * If a courseid is specified, this value is ignored.
1042 * @return calendar_information
1044 public static function create($time, int $courseid, int $categoryid = null) : calendar_information {
1045 $calendar = new static(0, 0, 0, $time);
1046 if ($courseid != SITEID && !empty($courseid)) {
1047 // Course ID must be valid and existing.
1048 $course = get_course($courseid);
1049 $calendar->context = context_course::instance($course->id);
1051 if (!$course->visible) {
1052 require_capability('moodle/course:viewhiddencourses', $calendar->context);
1055 $courses = [$course->id => $course];
1056 $category = (\coursecat::get($course->category, MUST_EXIST, true))->get_db_record();
1057 } else if (!empty($categoryid)) {
1058 $course = get_site();
1059 $courses = calendar_get_default_courses();
1061 // Filter available courses to those within this category or it's children.
1062 $ids = [$categoryid];
1063 $category = \coursecat::get($categoryid);
1064 $ids = array_merge($ids, array_keys($category->get_children()));
1065 $courses = array_filter($courses, function($course) use ($ids) {
1066 return array_search($course->category, $ids) !== false;
1068 $category = $category->get_db_record();
1070 $calendar->context = context_coursecat::instance($categoryid);
1071 } else {
1072 $course = get_site();
1073 $courses = calendar_get_default_courses();
1074 $category = null;
1076 $calendar->context = context_system::instance();
1079 $calendar->set_sources($course, $courses, $category);
1081 return $calendar;
1085 * Set the time period of this instance.
1087 * @param int $time the unixtimestamp representing the date we want to view.
1088 * @return $this
1090 public function set_time($time = null) {
1091 if (empty($time)) {
1092 $this->time = time();
1093 } else {
1094 $this->time = $time;
1097 return $this;
1101 * Initialize calendar information
1103 * @deprecated 3.4
1104 * @param stdClass $course object
1105 * @param array $coursestoload An array of courses [$course->id => $course]
1106 * @param bool $ignorefilters options to use filter
1108 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
1109 debugging('The prepare_for_view() function has been deprecated. Please update your code to use set_sources()',
1110 DEBUG_DEVELOPER);
1111 $this->set_sources($course, $coursestoload);
1115 * Set the sources for events within the calendar.
1117 * If no category is provided, then the category path for the current
1118 * course will be used.
1120 * @param stdClass $course The current course being viewed.
1121 * @param stdClass[] $courses The list of all courses currently accessible.
1122 * @param stdClass $category The current category to show.
1124 public function set_sources(stdClass $course, array $courses, stdClass $category = null) {
1125 global $USER;
1127 // A cousre must always be specified.
1128 $this->course = $course;
1129 $this->courseid = $course->id;
1131 list($courseids, $group, $user) = calendar_set_filters($courses);
1132 $this->courses = $courseids;
1133 $this->groups = $group;
1134 $this->users = $user;
1136 // Do not show category events by default.
1137 $this->categoryid = null;
1138 $this->categories = null;
1140 // Determine the correct category information to show.
1141 // When called with a course, the category of that course is usually included too.
1142 // When a category was specifically requested, it should be requested with the site id.
1143 if (SITEID !== $this->courseid) {
1144 // A specific course was requested.
1145 // Fetch the category that this course is in, along with all parents.
1146 // Do not include child categories of this category, as the user many not have enrolments in those siblings or children.
1147 $category = \coursecat::get($course->category, MUST_EXIST, true);
1148 $this->categoryid = $category->id;
1150 $this->categories = $category->get_parents();
1151 $this->categories[] = $category->id;
1152 } else if (null !== $category && $category->id > 0) {
1153 // A specific category was requested.
1154 // Fetch all parents of this category, along with all children too.
1155 $category = \coursecat::get($category->id);
1156 $this->categoryid = $category->id;
1158 // Build the category list.
1159 // This includes the current category.
1160 $this->categories = $category->get_parents();
1161 $this->categories[] = $category->id;
1162 $this->categories = array_merge($this->categories, $category->get_all_children_ids());
1163 } else if (SITEID === $this->courseid) {
1164 // The site was requested.
1165 // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
1167 // Grab the list of categories that this user has courses in.
1168 $coursecategories = array_flip(array_map(function($course) {
1169 return $course->category;
1170 }, $courses));
1172 $calcatcache = cache::make('core', 'calendar_categories');
1173 $this->categories = $calcatcache->get('site');
1174 if ($this->categories === false) {
1175 // Use the category id as the key in the following array. That way we do not have to remove duplicates.
1176 $categories = [];
1177 foreach (\coursecat::get_all() as $category) {
1178 if (isset($coursecategories[$category->id]) ||
1179 has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
1180 // If the user has access to a course in this category or can manage the category,
1181 // then they can see all parent categories too.
1182 $categories[$category->id] = true;
1183 foreach ($category->get_parents() as $catid) {
1184 $categories[$catid] = true;
1188 $this->categories = array_keys($categories);
1189 $calcatcache->set('site', $this->categories);
1195 * Ensures the date for the calendar is correct and either sets it to now
1196 * or throws a moodle_exception if not
1198 * @param bool $defaultonow use current time
1199 * @throws moodle_exception
1200 * @return bool validation of checkdate
1202 public function checkdate($defaultonow = true) {
1203 if (!checkdate($this->month, $this->day, $this->year)) {
1204 if ($defaultonow) {
1205 $now = usergetdate(time());
1206 $this->day = intval($now['mday']);
1207 $this->month = intval($now['mon']);
1208 $this->year = intval($now['year']);
1209 return true;
1210 } else {
1211 throw new moodle_exception('invaliddate');
1214 return true;
1218 * Gets todays timestamp for the calendar
1220 * @return int today timestamp
1222 public function timestamp_today() {
1223 return $this->time;
1226 * Gets tomorrows timestamp for the calendar
1228 * @return int tomorrow timestamp
1230 public function timestamp_tomorrow() {
1231 return strtotime('+1 day', $this->time);
1234 * Adds the pretend blocks for the calendar
1236 * @param core_calendar_renderer $renderer
1237 * @param bool $showfilters display filters, false is set as default
1238 * @param string|null $view preference view options (eg: day, month, upcoming)
1240 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
1241 if ($showfilters) {
1242 $filters = new block_contents();
1243 $filters->content = $renderer->event_filter();
1244 $filters->footer = '';
1245 $filters->title = get_string('eventskey', 'calendar');
1246 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
1248 $block = new block_contents;
1249 $block->content = $renderer->fake_block_threemonths($this);
1250 $block->footer = '';
1251 $block->title = get_string('monthlyview', 'calendar');
1252 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
1257 * Get calendar events.
1259 * @param int $tstart Start time of time range for events
1260 * @param int $tend End time of time range for events
1261 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
1262 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
1263 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
1264 * @param boolean $withduration whether only events starting within time range selected
1265 * or events in progress/already started selected as well
1266 * @param boolean $ignorehidden whether to select only visible events or all events
1267 * @param array|int|boolean $categories array of categories, category id or boolean for all/no course events
1268 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
1270 function calendar_get_events($tstart, $tend, $users, $groups, $courses,
1271 $withduration = true, $ignorehidden = true, $categories = []) {
1272 global $DB;
1274 $whereclause = '';
1275 $params = array();
1276 // Quick test.
1277 if (empty($users) && empty($groups) && empty($courses) && empty($categories)) {
1278 return array();
1281 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
1282 // Events from a number of users
1283 if(!empty($whereclause)) $whereclause .= ' OR';
1284 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED);
1285 $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)";
1286 $params = array_merge($params, $inparamsusers);
1287 } else if($users === true) {
1288 // Events from ALL users
1289 if(!empty($whereclause)) $whereclause .= ' OR';
1290 $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)';
1291 } else if($users === false) {
1292 // No user at all, do nothing
1295 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
1296 // Events from a number of groups
1297 if(!empty($whereclause)) $whereclause .= ' OR';
1298 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED);
1299 $whereclause .= " e.groupid $insqlgroups ";
1300 $params = array_merge($params, $inparamsgroups);
1301 } else if($groups === true) {
1302 // Events from ALL groups
1303 if(!empty($whereclause)) $whereclause .= ' OR ';
1304 $whereclause .= ' e.groupid != 0';
1306 // boolean false (no groups at all): we don't need to do anything
1308 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
1309 if(!empty($whereclause)) $whereclause .= ' OR';
1310 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED);
1311 $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
1312 $params = array_merge($params, $inparamscourses);
1313 } else if ($courses === true) {
1314 // Events from ALL courses
1315 if(!empty($whereclause)) $whereclause .= ' OR';
1316 $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
1319 if ((is_array($categories) && !empty($categories)) || is_numeric($categories)) {
1320 if (!empty($whereclause)) {
1321 $whereclause .= ' OR';
1323 list($insqlcategories, $inparamscategories) = $DB->get_in_or_equal($categories, SQL_PARAMS_NAMED);
1324 $whereclause .= " (e.groupid = 0 AND e.courseid = 0 AND e.categoryid $insqlcategories)";
1325 $params = array_merge($params, $inparamscategories);
1326 } else if ($categories === true) {
1327 // Events from ALL categories.
1328 if (!empty($whereclause)) {
1329 $whereclause .= ' OR';
1331 $whereclause .= ' (e.groupid = 0 AND e.courseid = 0 AND e.categoryid != 0)';
1334 // Security check: if, by now, we have NOTHING in $whereclause, then it means
1335 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
1336 // events no matter what. Allowing the code to proceed might return a completely
1337 // valid query with only time constraints, thus selecting ALL events in that time frame!
1338 if(empty($whereclause)) {
1339 return array();
1342 if($withduration) {
1343 $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1345 else {
1346 $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1348 if(!empty($whereclause)) {
1349 // We have additional constraints
1350 $whereclause = $timeclause.' AND ('.$whereclause.')';
1352 else {
1353 // Just basic time filtering
1354 $whereclause = $timeclause;
1357 if ($ignorehidden) {
1358 $whereclause .= ' AND e.visible = 1';
1361 $sql = "SELECT e.*
1362 FROM {event} e
1363 LEFT JOIN {modules} m ON e.modulename = m.name
1364 -- Non visible modules will have a value of 0.
1365 WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
1366 ORDER BY e.timestart";
1367 $events = $DB->get_records_sql($sql, $params);
1369 if ($events === false) {
1370 $events = array();
1372 return $events;
1376 * Return the days of the week.
1378 * @return array array of days
1380 function calendar_get_days() {
1381 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1382 return $calendartype->get_weekdays();
1386 * Get the subscription from a given id.
1388 * @since Moodle 2.5
1389 * @param int $id id of the subscription
1390 * @return stdClass Subscription record from DB
1391 * @throws moodle_exception for an invalid id
1393 function calendar_get_subscription($id) {
1394 global $DB;
1396 $cache = \cache::make('core', 'calendar_subscriptions');
1397 $subscription = $cache->get($id);
1398 if (empty($subscription)) {
1399 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
1400 $cache->set($id, $subscription);
1403 return $subscription;
1407 * Gets the first day of the week.
1409 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
1411 * @return int
1413 function calendar_get_starting_weekday() {
1414 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1415 return $calendartype->get_starting_weekday();
1419 * Get a HTML link to a course.
1421 * @param int|stdClass $course the course id or course object
1422 * @return string a link to the course (as HTML); empty if the course id is invalid
1424 function calendar_get_courselink($course) {
1425 if (!$course) {
1426 return '';
1429 if (!is_object($course)) {
1430 $course = calendar_get_course_cached($coursecache, $course);
1432 $context = \context_course::instance($course->id);
1433 $fullname = format_string($course->fullname, true, array('context' => $context));
1434 $url = new \moodle_url('/course/view.php', array('id' => $course->id));
1435 $link = \html_writer::link($url, $fullname);
1437 return $link;
1441 * Get current module cache.
1443 * Only use this method if you do not know courseid. Otherwise use:
1444 * get_fast_modinfo($courseid)->instances[$modulename][$instance]
1446 * @param array $modulecache in memory module cache
1447 * @param string $modulename name of the module
1448 * @param int $instance module instance number
1449 * @return stdClass|bool $module information
1451 function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
1452 if (!isset($modulecache[$modulename . '_' . $instance])) {
1453 $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
1456 return $modulecache[$modulename . '_' . $instance];
1460 * Get current course cache.
1462 * @param array $coursecache list of course cache
1463 * @param int $courseid id of the course
1464 * @return stdClass $coursecache[$courseid] return the specific course cache
1466 function calendar_get_course_cached(&$coursecache, $courseid) {
1467 if (!isset($coursecache[$courseid])) {
1468 $coursecache[$courseid] = get_course($courseid);
1470 return $coursecache[$courseid];
1474 * Get group from groupid for calendar display
1476 * @param int $groupid
1477 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1479 function calendar_get_group_cached($groupid) {
1480 static $groupscache = array();
1481 if (!isset($groupscache[$groupid])) {
1482 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1484 return $groupscache[$groupid];
1488 * Add calendar event metadata
1490 * @param stdClass $event event info
1491 * @return stdClass $event metadata
1493 function calendar_add_event_metadata($event) {
1494 global $CFG, $OUTPUT;
1496 // Support multilang in event->name.
1497 $event->name = format_string($event->name, true);
1499 if (!empty($event->modulename)) { // Activity event.
1500 // The module name is set. I will assume that it has to be displayed, and
1501 // also that it is an automatically-generated event. And of course that the
1502 // instace id and modulename are set correctly.
1503 $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
1504 if (!array_key_exists($event->instance, $instances)) {
1505 return;
1507 $module = $instances[$event->instance];
1509 $modulename = $module->get_module_type_name(false);
1510 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
1511 // Will be used as alt text if the event icon.
1512 $eventtype = get_string($event->eventtype, $event->modulename);
1513 } else {
1514 $eventtype = '';
1517 $event->icon = '<img src="' . s($module->get_icon_url()) . '" alt="' . s($eventtype) .
1518 '" title="' . s($modulename) . '" class="icon" />';
1519 $event->referer = html_writer::link($module->url, $event->name);
1520 $event->courselink = calendar_get_courselink($module->get_course());
1521 $event->cmid = $module->id;
1522 } else if ($event->courseid == SITEID) { // Site event.
1523 $event->icon = '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
1524 get_string('globalevent', 'calendar') . '" class="icon" />';
1525 $event->cssclass = 'calendar_event_global';
1526 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event.
1527 $event->icon = '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
1528 get_string('courseevent', 'calendar') . '" class="icon" />';
1529 $event->courselink = calendar_get_courselink($event->courseid);
1530 $event->cssclass = 'calendar_event_course';
1531 } else if ($event->groupid) { // Group event.
1532 if ($group = calendar_get_group_cached($event->groupid)) {
1533 $groupname = format_string($group->name, true, \context_course::instance($group->courseid));
1534 } else {
1535 $groupname = '';
1537 $event->icon = \html_writer::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
1538 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
1539 $event->courselink = calendar_get_courselink($event->courseid) . ', ' . $groupname;
1540 $event->cssclass = 'calendar_event_group';
1541 } else if ($event->userid) { // User event.
1542 $event->icon = '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
1543 get_string('userevent', 'calendar') . '" class="icon" />';
1544 $event->cssclass = 'calendar_event_user';
1547 return $event;
1551 * Get calendar events by id.
1553 * @since Moodle 2.5
1554 * @param array $eventids list of event ids
1555 * @return array Array of event entries, empty array if nothing found
1557 function calendar_get_events_by_id($eventids) {
1558 global $DB;
1560 if (!is_array($eventids) || empty($eventids)) {
1561 return array();
1564 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
1565 $wheresql = "id $wheresql";
1567 return $DB->get_records_select('event', $wheresql, $params);
1571 * Get control options for calendar.
1573 * @param string $type of calendar
1574 * @param array $data calendar information
1575 * @return string $content return available control for the calender in html
1577 function calendar_top_controls($type, $data) {
1578 global $PAGE, $OUTPUT;
1580 // Get the calendar type we are using.
1581 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1583 $content = '';
1585 // Ensure course id passed if relevant.
1586 $courseid = '';
1587 if (!empty($data['id'])) {
1588 $courseid = '&amp;course=' . $data['id'];
1591 // If we are passing a month and year then we need to convert this to a timestamp to
1592 // support multiple calendars. No where in core should these be passed, this logic
1593 // here is for third party plugins that may use this function.
1594 if (!empty($data['m']) && !empty($date['y'])) {
1595 if (!isset($data['d'])) {
1596 $data['d'] = 1;
1598 if (!checkdate($data['m'], $data['d'], $data['y'])) {
1599 $time = time();
1600 } else {
1601 $time = make_timestamp($data['y'], $data['m'], $data['d']);
1603 } else if (!empty($data['time'])) {
1604 $time = $data['time'];
1605 } else {
1606 $time = time();
1609 // Get the date for the calendar type.
1610 $date = $calendartype->timestamp_to_date_array($time);
1612 $urlbase = $PAGE->url;
1614 // We need to get the previous and next months in certain cases.
1615 if ($type == 'frontpage' || $type == 'course' || $type == 'month') {
1616 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1617 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
1618 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
1619 $prevmonthtime['hour'], $prevmonthtime['minute']);
1621 $nextmonth = calendar_add_month($date['mon'], $date['year']);
1622 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
1623 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
1624 $nextmonthtime['hour'], $nextmonthtime['minute']);
1627 switch ($type) {
1628 case 'frontpage':
1629 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1630 true, $prevmonthtime);
1631 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true,
1632 $nextmonthtime);
1633 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1634 false, false, false, $time);
1636 if (!empty($data['id'])) {
1637 $calendarlink->param('course', $data['id']);
1640 $right = $nextlink;
1642 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1643 $content .= $prevlink . '<span class="hide"> | </span>';
1644 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1645 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1646 ), array('class' => 'current'));
1647 $content .= '<span class="hide"> | </span>' . $right;
1648 $content .= "<span class=\"clearer\"><!-- --></span>\n";
1649 $content .= \html_writer::end_tag('div');
1651 break;
1652 case 'course':
1653 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1654 true, $prevmonthtime);
1655 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false,
1656 true, $nextmonthtime);
1657 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1658 false, false, false, $time);
1660 if (!empty($data['id'])) {
1661 $calendarlink->param('course', $data['id']);
1664 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1665 $content .= $prevlink . '<span class="hide"> | </span>';
1666 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1667 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1668 ), array('class' => 'current'));
1669 $content .= '<span class="hide"> | </span>' . $nextlink;
1670 $content .= "<span class=\"clearer\"><!-- --></span>";
1671 $content .= \html_writer::end_tag('div');
1672 break;
1673 case 'upcoming':
1674 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'upcoming')),
1675 false, false, false, $time);
1676 if (!empty($data['id'])) {
1677 $calendarlink->param('course', $data['id']);
1679 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1680 $content .= \html_writer::tag('div', $calendarlink, array('class' => 'centered'));
1681 break;
1682 case 'display':
1683 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1684 false, false, false, $time);
1685 if (!empty($data['id'])) {
1686 $calendarlink->param('course', $data['id']);
1688 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1689 $content .= \html_writer::tag('h3', $calendarlink);
1690 break;
1691 case 'month':
1692 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1693 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $prevmonthtime);
1694 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1695 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $nextmonthtime);
1697 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1698 $content .= $prevlink . '<span class="hide"> | </span>';
1699 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1700 $content .= '<span class="hide"> | </span>' . $nextlink;
1701 $content .= '<span class="clearer"><!-- --></span>';
1702 $content .= \html_writer::end_tag('div')."\n";
1703 break;
1704 case 'day':
1705 $days = calendar_get_days();
1707 $prevtimestamp = strtotime('-1 day', $time);
1708 $nexttimestamp = strtotime('+1 day', $time);
1710 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1711 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1713 $prevname = $days[$prevdate['wday']]['fullname'];
1714 $nextname = $days[$nextdate['wday']]['fullname'];
1715 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&amp;', false, false,
1716 false, false, $prevtimestamp);
1717 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&amp;', false, false, false,
1718 false, $nexttimestamp);
1720 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1721 $content .= $prevlink;
1722 $content .= '<span class="hide"> | </span><span class="current">' .userdate($time,
1723 get_string('strftimedaydate')) . '</span>';
1724 $content .= '<span class="hide"> | </span>' . $nextlink;
1725 $content .= "<span class=\"clearer\"><!-- --></span>";
1726 $content .= \html_writer::end_tag('div') . "\n";
1728 break;
1731 return $content;
1735 * Return the representation day.
1737 * @param int $tstamp Timestamp in GMT
1738 * @param int|bool $now current Unix timestamp
1739 * @param bool $usecommonwords
1740 * @return string the formatted date/time
1742 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1743 static $shortformat;
1745 if (empty($shortformat)) {
1746 $shortformat = get_string('strftimedayshort');
1749 if ($now === false) {
1750 $now = time();
1753 // To have it in one place, if a change is needed.
1754 $formal = userdate($tstamp, $shortformat);
1756 $datestamp = usergetdate($tstamp);
1757 $datenow = usergetdate($now);
1759 if ($usecommonwords == false) {
1760 // We don't want words, just a date.
1761 return $formal;
1762 } else if ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1763 return get_string('today', 'calendar');
1764 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1765 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12
1766 && $datenow['yday'] == 1)) {
1767 return get_string('yesterday', 'calendar');
1768 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1769 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12
1770 && $datestamp['yday'] == 1)) {
1771 return get_string('tomorrow', 'calendar');
1772 } else {
1773 return $formal;
1778 * return the formatted representation time.
1781 * @param int $time the timestamp in UTC, as obtained from the database
1782 * @return string the formatted date/time
1784 function calendar_time_representation($time) {
1785 static $langtimeformat = null;
1787 if ($langtimeformat === null) {
1788 $langtimeformat = get_string('strftimetime');
1791 $timeformat = get_user_preferences('calendar_timeformat');
1792 if (empty($timeformat)) {
1793 $timeformat = get_config(null, 'calendar_site_timeformat');
1796 // Allow language customization of selected time format.
1797 if ($timeformat === CALENDAR_TF_12) {
1798 $timeformat = get_string('strftimetime12', 'langconfig');
1799 } else if ($timeformat === CALENDAR_TF_24) {
1800 $timeformat = get_string('strftimetime24', 'langconfig');
1803 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
1807 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1809 * @param string|moodle_url $linkbase
1810 * @param int $d The number of the day.
1811 * @param int $m The number of the month.
1812 * @param int $y The number of the year.
1813 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1814 * $m and $y are kept for backwards compatibility.
1815 * @return moodle_url|null $linkbase
1817 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1818 if (empty($linkbase)) {
1819 return null;
1822 if (!($linkbase instanceof \moodle_url)) {
1823 $linkbase = new \moodle_url($linkbase);
1826 $linkbase->param('time', calendar_get_timestamp($d, $m, $y, $time));
1828 return $linkbase;
1832 * Build and return a previous month HTML link, with an arrow.
1834 * @param string $text The text label.
1835 * @param string|moodle_url $linkbase The URL stub.
1836 * @param int $d The number of the date.
1837 * @param int $m The number of the month.
1838 * @param int $y year The number of the year.
1839 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1840 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1841 * $m and $y are kept for backwards compatibility.
1842 * @return string HTML string.
1844 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1845 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1847 if (empty($href)) {
1848 return $text;
1851 $attrs = [
1852 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1853 'data-drop-zone' => 'nav-link',
1856 return link_arrow_left($text, $href->out(false), $accesshide, 'previous', $attrs);
1860 * Build and return a next month HTML link, with an arrow.
1862 * @param string $text The text label.
1863 * @param string|moodle_url $linkbase The URL stub.
1864 * @param int $d the number of the Day
1865 * @param int $m The number of the month.
1866 * @param int $y The number of the year.
1867 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1868 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1869 * $m and $y are kept for backwards compatibility.
1870 * @return string HTML string.
1872 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1873 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1875 if (empty($href)) {
1876 return $text;
1879 $attrs = [
1880 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1881 'data-drop-zone' => 'nav-link',
1884 return link_arrow_right($text, $href->out(false), $accesshide, 'next', $attrs);
1888 * Return the number of days in month.
1890 * @param int $month the number of the month.
1891 * @param int $year the number of the year
1892 * @return int
1894 function calendar_days_in_month($month, $year) {
1895 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1896 return $calendartype->get_num_days_in_month($year, $month);
1900 * Get the next following month.
1902 * @param int $month the number of the month.
1903 * @param int $year the number of the year.
1904 * @return array the following month
1906 function calendar_add_month($month, $year) {
1907 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1908 return $calendartype->get_next_month($year, $month);
1912 * Get the previous month.
1914 * @param int $month the number of the month.
1915 * @param int $year the number of the year.
1916 * @return array previous month
1918 function calendar_sub_month($month, $year) {
1919 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1920 return $calendartype->get_prev_month($year, $month);
1924 * Get per-day basis events
1926 * @param array $events list of events
1927 * @param int $month the number of the month
1928 * @param int $year the number of the year
1929 * @param array $eventsbyday event on specific day
1930 * @param array $durationbyday duration of the event in days
1931 * @param array $typesbyday event type (eg: global, course, user, or group)
1932 * @param array $courses list of courses
1933 * @return void
1935 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1936 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1938 $eventsbyday = array();
1939 $typesbyday = array();
1940 $durationbyday = array();
1942 if ($events === false) {
1943 return;
1946 foreach ($events as $event) {
1947 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
1948 if ($event->timeduration) {
1949 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
1950 } else {
1951 $enddate = $startdate;
1954 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair.
1955 if (!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) &&
1956 ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1957 continue;
1960 $eventdaystart = intval($startdate['mday']);
1962 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
1963 // Give the event to its day.
1964 $eventsbyday[$eventdaystart][] = $event->id;
1966 // Mark the day as having such an event.
1967 if ($event->courseid == SITEID && $event->groupid == 0) {
1968 $typesbyday[$eventdaystart]['startglobal'] = true;
1969 // Set event class for global event.
1970 $events[$event->id]->class = 'calendar_event_global';
1971 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1972 $typesbyday[$eventdaystart]['startcourse'] = true;
1973 // Set event class for course event.
1974 $events[$event->id]->class = 'calendar_event_course';
1975 } else if ($event->groupid) {
1976 $typesbyday[$eventdaystart]['startgroup'] = true;
1977 // Set event class for group event.
1978 $events[$event->id]->class = 'calendar_event_group';
1979 } else if ($event->userid) {
1980 $typesbyday[$eventdaystart]['startuser'] = true;
1981 // Set event class for user event.
1982 $events[$event->id]->class = 'calendar_event_user';
1986 if ($event->timeduration == 0) {
1987 // Proceed with the next.
1988 continue;
1991 // The event starts on $month $year or before.
1992 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
1993 $lowerbound = intval($startdate['mday']);
1994 } else {
1995 $lowerbound = 0;
1998 // Also, it ends on $month $year or later.
1999 if ($enddate['mon'] == $month && $enddate['year'] == $year) {
2000 $upperbound = intval($enddate['mday']);
2001 } else {
2002 $upperbound = calendar_days_in_month($month, $year);
2005 // Mark all days between $lowerbound and $upperbound (inclusive) as duration.
2006 for ($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
2007 $durationbyday[$i][] = $event->id;
2008 if ($event->courseid == SITEID && $event->groupid == 0) {
2009 $typesbyday[$i]['durationglobal'] = true;
2010 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
2011 $typesbyday[$i]['durationcourse'] = true;
2012 } else if ($event->groupid) {
2013 $typesbyday[$i]['durationgroup'] = true;
2014 } else if ($event->userid) {
2015 $typesbyday[$i]['durationuser'] = true;
2020 return;
2024 * Returns the courses to load events for.
2026 * @param array $courseeventsfrom An array of courses to load calendar events for
2027 * @param bool $ignorefilters specify the use of filters, false is set as default
2028 * @return array An array of courses, groups, and user to load calendar events for based upon filters
2030 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
2031 global $USER, $CFG;
2033 // For backwards compatability we have to check whether the courses array contains
2034 // just id's in which case we need to load course objects.
2035 $coursestoload = array();
2036 foreach ($courseeventsfrom as $id => $something) {
2037 if (!is_object($something)) {
2038 $coursestoload[] = $id;
2039 unset($courseeventsfrom[$id]);
2043 $courses = array();
2044 $user = false;
2045 $group = false;
2047 // Get the capabilities that allow seeing group events from all groups.
2048 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
2050 $isloggedin = isloggedin();
2052 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
2053 $courses = array_keys($courseeventsfrom);
2055 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
2056 $courses[] = SITEID;
2058 $courses = array_unique($courses);
2059 sort($courses);
2061 if (!empty($courses) && in_array(SITEID, $courses)) {
2062 // Sort courses for consistent colour highlighting.
2063 // Effectively ignoring SITEID as setting as last course id.
2064 $key = array_search(SITEID, $courses);
2065 unset($courses[$key]);
2066 $courses[] = SITEID;
2069 if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
2070 $user = $USER->id;
2073 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
2075 if (count($courseeventsfrom) == 1) {
2076 $course = reset($courseeventsfrom);
2077 if (has_any_capability($allgroupscaps, \context_course::instance($course->id))) {
2078 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
2079 $group = array_keys($coursegroups);
2082 if ($group === false) {
2083 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, \context_system::instance())) {
2084 $group = true;
2085 } else if ($isloggedin) {
2086 $groupids = array();
2087 foreach ($courseeventsfrom as $courseid => $course) {
2088 // If the user is an editing teacher in there.
2089 if (!empty($USER->groupmember[$course->id])) {
2090 // We've already cached the users groups for this course so we can just use that.
2091 $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
2092 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2093 // If this course has groups, show events from all of those related to the current user.
2094 $coursegroups = groups_get_user_groups($course->id, $USER->id);
2095 $groupids = array_merge($groupids, $coursegroups['0']);
2098 if (!empty($groupids)) {
2099 $group = $groupids;
2104 if (empty($courses)) {
2105 $courses = false;
2108 return array($courses, $group, $user);
2112 * Return the capability for viewing a calendar event.
2114 * @param calendar_event $event event object
2115 * @return boolean
2117 function calendar_view_event_allowed(calendar_event $event) {
2118 global $USER;
2120 // Anyone can see site events.
2121 if ($event->courseid && $event->courseid == SITEID) {
2122 return true;
2125 // If a user can manage events at the site level they can see any event.
2126 $sitecontext = \context_system::instance();
2127 // If user has manageentries at site level, return true.
2128 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2129 return true;
2132 if (!empty($event->groupid)) {
2133 // If it is a group event we need to be able to manage events in the course, or be in the group.
2134 if (has_capability('moodle/calendar:manageentries', $event->context) ||
2135 has_capability('moodle/calendar:managegroupentries', $event->context)) {
2136 return true;
2139 $mycourses = enrol_get_my_courses('id');
2140 return isset($mycourses[$event->courseid]) && groups_is_member($event->groupid);
2141 } else if ($event->modulename) {
2142 // If this is a module event we need to be able to see the module.
2143 $coursemodules = [];
2144 $courseid = 0;
2145 // Override events do not have the courseid set.
2146 if ($event->courseid) {
2147 $courseid = $event->courseid;
2148 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2149 } else {
2150 $cmraw = get_coursemodule_from_instance($event->modulename, $event->instance, 0, false, MUST_EXIST);
2151 $courseid = $cmraw->course;
2152 $coursemodules = get_fast_modinfo($cmraw->course)->instances;
2154 $hasmodule = isset($coursemodules[$event->modulename]);
2155 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2157 // If modinfo doesn't know about the module, return false to be safe.
2158 if (!$hasmodule || !$hasinstance) {
2159 return false;
2162 // Must be able to see the course and the module - MDL-59304.
2163 $cm = $coursemodules[$event->modulename][$event->instance];
2164 if (!$cm->uservisible) {
2165 return false;
2167 $mycourses = enrol_get_my_courses('id');
2168 return isset($mycourses[$courseid]);
2169 } else if ($event->categoryid) {
2170 // If this is a category we need to be able to see the category.
2171 $cat = \coursecat::get($event->categoryid, IGNORE_MISSING);
2172 if (!$cat) {
2173 return false;
2175 return true;
2176 } else if (!empty($event->courseid)) {
2177 // If it is a course event we need to be able to manage events in the course, or be in the course.
2178 if (has_capability('moodle/calendar:manageentries', $event->context)) {
2179 return true;
2181 $mycourses = enrol_get_my_courses('id');
2182 return isset($mycourses[$event->courseid]);
2183 } else if ($event->userid) {
2184 if ($event->userid != $USER->id) {
2185 // No-one can ever see another users events.
2186 return false;
2188 return true;
2189 } else {
2190 throw new moodle_exception('unknown event type');
2193 return false;
2197 * Return the capability for editing calendar event.
2199 * @param calendar_event $event event object
2200 * @param bool $manualedit is the event being edited manually by the user
2201 * @return bool capability to edit event
2203 function calendar_edit_event_allowed($event, $manualedit = false) {
2204 global $USER, $DB;
2206 // Must be logged in.
2207 if (!isloggedin()) {
2208 return false;
2211 // Can not be using guest account.
2212 if (isguestuser()) {
2213 return false;
2216 if ($manualedit && !empty($event->modulename)) {
2217 $hascallback = component_callback_exists(
2218 'mod_' . $event->modulename,
2219 'core_calendar_event_timestart_updated'
2222 if (!$hascallback) {
2223 // If the activity hasn't implemented the correct callback
2224 // to handle changes to it's events then don't allow any
2225 // manual changes to them.
2226 return false;
2229 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2230 $hasmodule = isset($coursemodules[$event->modulename]);
2231 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2233 // If modinfo doesn't know about the module, return false to be safe.
2234 if (!$hasmodule || !$hasinstance) {
2235 return false;
2238 $coursemodule = $coursemodules[$event->modulename][$event->instance];
2239 $context = context_module::instance($coursemodule->id);
2240 // This is the capability that allows a user to modify the activity
2241 // settings. Since the activity generated this event we need to check
2242 // that the current user has the same capability before allowing them
2243 // to update the event because the changes to the event will be
2244 // reflected within the activity.
2245 return has_capability('moodle/course:manageactivities', $context);
2248 // You cannot edit URL based calendar subscription events presently.
2249 if (!empty($event->subscriptionid)) {
2250 if (!empty($event->subscription->url)) {
2251 // This event can be updated externally, so it cannot be edited.
2252 return false;
2256 $sitecontext = \context_system::instance();
2258 // If user has manageentries at site level, return true.
2259 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2260 return true;
2263 // If groupid is set, it's definitely a group event.
2264 if (!empty($event->groupid)) {
2265 // Allow users to add/edit group events if -
2266 // 1) They have manageentries for the course OR
2267 // 2) They have managegroupentries AND are in the group.
2268 $group = $DB->get_record('groups', array('id' => $event->groupid));
2269 return $group && (
2270 has_capability('moodle/calendar:manageentries', $event->context) ||
2271 (has_capability('moodle/calendar:managegroupentries', $event->context)
2272 && groups_is_member($event->groupid)));
2273 } else if (!empty($event->courseid)) {
2274 // If groupid is not set, but course is set, it's definitely a course event.
2275 return has_capability('moodle/calendar:manageentries', $event->context);
2276 } else if (!empty($event->categoryid)) {
2277 // If groupid is not set, but category is set, it's definitely a category event.
2278 return has_capability('moodle/calendar:manageentries', $event->context);
2279 } else if (!empty($event->userid) && $event->userid == $USER->id) {
2280 // If course is not set, but userid id set, it's a user event.
2281 return (has_capability('moodle/calendar:manageownentries', $event->context));
2282 } else if (!empty($event->userid)) {
2283 return (has_capability('moodle/calendar:manageentries', $event->context));
2286 return false;
2290 * Return the capability for deleting a calendar event.
2292 * @param calendar_event $event The event object
2293 * @return bool Whether the user has permission to delete the event or not.
2295 function calendar_delete_event_allowed($event) {
2296 // Only allow delete if you have capabilities and it is not an module event.
2297 return (calendar_edit_event_allowed($event) && empty($event->modulename));
2301 * Returns the default courses to display on the calendar when there isn't a specific
2302 * course to display.
2304 * @param int $courseid (optional) If passed, an additional course can be returned for admins (the current course).
2305 * @param string $fields Comma separated list of course fields to return.
2306 * @param bool $canmanage If true, this will return the list of courses the current user can create events in, rather
2307 * than the list of courses they see events from (an admin can always add events in a course
2308 * calendar, even if they are not enrolled in the course).
2309 * @return array $courses Array of courses to display
2311 function calendar_get_default_courses($courseid = null, $fields = '*', $canmanage=false) {
2312 global $CFG, $DB;
2314 if (!isloggedin()) {
2315 return array();
2318 if (has_capability('moodle/calendar:manageentries', context_system::instance()) &&
2319 (!empty($CFG->calendar_adminseesall) || $canmanage)) {
2321 // Add a c. prefix to every field as expected by get_courses function.
2322 $fieldlist = explode(',', $fields);
2324 $prefixedfields = array_map(function($value) {
2325 return 'c.' . trim($value);
2326 }, $fieldlist);
2327 $courses = get_courses('all', 'c.shortname', implode(',', $prefixedfields));
2328 } else {
2329 $courses = enrol_get_my_courses($fields);
2332 if ($courseid && $courseid != SITEID) {
2333 if (empty($courses[$courseid]) && has_capability('moodle/calendar:manageentries', context_system::instance())) {
2334 // Allow a site admin to see calendars from courses he is not enrolled in.
2335 // This will come from $COURSE.
2336 $courses[$courseid] = get_course($courseid);
2340 return $courses;
2344 * Get event format time.
2346 * @param calendar_event $event event object
2347 * @param int $now current time in gmt
2348 * @param array $linkparams list of params for event link
2349 * @param bool $usecommonwords the words as formatted date/time.
2350 * @param int $showtime determine the show time GMT timestamp
2351 * @return string $eventtime link/string for event time
2353 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
2354 $starttime = $event->timestart;
2355 $endtime = $event->timestart + $event->timeduration;
2357 if (empty($linkparams) || !is_array($linkparams)) {
2358 $linkparams = array();
2361 $linkparams['view'] = 'day';
2363 // OK, now to get a meaningful display.
2364 // Check if there is a duration for this event.
2365 if ($event->timeduration) {
2366 // Get the midnight of the day the event will start.
2367 $usermidnightstart = usergetmidnight($starttime);
2368 // Get the midnight of the day the event will end.
2369 $usermidnightend = usergetmidnight($endtime);
2370 // Check if we will still be on the same day.
2371 if ($usermidnightstart == $usermidnightend) {
2372 // Check if we are running all day.
2373 if ($event->timeduration == DAYSECS) {
2374 $time = get_string('allday', 'calendar');
2375 } else { // Specify the time we will be running this from.
2376 $datestart = calendar_time_representation($starttime);
2377 $dateend = calendar_time_representation($endtime);
2378 $time = $datestart . ' <strong>&raquo;</strong> ' . $dateend;
2381 // Set printable representation.
2382 if (!$showtime) {
2383 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2384 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2385 $eventtime = \html_writer::link($url, $day) . ', ' . $time;
2386 } else {
2387 $eventtime = $time;
2389 } else { // It must spans two or more days.
2390 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
2391 if ($showtime == $usermidnightstart) {
2392 $daystart = '';
2394 $timestart = calendar_time_representation($event->timestart);
2395 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
2396 if ($showtime == $usermidnightend) {
2397 $dayend = '';
2399 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
2401 // Set printable representation.
2402 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2403 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2404 $eventtime = $timestart . ' <strong>&raquo;</strong> ' . \html_writer::link($url, $dayend) . $timeend;
2405 } else {
2406 // The event is in the future, print start and end links.
2407 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2408 $eventtime = \html_writer::link($url, $daystart) . $timestart . ' <strong>&raquo;</strong> ';
2410 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2411 $eventtime .= \html_writer::link($url, $dayend) . $timeend;
2414 } else { // There is no time duration.
2415 $time = calendar_time_representation($event->timestart);
2416 // Set printable representation.
2417 if (!$showtime) {
2418 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2419 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2420 $eventtime = \html_writer::link($url, $day) . ', ' . trim($time);
2421 } else {
2422 $eventtime = $time;
2426 // Check if It has expired.
2427 if ($event->timestart + $event->timeduration < $now) {
2428 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2431 return $eventtime;
2435 * Checks to see if the requested type of event should be shown for the given user.
2437 * @param int $type The type to check the display for (default is to display all)
2438 * @param stdClass|int|null $user The user to check for - by default the current user
2439 * @return bool True if the tyep should be displayed false otherwise
2441 function calendar_show_event_type($type, $user = null) {
2442 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
2444 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2445 global $SESSION;
2446 if (!isset($SESSION->calendarshoweventtype)) {
2447 $SESSION->calendarshoweventtype = $default;
2449 return $SESSION->calendarshoweventtype & $type;
2450 } else {
2451 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2456 * Sets the display of the event type given $display.
2458 * If $display = true the event type will be shown.
2459 * If $display = false the event type will NOT be shown.
2460 * If $display = null the current value will be toggled and saved.
2462 * @param int $type object of CALENDAR_EVENT_XXX
2463 * @param bool $display option to display event type
2464 * @param stdClass|int $user moodle user object or id, null means current user
2466 function calendar_set_event_type_display($type, $display = null, $user = null) {
2467 $persist = get_user_preferences('calendar_persistflt', 0, $user);
2468 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP
2469 + CALENDAR_EVENT_USER + CALENDAR_EVENT_COURSECAT;
2470 if ($persist === 0) {
2471 global $SESSION;
2472 if (!isset($SESSION->calendarshoweventtype)) {
2473 $SESSION->calendarshoweventtype = $default;
2475 $preference = $SESSION->calendarshoweventtype;
2476 } else {
2477 $preference = get_user_preferences('calendar_savedflt', $default, $user);
2479 $current = $preference & $type;
2480 if ($display === null) {
2481 $display = !$current;
2483 if ($display && !$current) {
2484 $preference += $type;
2485 } else if (!$display && $current) {
2486 $preference -= $type;
2488 if ($persist === 0) {
2489 $SESSION->calendarshoweventtype = $preference;
2490 } else {
2491 if ($preference == $default) {
2492 unset_user_preference('calendar_savedflt', $user);
2493 } else {
2494 set_user_preference('calendar_savedflt', $preference, $user);
2500 * Get calendar's allowed types.
2502 * @param stdClass $allowed list of allowed edit for event type
2503 * @param stdClass|int $course object of a course or course id
2504 * @param array $groups array of groups for the given course
2505 * @param stdClass|int $category object of a category
2507 function calendar_get_allowed_types(&$allowed, $course = null, $groups = null, $category = null) {
2508 global $USER, $DB;
2510 $allowed = new \stdClass();
2511 $allowed->user = has_capability('moodle/calendar:manageownentries', \context_system::instance());
2512 $allowed->groups = false;
2513 $allowed->courses = false;
2514 $allowed->categories = false;
2515 $allowed->site = has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID));
2516 $getgroupsfunc = function($course, $context, $user) use ($groups) {
2517 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2518 if (has_capability('moodle/site:accessallgroups', $context)) {
2519 return is_null($groups) ? groups_get_all_groups($course->id) : $groups;
2520 } else {
2521 if (is_null($groups)) {
2522 return groups_get_all_groups($course->id, $user->id);
2523 } else {
2524 return array_filter($groups, function($group) use ($user) {
2525 return isset($group->members[$user->id]);
2531 return false;
2534 if (!empty($course)) {
2535 if (!is_object($course)) {
2536 $course = $DB->get_record('course', array('id' => $course), 'id, groupmode, groupmodeforce', MUST_EXIST);
2538 if ($course->id != SITEID) {
2539 $coursecontext = \context_course::instance($course->id);
2540 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
2542 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2543 $allowed->courses = array($course->id => 1);
2544 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2545 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
2546 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2551 if (!empty($category)) {
2552 $catcontext = \context_coursecat::instance($category->id);
2553 if (has_capability('moodle/category:manage', $catcontext)) {
2554 $allowed->categories = [$category->id => 1];
2560 * Get all of the allowed types for all of the courses and groups
2561 * the logged in user belongs to.
2563 * The returned array will optionally have 5 keys:
2564 * 'user' : true if the logged in user can create user events
2565 * 'site' : true if the logged in user can create site events
2566 * 'category' : array of course categories that the user can create events for
2567 * 'course' : array of courses that the user can create events for
2568 * 'group': array of groups that the user can create events for
2569 * 'groupcourses' : array of courses that the groups belong to (can
2570 * be different from the list in 'course'.
2572 * @return array The array of allowed types.
2574 function calendar_get_all_allowed_types() {
2575 global $CFG, $USER, $DB;
2577 require_once($CFG->libdir . '/enrollib.php');
2579 $types = [];
2581 $allowed = new stdClass();
2583 calendar_get_allowed_types($allowed);
2585 if ($allowed->user) {
2586 $types['user'] = true;
2589 if ($allowed->site) {
2590 $types['site'] = true;
2593 if (coursecat::has_manage_capability_on_any()) {
2594 $types['category'] = coursecat::make_categories_list('moodle/category:manage');
2597 // This function warms the context cache for the course so the calls
2598 // to load the course context in calendar_get_allowed_types don't result
2599 // in additional DB queries.
2600 $courses = calendar_get_default_courses(null, 'id, groupmode, groupmodeforce', true);
2602 // We want to pre-fetch all of the groups for each course in a single
2603 // query to avoid calendar_get_allowed_types from hitting the DB for
2604 // each separate course.
2605 $groups = groups_get_all_groups_for_courses($courses);
2607 foreach ($courses as $course) {
2608 $coursegroups = isset($groups[$course->id]) ? $groups[$course->id] : null;
2609 calendar_get_allowed_types($allowed, $course, $coursegroups);
2611 if (!empty($allowed->courses)) {
2612 $types['course'][$course->id] = $course;
2615 if (!empty($allowed->groups)) {
2616 $types['groupcourses'][$course->id] = $course;
2618 if (!isset($types['group'])) {
2619 $types['group'] = array_values($allowed->groups);
2620 } else {
2621 $types['group'] = array_merge($types['group'], array_values($allowed->groups));
2626 return $types;
2630 * See if user can add calendar entries at all used to print the "New Event" button.
2632 * @param stdClass $course object of a course or course id
2633 * @return bool has the capability to add at least one event type
2635 function calendar_user_can_add_event($course) {
2636 if (!isloggedin() || isguestuser()) {
2637 return false;
2640 calendar_get_allowed_types($allowed, $course);
2642 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->categories || $allowed->site);
2646 * Check wether the current user is permitted to add events.
2648 * @param stdClass $event object of event
2649 * @return bool has the capability to add event
2651 function calendar_add_event_allowed($event) {
2652 global $USER, $DB;
2654 // Can not be using guest account.
2655 if (!isloggedin() or isguestuser()) {
2656 return false;
2659 $sitecontext = \context_system::instance();
2661 // If user has manageentries at site level, always return true.
2662 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2663 return true;
2666 switch ($event->eventtype) {
2667 case 'category':
2668 return has_capability('moodle/category:manage', $event->context);
2669 case 'course':
2670 return has_capability('moodle/calendar:manageentries', $event->context);
2671 case 'group':
2672 // Allow users to add/edit group events if -
2673 // 1) They have manageentries (= entries for whole course).
2674 // 2) They have managegroupentries AND are in the group.
2675 $group = $DB->get_record('groups', array('id' => $event->groupid));
2676 return $group && (
2677 has_capability('moodle/calendar:manageentries', $event->context) ||
2678 (has_capability('moodle/calendar:managegroupentries', $event->context)
2679 && groups_is_member($event->groupid)));
2680 case 'user':
2681 if ($event->userid == $USER->id) {
2682 return (has_capability('moodle/calendar:manageownentries', $event->context));
2684 // There is intentionally no 'break'.
2685 case 'site':
2686 return has_capability('moodle/calendar:manageentries', $event->context);
2687 default:
2688 return has_capability('moodle/calendar:manageentries', $event->context);
2693 * Returns option list for the poll interval setting.
2695 * @return array An array of poll interval options. Interval => description.
2697 function calendar_get_pollinterval_choices() {
2698 return array(
2699 '0' => new \lang_string('never', 'calendar'),
2700 HOURSECS => new \lang_string('hourly', 'calendar'),
2701 DAYSECS => new \lang_string('daily', 'calendar'),
2702 WEEKSECS => new \lang_string('weekly', 'calendar'),
2703 '2628000' => new \lang_string('monthly', 'calendar'),
2704 YEARSECS => new \lang_string('annually', 'calendar')
2709 * Returns option list of available options for the calendar event type, given the current user and course.
2711 * @param int $courseid The id of the course
2712 * @return array An array containing the event types the user can create.
2714 function calendar_get_eventtype_choices($courseid) {
2715 $choices = array();
2716 $allowed = new \stdClass;
2717 calendar_get_allowed_types($allowed, $courseid);
2719 if ($allowed->user) {
2720 $choices['user'] = get_string('userevents', 'calendar');
2722 if ($allowed->site) {
2723 $choices['site'] = get_string('siteevents', 'calendar');
2725 if (!empty($allowed->courses)) {
2726 $choices['course'] = get_string('courseevents', 'calendar');
2728 if (!empty($allowed->categories)) {
2729 $choices['category'] = get_string('categoryevents', 'calendar');
2731 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2732 $choices['group'] = get_string('group');
2735 return array($choices, $allowed->groups);
2739 * Add an iCalendar subscription to the database.
2741 * @param stdClass $sub The subscription object (e.g. from the form)
2742 * @return int The insert ID, if any.
2744 function calendar_add_subscription($sub) {
2745 global $DB, $USER, $SITE;
2747 // Undo the form definition work around to allow us to have two different
2748 // course selectors present depending on which event type the user selects.
2749 if (!empty($sub->groupcourseid)) {
2750 $sub->courseid = $sub->groupcourseid;
2751 unset($sub->groupcourseid);
2754 // Pull the group id back out of the value. The form saves the value
2755 // as "<courseid>-<groupid>" to allow the javascript to work correctly.
2756 if (!empty($sub->groupid)) {
2757 list($courseid, $groupid) = explode('-', $sub->groupid);
2758 $sub->courseid = $courseid;
2759 $sub->groupid = $groupid;
2762 // Default course id if none is set.
2763 if (empty($sub->courseid)) {
2764 if ($sub->eventtype === 'site') {
2765 $sub->courseid = SITEID;
2766 } else {
2767 $sub->courseid = 0;
2771 if ($sub->eventtype === 'site') {
2772 $sub->courseid = $SITE->id;
2773 } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
2774 $sub->courseid = $sub->courseid;
2775 } else if ($sub->eventtype === 'category') {
2776 $sub->categoryid = $sub->categoryid;
2777 } else {
2778 // User events.
2779 $sub->courseid = 0;
2781 $sub->userid = $USER->id;
2783 // File subscriptions never update.
2784 if (empty($sub->url)) {
2785 $sub->pollinterval = 0;
2788 if (!empty($sub->name)) {
2789 if (empty($sub->id)) {
2790 $id = $DB->insert_record('event_subscriptions', $sub);
2791 // We cannot cache the data here because $sub is not complete.
2792 $sub->id = $id;
2793 // Trigger event, calendar subscription added.
2794 $eventparams = array('objectid' => $sub->id,
2795 'context' => calendar_get_calendar_context($sub),
2796 'other' => array(
2797 'eventtype' => $sub->eventtype,
2800 switch ($sub->eventtype) {
2801 case 'category':
2802 $eventparams['other']['categoryid'] = $sub->categoryid;
2803 break;
2804 case 'course':
2805 $eventparams['other']['courseid'] = $sub->courseid;
2806 break;
2807 case 'group':
2808 $eventparams['other']['courseid'] = $sub->courseid;
2809 $eventparams['other']['groupid'] = $sub->groupid;
2810 break;
2811 default:
2812 $eventparams['other']['courseid'] = $sub->courseid;
2815 $event = \core\event\calendar_subscription_created::create($eventparams);
2816 $event->trigger();
2817 return $id;
2818 } else {
2819 // Why are we doing an update here?
2820 calendar_update_subscription($sub);
2821 return $sub->id;
2823 } else {
2824 print_error('errorbadsubscription', 'importcalendar');
2829 * Add an iCalendar event to the Moodle calendar.
2831 * @param stdClass $event The RFC-2445 iCalendar event
2832 * @param int $unused Deprecated
2833 * @param int $subscriptionid The iCalendar subscription ID
2834 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2835 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2836 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2838 function calendar_add_icalendar_event($event, $unused = null, $subscriptionid, $timezone='UTC') {
2839 global $DB;
2841 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2842 if (empty($event->properties['SUMMARY'])) {
2843 return 0;
2846 $name = $event->properties['SUMMARY'][0]->value;
2847 $name = str_replace('\n', '<br />', $name);
2848 $name = str_replace('\\', '', $name);
2849 $name = preg_replace('/\s+/u', ' ', $name);
2851 $eventrecord = new \stdClass;
2852 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
2854 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2855 $description = '';
2856 } else {
2857 $description = $event->properties['DESCRIPTION'][0]->value;
2858 $description = clean_param($description, PARAM_NOTAGS);
2859 $description = str_replace('\n', '<br />', $description);
2860 $description = str_replace('\\', '', $description);
2861 $description = preg_replace('/\s+/u', ' ', $description);
2863 $eventrecord->description = $description;
2865 // Probably a repeating event with RRULE etc. TODO: skip for now.
2866 if (empty($event->properties['DTSTART'][0]->value)) {
2867 return 0;
2870 if (isset($event->properties['DTSTART'][0]->parameters['TZID'])) {
2871 $tz = $event->properties['DTSTART'][0]->parameters['TZID'];
2872 } else {
2873 $tz = $timezone;
2875 $tz = \core_date::normalise_timezone($tz);
2876 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value . ' ' . $tz);
2877 if (empty($event->properties['DTEND'])) {
2878 $eventrecord->timeduration = 0; // No duration if no end time specified.
2879 } else {
2880 if (isset($event->properties['DTEND'][0]->parameters['TZID'])) {
2881 $endtz = $event->properties['DTEND'][0]->parameters['TZID'];
2882 } else {
2883 $endtz = $timezone;
2885 $endtz = \core_date::normalise_timezone($endtz);
2886 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value . ' ' . $endtz) - $eventrecord->timestart;
2889 // Check to see if it should be treated as an all day event.
2890 if ($eventrecord->timeduration == DAYSECS) {
2891 // Check to see if the event started at Midnight on the imported calendar.
2892 date_default_timezone_set($timezone);
2893 if (date('H:i:s', $eventrecord->timestart) === "00:00:00") {
2894 // This event should be an all day event. This is not correct, we don't do anything differently for all day events.
2895 // See MDL-56227.
2896 $eventrecord->timeduration = 0;
2898 \core_date::set_default_server_timezone();
2901 $eventrecord->uuid = $event->properties['UID'][0]->value;
2902 $eventrecord->timemodified = time();
2904 // Add the iCal subscription details if required.
2905 // We should never do anything with an event without a subscription reference.
2906 $sub = calendar_get_subscription($subscriptionid);
2907 $eventrecord->subscriptionid = $subscriptionid;
2908 $eventrecord->userid = $sub->userid;
2909 $eventrecord->groupid = $sub->groupid;
2910 $eventrecord->courseid = $sub->courseid;
2911 $eventrecord->categoryid = $sub->categoryid;
2912 $eventrecord->eventtype = $sub->eventtype;
2914 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid,
2915 'subscriptionid' => $eventrecord->subscriptionid))) {
2916 $eventrecord->id = $updaterecord->id;
2917 $return = CALENDAR_IMPORT_EVENT_UPDATED; // Update.
2918 } else {
2919 $return = CALENDAR_IMPORT_EVENT_INSERTED; // Insert.
2921 if ($createdevent = \calendar_event::create($eventrecord, false)) {
2922 if (!empty($event->properties['RRULE'])) {
2923 // Repeating events.
2924 date_default_timezone_set($tz); // Change time zone to parse all events.
2925 $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
2926 $rrule->parse_rrule();
2927 $rrule->create_events($createdevent);
2928 \core_date::set_default_server_timezone(); // Change time zone back to what it was.
2930 return $return;
2931 } else {
2932 return 0;
2937 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2939 * @param int $subscriptionid The ID of the subscription we are acting upon.
2940 * @param int $pollinterval The poll interval to use.
2941 * @param int $action The action to be performed. One of update or remove.
2942 * @throws dml_exception if invalid subscriptionid is provided
2943 * @return string A log of the import progress, including errors
2945 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2946 // Fetch the subscription from the database making sure it exists.
2947 $sub = calendar_get_subscription($subscriptionid);
2949 // Update or remove the subscription, based on action.
2950 switch ($action) {
2951 case CALENDAR_SUBSCRIPTION_UPDATE:
2952 // Skip updating file subscriptions.
2953 if (empty($sub->url)) {
2954 break;
2956 $sub->pollinterval = $pollinterval;
2957 calendar_update_subscription($sub);
2959 // Update the events.
2960 return "<p>" . get_string('subscriptionupdated', 'calendar', $sub->name) . "</p>" .
2961 calendar_update_subscription_events($subscriptionid);
2962 case CALENDAR_SUBSCRIPTION_REMOVE:
2963 calendar_delete_subscription($subscriptionid);
2964 return get_string('subscriptionremoved', 'calendar', $sub->name);
2965 break;
2966 default:
2967 break;
2969 return '';
2973 * Delete subscription and all related events.
2975 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
2977 function calendar_delete_subscription($subscription) {
2978 global $DB;
2980 if (!is_object($subscription)) {
2981 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST);
2984 // Delete subscription and related events.
2985 $DB->delete_records('event', array('subscriptionid' => $subscription->id));
2986 $DB->delete_records('event_subscriptions', array('id' => $subscription->id));
2987 \cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id));
2989 // Trigger event, calendar subscription deleted.
2990 $eventparams = array('objectid' => $subscription->id,
2991 'context' => calendar_get_calendar_context($subscription),
2992 'other' => array(
2993 'eventtype' => $subscription->eventtype,
2996 switch ($subscription->eventtype) {
2997 case 'category':
2998 $eventparams['other']['categoryid'] = $subscription->categoryid;
2999 break;
3000 case 'course':
3001 $eventparams['other']['courseid'] = $subscription->courseid;
3002 break;
3003 case 'group':
3004 $eventparams['other']['courseid'] = $subscription->courseid;
3005 $eventparams['other']['groupid'] = $subscription->groupid;
3006 break;
3007 default:
3008 $eventparams['other']['courseid'] = $subscription->courseid;
3010 $event = \core\event\calendar_subscription_deleted::create($eventparams);
3011 $event->trigger();
3015 * From a URL, fetch the calendar and return an iCalendar object.
3017 * @param string $url The iCalendar URL
3018 * @return iCalendar The iCalendar object
3020 function calendar_get_icalendar($url) {
3021 global $CFG;
3023 require_once($CFG->libdir . '/filelib.php');
3025 $curl = new \curl();
3026 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
3027 $calendar = $curl->get($url);
3029 // Http code validation should actually be the job of curl class.
3030 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
3031 throw new \moodle_exception('errorinvalidicalurl', 'calendar');
3034 $ical = new \iCalendar();
3035 $ical->unserialize($calendar);
3037 return $ical;
3041 * Import events from an iCalendar object into a course calendar.
3043 * @param iCalendar $ical The iCalendar object.
3044 * @param int $courseid The course ID for the calendar.
3045 * @param int $subscriptionid The subscription ID.
3046 * @return string A log of the import progress, including errors.
3048 function calendar_import_icalendar_events($ical, $unused = null, $subscriptionid = null) {
3049 global $DB;
3051 $return = '';
3052 $eventcount = 0;
3053 $updatecount = 0;
3055 // Large calendars take a while...
3056 if (!CLI_SCRIPT) {
3057 \core_php_time_limit::raise(300);
3060 // Mark all events in a subscription with a zero timestamp.
3061 if (!empty($subscriptionid)) {
3062 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
3063 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3066 // Grab the timezone from the iCalendar file to be used later.
3067 if (isset($ical->properties['X-WR-TIMEZONE'][0]->value)) {
3068 $timezone = $ical->properties['X-WR-TIMEZONE'][0]->value;
3069 } else {
3070 $timezone = 'UTC';
3073 $return = '';
3074 foreach ($ical->components['VEVENT'] as $event) {
3075 $res = calendar_add_icalendar_event($event, null, $subscriptionid, $timezone);
3076 switch ($res) {
3077 case CALENDAR_IMPORT_EVENT_UPDATED:
3078 $updatecount++;
3079 break;
3080 case CALENDAR_IMPORT_EVENT_INSERTED:
3081 $eventcount++;
3082 break;
3083 case 0:
3084 $return .= '<p>' . get_string('erroraddingevent', 'calendar') . ': ';
3085 if (empty($event->properties['SUMMARY'])) {
3086 $return .= '(' . get_string('notitle', 'calendar') . ')';
3087 } else {
3088 $return .= $event->properties['SUMMARY'][0]->value;
3090 $return .= "</p>\n";
3091 break;
3095 $return .= "<p>" . get_string('eventsimported', 'calendar', $eventcount) . "</p> ";
3096 $return .= "<p>" . get_string('eventsupdated', 'calendar', $updatecount) . "</p>";
3098 // Delete remaining zero-marked events since they're not in remote calendar.
3099 if (!empty($subscriptionid)) {
3100 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3101 if (!empty($deletecount)) {
3102 $DB->delete_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3103 $return .= "<p> " . get_string('eventsdeleted', 'calendar') . ": {$deletecount} </p>\n";
3107 return $return;
3111 * Fetch a calendar subscription and update the events in the calendar.
3113 * @param int $subscriptionid The course ID for the calendar.
3114 * @return string A log of the import progress, including errors.
3116 function calendar_update_subscription_events($subscriptionid) {
3117 $sub = calendar_get_subscription($subscriptionid);
3119 // Don't update a file subscription.
3120 if (empty($sub->url)) {
3121 return 'File subscription not updated.';
3124 $ical = calendar_get_icalendar($sub->url);
3125 $return = calendar_import_icalendar_events($ical, null, $subscriptionid);
3126 $sub->lastupdated = time();
3128 calendar_update_subscription($sub);
3130 return $return;
3134 * Update a calendar subscription. Also updates the associated cache.
3136 * @param stdClass|array $subscription Subscription record.
3137 * @throws coding_exception If something goes wrong
3138 * @since Moodle 2.5
3140 function calendar_update_subscription($subscription) {
3141 global $DB;
3143 if (is_array($subscription)) {
3144 $subscription = (object)$subscription;
3146 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
3147 throw new \coding_exception('Cannot update a subscription without a valid id');
3150 $DB->update_record('event_subscriptions', $subscription);
3152 // Update cache.
3153 $cache = \cache::make('core', 'calendar_subscriptions');
3154 $cache->set($subscription->id, $subscription);
3156 // Trigger event, calendar subscription updated.
3157 $eventparams = array('userid' => $subscription->userid,
3158 'objectid' => $subscription->id,
3159 'context' => calendar_get_calendar_context($subscription),
3160 'other' => array(
3161 'eventtype' => $subscription->eventtype,
3164 switch ($subscription->eventtype) {
3165 case 'category':
3166 $eventparams['other']['categoryid'] = $subscription->categoryid;
3167 break;
3168 case 'course':
3169 $eventparams['other']['courseid'] = $subscription->courseid;
3170 break;
3171 case 'group':
3172 $eventparams['other']['courseid'] = $subscription->courseid;
3173 $eventparams['other']['groupid'] = $subscription->groupid;
3174 break;
3175 default:
3176 $eventparams['other']['courseid'] = $subscription->courseid;
3178 $event = \core\event\calendar_subscription_updated::create($eventparams);
3179 $event->trigger();
3183 * Checks to see if the user can edit a given subscription feed.
3185 * @param mixed $subscriptionorid Subscription object or id
3186 * @return bool true if current user can edit the subscription else false
3188 function calendar_can_edit_subscription($subscriptionorid) {
3189 if (is_array($subscriptionorid)) {
3190 $subscription = (object)$subscriptionorid;
3191 } else if (is_object($subscriptionorid)) {
3192 $subscription = $subscriptionorid;
3193 } else {
3194 $subscription = calendar_get_subscription($subscriptionorid);
3197 $allowed = new \stdClass;
3198 $courseid = $subscription->courseid;
3199 $categoryid = $subscription->categoryid;
3200 $groupid = $subscription->groupid;
3201 $category = null;
3203 if (!empty($categoryid)) {
3204 $category = \coursecat::get($categoryid);
3206 calendar_get_allowed_types($allowed, $courseid, null, $category);
3207 switch ($subscription->eventtype) {
3208 case 'user':
3209 return $allowed->user;
3210 case 'course':
3211 if (isset($allowed->courses[$courseid])) {
3212 return $allowed->courses[$courseid];
3213 } else {
3214 return false;
3216 case 'category':
3217 if (isset($allowed->categories[$categoryid])) {
3218 return $allowed->categories[$categoryid];
3219 } else {
3220 return false;
3222 case 'site':
3223 return $allowed->site;
3224 case 'group':
3225 if (isset($allowed->groups[$groupid])) {
3226 return $allowed->groups[$groupid];
3227 } else {
3228 return false;
3230 default:
3231 return false;
3236 * Helper function to determine the context of a calendar subscription.
3237 * Subscriptions can be created in two contexts COURSE, or USER.
3239 * @param stdClass $subscription
3240 * @return context instance
3242 function calendar_get_calendar_context($subscription) {
3243 // Determine context based on calendar type.
3244 if ($subscription->eventtype === 'site') {
3245 $context = \context_course::instance(SITEID);
3246 } else if ($subscription->eventtype === 'group' || $subscription->eventtype === 'course') {
3247 $context = \context_course::instance($subscription->courseid);
3248 } else {
3249 $context = \context_user::instance($subscription->userid);
3251 return $context;
3255 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
3257 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3259 * @return array
3261 function core_calendar_user_preferences() {
3262 $preferences = [];
3263 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED, 'default' => '0',
3264 'choices' => array('0', CALENDAR_TF_12, CALENDAR_TF_24)
3266 $preferences['calendar_startwday'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3267 'choices' => array(0, 1, 2, 3, 4, 5, 6));
3268 $preferences['calendar_maxevents'] = array('type' => PARAM_INT, 'choices' => range(1, 20));
3269 $preferences['calendar_lookahead'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 365,
3270 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3271 $preferences['calendar_persistflt'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3272 'choices' => array(0, 1));
3273 return $preferences;
3277 * Get legacy calendar events
3279 * @param int $tstart Start time of time range for events
3280 * @param int $tend End time of time range for events
3281 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3282 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3283 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3284 * @param boolean $withduration whether only events starting within time range selected
3285 * or events in progress/already started selected as well
3286 * @param boolean $ignorehidden whether to select only visible events or all events
3287 * @param array $categories array of category ids and/or objects.
3288 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3290 function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses,
3291 $withduration = true, $ignorehidden = true, $categories = []) {
3292 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3293 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3294 // parameters, but with the new API method, only null and arrays are accepted.
3295 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3296 // If parameter is true, return null.
3297 if ($param === true) {
3298 return null;
3301 // If parameter is false, return an empty array.
3302 if ($param === false) {
3303 return [];
3306 // If the parameter is a scalar value, enclose it in an array.
3307 if (!is_array($param)) {
3308 return [$param];
3311 // No normalisation required.
3312 return $param;
3313 }, [$users, $groups, $courses, $categories]);
3315 $mapper = \core_calendar\local\event\container::get_event_mapper();
3316 $events = \core_calendar\local\api::get_events(
3317 $tstart,
3318 $tend,
3319 null,
3320 null,
3321 null,
3322 null,
3324 null,
3325 $userparam,
3326 $groupparam,
3327 $courseparam,
3328 $categoryparam,
3329 $withduration,
3330 $ignorehidden
3333 return array_reduce($events, function($carry, $event) use ($mapper) {
3334 return $carry + [$event->get_id() => $mapper->from_event_to_stdclass($event)];
3335 }, []);
3340 * Get the calendar view output.
3342 * @param \calendar_information $calendar The calendar being represented
3343 * @param string $view The type of calendar to have displayed
3344 * @param bool $includenavigation Whether to include navigation
3345 * @return array[array, string]
3347 function calendar_get_view(\calendar_information $calendar, $view, $includenavigation = true) {
3348 global $PAGE, $CFG;
3350 $renderer = $PAGE->get_renderer('core_calendar');
3351 $type = \core_calendar\type_factory::get_calendar_instance();
3353 // Calculate the bounds of the month.
3354 $calendardate = $type->timestamp_to_date_array($calendar->time);
3356 $date = new \DateTime('now', core_date::get_user_timezone_object(99));
3357 $eventlimit = 200;
3359 if ($view === 'day') {
3360 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday']);
3361 $date->setTimestamp($tstart);
3362 $date->modify('+1 day');
3363 } else if ($view === 'upcoming' || $view === 'upcoming_mini') {
3364 // Number of days in the future that will be used to fetch events.
3365 if (isset($CFG->calendar_lookahead)) {
3366 $defaultlookahead = intval($CFG->calendar_lookahead);
3367 } else {
3368 $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD;
3370 $lookahead = get_user_preferences('calendar_lookahead', $defaultlookahead);
3372 // Maximum number of events to be displayed on upcoming view.
3373 $defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS;
3374 if (isset($CFG->calendar_maxevents)) {
3375 $defaultmaxevents = intval($CFG->calendar_maxevents);
3377 $eventlimit = get_user_preferences('calendar_maxevents', $defaultmaxevents);
3379 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday'],
3380 $calendardate['hours']);
3381 $date->setTimestamp($tstart);
3382 $date->modify('+' . $lookahead . ' days');
3383 } else {
3384 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], 1);
3385 $monthdays = $type->get_num_days_in_month($calendardate['year'], $calendardate['mon']);
3386 $date->setTimestamp($tstart);
3387 $date->modify('+' . $monthdays . ' days');
3389 if ($view === 'mini' || $view === 'minithree') {
3390 $template = 'core_calendar/calendar_mini';
3391 } else {
3392 $template = 'core_calendar/calendar_month';
3396 // We need to extract 1 second to ensure that we don't get into the next day.
3397 $date->modify('-1 second');
3398 $tend = $date->getTimestamp();
3400 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3401 // If parameter is true, return null.
3402 if ($param === true) {
3403 return null;
3406 // If parameter is false, return an empty array.
3407 if ($param === false) {
3408 return [];
3411 // If the parameter is a scalar value, enclose it in an array.
3412 if (!is_array($param)) {
3413 return [$param];
3416 // No normalisation required.
3417 return $param;
3418 }, [$calendar->users, $calendar->groups, $calendar->courses, $calendar->categories]);
3420 $events = \core_calendar\local\api::get_events(
3421 $tstart,
3422 $tend,
3423 null,
3424 null,
3425 null,
3426 null,
3427 $eventlimit,
3428 null,
3429 $userparam,
3430 $groupparam,
3431 $courseparam,
3432 $categoryparam,
3433 true,
3434 true,
3435 function ($event) {
3436 if ($proxy = $event->get_course_module()) {
3437 $cminfo = $proxy->get_proxied_instance();
3438 return $cminfo->uservisible;
3441 if ($proxy = $event->get_category()) {
3442 $category = $proxy->get_proxied_instance();
3444 return $category->is_uservisible();
3447 return true;
3451 $related = [
3452 'events' => $events,
3453 'cache' => new \core_calendar\external\events_related_objects_cache($events),
3454 'type' => $type,
3457 $data = [];
3458 if ($view == "month" || $view == "mini" || $view == "minithree") {
3459 $month = new \core_calendar\external\month_exporter($calendar, $type, $related);
3460 $month->set_includenavigation($includenavigation);
3461 $data = $month->export($renderer);
3462 } else if ($view == "day") {
3463 $day = new \core_calendar\external\calendar_day_exporter($calendar, $related);
3464 $data = $day->export($renderer);
3465 $template = 'core_calendar/calendar_day';
3466 } else if ($view == "upcoming" || $view == "upcoming_mini") {
3467 $upcoming = new \core_calendar\external\calendar_upcoming_exporter($calendar, $related);
3468 $data = $upcoming->export($renderer);
3470 if ($view == "upcoming") {
3471 $template = 'core_calendar/calendar_upcoming';
3472 } else if ($view == "upcoming_mini") {
3473 $template = 'core_calendar/calendar_upcoming_mini';
3477 return [$data, $template];
3481 * Request and render event form fragment.
3483 * @param array $args The fragment arguments.
3484 * @return string The rendered mform fragment.
3486 function calendar_output_fragment_event_form($args) {
3487 global $CFG, $OUTPUT, $USER;
3489 $html = '';
3490 $data = [];
3491 $eventid = isset($args['eventid']) ? clean_param($args['eventid'], PARAM_INT) : null;
3492 $starttime = isset($args['starttime']) ? clean_param($args['starttime'], PARAM_INT) : null;
3493 $courseid = isset($args['courseid']) ? clean_param($args['courseid'], PARAM_INT) : null;
3494 $categoryid = isset($args['categoryid']) ? clean_param($args['categoryid'], PARAM_INT) : null;
3495 $event = null;
3496 $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
3497 $context = \context_user::instance($USER->id);
3498 $editoroptions = \core_calendar\local\event\forms\create::build_editor_options($context);
3499 $formoptions = ['editoroptions' => $editoroptions];
3500 $draftitemid = 0;
3502 if ($hasformdata) {
3503 parse_str(clean_param($args['formdata'], PARAM_TEXT), $data);
3504 if (isset($data['description']['itemid'])) {
3505 $draftitemid = $data['description']['itemid'];
3509 if ($starttime) {
3510 $formoptions['starttime'] = $starttime;
3513 if (is_null($eventid)) {
3514 $mform = new \core_calendar\local\event\forms\create(
3515 null,
3516 $formoptions,
3517 'post',
3519 null,
3520 true,
3521 $data
3524 // Let's check first which event types user can add.
3525 calendar_get_allowed_types($allowed, $courseid);
3527 // If the user is on course context and is allowed to add course events set the event type default to course.
3528 if ($courseid != SITEID && !empty($allowed->courses)) {
3529 $data['eventtype'] = 'course';
3530 $data['courseid'] = $courseid;
3531 $data['groupcourseid'] = $courseid;
3532 } else if (!empty($categoryid) && !empty($allowed->category)) {
3533 $data['eventtype'] = 'category';
3534 $data['categoryid'] = $categoryid;
3536 $mform->set_data($data);
3537 } else {
3538 $event = calendar_event::load($eventid);
3539 $mapper = new \core_calendar\local\event\mappers\create_update_form_mapper();
3540 $eventdata = $mapper->from_legacy_event_to_data($event);
3541 $data = array_merge((array) $eventdata, $data);
3542 $event->count_repeats();
3543 $formoptions['event'] = $event;
3544 $data['description']['text'] = file_prepare_draft_area(
3545 $draftitemid,
3546 $event->context->id,
3547 'calendar',
3548 'event_description',
3549 $event->id,
3550 null,
3551 $data['description']['text']
3553 $data['description']['itemid'] = $draftitemid;
3555 $mform = new \core_calendar\local\event\forms\update(
3556 null,
3557 $formoptions,
3558 'post',
3560 null,
3561 true,
3562 $data
3564 $mform->set_data($data);
3566 // Check to see if this event is part of a subscription or import.
3567 // If so display a warning on edit.
3568 if (isset($event->subscriptionid) && ($event->subscriptionid != null)) {
3569 $renderable = new \core\output\notification(
3570 get_string('eventsubscriptioneditwarning', 'calendar'),
3571 \core\output\notification::NOTIFY_INFO
3574 $html .= $OUTPUT->render($renderable);
3578 if ($hasformdata) {
3579 $mform->is_validated();
3582 $html .= $mform->render();
3583 return $html;
3587 * Calculate the timestamp from the supplied Gregorian Year, Month, and Day.
3589 * @param int $d The day
3590 * @param int $m The month
3591 * @param int $y The year
3592 * @param int $time The timestamp to use instead of a separate y/m/d.
3593 * @return int The timestamp
3595 function calendar_get_timestamp($d, $m, $y, $time = 0) {
3596 // If a day, month and year were passed then convert it to a timestamp. If these were passed
3597 // then we can assume the day, month and year are passed as Gregorian, as no where in core
3598 // should we be passing these values rather than the time.
3599 if (!empty($d) && !empty($m) && !empty($y)) {
3600 if (checkdate($m, $d, $y)) {
3601 $time = make_timestamp($y, $m, $d);
3602 } else {
3603 $time = time();
3605 } else if (empty($time)) {
3606 $time = time();
3609 return $time;
3613 * Get the calendar footer options.
3615 * @param calendar_information $calendar The calendar information object.
3616 * @return array The data for template and template name.
3618 function calendar_get_footer_options($calendar) {
3619 global $CFG, $USER, $DB, $PAGE;
3621 // Generate hash for iCal link.
3622 $rawhash = $USER->id . $DB->get_field('user', 'password', ['id' => $USER->id]) . $CFG->calendar_exportsalt;
3623 $authtoken = sha1($rawhash);
3625 $renderer = $PAGE->get_renderer('core_calendar');
3626 $footer = new \core_calendar\external\footer_options_exporter($calendar, $USER->id, $authtoken);
3627 $data = $footer->export($renderer);
3628 $template = 'core_calendar/footer_options';
3630 return [$data, $template];
3634 * Get the list of potential calendar filter types as a type => name
3635 * combination.
3637 * @return array
3639 function calendar_get_filter_types() {
3640 $types = [
3641 'site',
3642 'category',
3643 'course',
3644 'group',
3645 'user',
3648 return array_map(function($type) {
3649 return [
3650 'eventtype' => $type,
3651 'name' => get_string("eventtype{$type}", "calendar"),
3653 }, $types);
3657 * Check whether the specified event type is valid.
3659 * @param string $type
3660 * @return bool
3662 function calendar_is_valid_eventtype($type) {
3663 $validtypes = [
3664 'user',
3665 'group',
3666 'course',
3667 'category',
3668 'site',
3670 return in_array($type, $validtypes);