Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.
/calendar/ -> lib.php (source)

Differences Between: [Versions 310 and 402] [Versions 311 and 402] [Versions 39 and 402] [Versions 400 and 402] [Versions 401 and 402] [Versions 402 and 403]

   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.
  13  //
  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/>.
  16  
  17  /**
  18   * Calendar extension
  19   *
  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
  24   */
  25  
  26  use core_external\external_api;
  27  
  28  if (!defined('MOODLE_INTERNAL')) {
  29      die('Direct access to this script is forbidden.');    ///  It must be included from a Moodle page
  30  }
  31  
  32  /**
  33   *  These are read by the administration component to provide default values
  34   */
  35  
  36  /**
  37   * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
  38   */
  39  define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
  40  
  41  /**
  42   * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
  43   */
  44  define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
  45  
  46  /**
  47   * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
  48   */
  49  define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
  50  
  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
  53  
  54  /**
  55   * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
  56   */
  57  define('CALENDAR_DEFAULT_WEEKEND', 65);
  58  
  59  /**
  60   * CALENDAR_URL - path to calendar's folder
  61   */
  62  define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
  63  
  64  /**
  65   * CALENDAR_TF_24 - Calendar time in 24 hours format
  66   */
  67  define('CALENDAR_TF_24', '%H:%M');
  68  
  69  /**
  70   * CALENDAR_TF_12 - Calendar time in 12 hours format
  71   */
  72  define('CALENDAR_TF_12', '%I:%M %p');
  73  
  74  /**
  75   * CALENDAR_EVENT_SITE - Site calendar event types
  76   */
  77  define('CALENDAR_EVENT_SITE', 1);
  78  
  79  /**
  80   * CALENDAR_EVENT_COURSE - Course calendar event types
  81   */
  82  define('CALENDAR_EVENT_COURSE', 2);
  83  
  84  /**
  85   * CALENDAR_EVENT_GROUP - group calendar event types
  86   */
  87  define('CALENDAR_EVENT_GROUP', 4);
  88  
  89  /**
  90   * CALENDAR_EVENT_USER - user calendar event types
  91   */
  92  define('CALENDAR_EVENT_USER', 8);
  93  
  94  /**
  95   * CALENDAR_EVENT_COURSECAT - Course category calendar event types
  96   */
  97  define('CALENDAR_EVENT_COURSECAT', 16);
  98  
  99  /**
 100   * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
 101   */
 102  define('CALENDAR_IMPORT_FROM_FILE', 0);
 103  
 104  /**
 105   * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
 106   */
 107  define('CALENDAR_IMPORT_FROM_URL',  1);
 108  
 109  /**
 110   * CALENDAR_IMPORT_EVENT_UPDATED_SKIPPED - imported event was skipped
 111   */
 112  define('CALENDAR_IMPORT_EVENT_SKIPPED',  -1);
 113  
 114  /**
 115   * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
 116   */
 117  define('CALENDAR_IMPORT_EVENT_UPDATED',  1);
 118  
 119  /**
 120   * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
 121   */
 122  define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
 123  
 124  /**
 125   * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
 126   */
 127  define('CALENDAR_SUBSCRIPTION_UPDATE', 1);
 128  
 129  /**
 130   * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
 131   */
 132  define('CALENDAR_SUBSCRIPTION_REMOVE', 2);
 133  
 134  /**
 135   * CALENDAR_EVENT_USER_OVERRIDE_PRIORITY - Constant for the user override priority.
 136   */
 137  define('CALENDAR_EVENT_USER_OVERRIDE_PRIORITY', 0);
 138  
 139  /**
 140   * CALENDAR_EVENT_TYPE_STANDARD - Standard events.
 141   */
 142  define('CALENDAR_EVENT_TYPE_STANDARD', 0);
 143  
 144  /**
 145   * CALENDAR_EVENT_TYPE_ACTION - Action events.
 146   */
 147  define('CALENDAR_EVENT_TYPE_ACTION', 1);
 148  
 149  /**
 150   * Manage calendar events.
 151   *
 152   * This class provides the required functionality in order to manage calendar events.
 153   * It was introduced as part of Moodle 2.0 and was created in order to provide a
 154   * better framework for dealing with calendar events in particular regard to file
 155   * handling through the new file API.
 156   *
 157   * @package    core_calendar
 158   * @category   calendar
 159   * @copyright  2009 Sam Hemelryk
 160   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 161   *
 162   * @property int $id The id within the event table
 163   * @property string $name The name of the event
 164   * @property string $description The description of the event
 165   * @property int $format The format of the description FORMAT_?
 166   * @property int $courseid The course the event is associated with (0 if none)
 167   * @property int $groupid The group the event is associated with (0 if none)
 168   * @property int $userid The user the event is associated with (0 if none)
 169   * @property int $repeatid If this is a repeated event this will be set to the
 170   *                          id of the original
 171   * @property string $component If created by a plugin/component (other than module), the full frankenstyle name of a component
 172   * @property string $modulename If added by a module this will be the module name
 173   * @property int $instance If added by a module this will be the module instance
 174   * @property string $eventtype The event type
 175   * @property int $timestart The start time as a timestamp
 176   * @property int $timeduration The duration of the event in seconds
 177   * @property int $timeusermidnight User midnight for the event
 178   * @property int $visible 1 if the event is visible
 179   * @property int $uuid ?
 180   * @property int $sequence ?
 181   * @property int $timemodified The time last modified as a timestamp
 182   */
 183  class calendar_event {
 184  
 185      /** @var stdClass An object containing the event properties can be accessed via the magic __get/set methods */
 186      protected $properties = null;
 187  
 188      /** @var string The converted event discription with file paths resolved.
 189       *              This gets populated when someone requests description for the first time */
 190      protected $_description = null;
 191  
 192      /** @var array The options to use with this description editor */
 193      protected $editoroptions = array(
 194          'subdirs' => false,
 195          'forcehttps' => false,
 196          'maxfiles' => -1,
 197          'maxbytes' => null,
 198          'trusttext' => false);
 199  
 200      /** @var object The context to use with the description editor */
 201      protected $editorcontext = null;
 202  
 203      /**
 204       * Instantiates a new event and optionally populates its properties with the data provided.
 205       *
 206       * @param \stdClass $data Optional. An object containing the properties to for
 207       *                  an event
 208       */
 209      public function __construct($data = null) {
 210          global $CFG, $USER;
 211  
 212          // First convert to object if it is not already (should either be object or assoc array).
 213          if (!is_object($data)) {
 214              $data = (object) $data;
 215          }
 216  
 217          $this->editoroptions['maxbytes'] = $CFG->maxbytes;
 218  
 219          $data->eventrepeats = 0;
 220  
 221          if (empty($data->id)) {
 222              $data->id = null;
 223          }
 224  
 225          if (!empty($data->subscriptionid)) {
 226              $data->subscription = calendar_get_subscription($data->subscriptionid);
 227          }
 228  
 229          // Default to a user event.
 230          if (empty($data->eventtype)) {
 231              $data->eventtype = 'user';
 232          }
 233  
 234          // Default to the current user.
 235          if (empty($data->userid)) {
 236              $data->userid = $USER->id;
 237          }
 238  
 239          if (!empty($data->timeduration) && is_array($data->timeduration)) {
 240              $data->timeduration = make_timestamp(
 241                      $data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'],
 242                      $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
 243          }
 244  
 245          if (!empty($data->description) && is_array($data->description)) {
 246              $data->format = $data->description['format'];
 247              $data->description = $data->description['text'];
 248          } else if (empty($data->description)) {
 249              $data->description = '';
 250              $data->format = editors_get_preferred_format();
 251          }
 252  
 253          // Ensure form is defaulted correctly.
 254          if (empty($data->format)) {
 255              $data->format = editors_get_preferred_format();
 256          }
 257  
 258          if (empty($data->component)) {
 259              $data->component = null;
 260          }
 261  
 262          $this->properties = $data;
 263      }
 264  
 265      /**
 266       * Magic set method.
 267       *
 268       * Attempts to call a set_$key method if one exists otherwise falls back
 269       * to simply set the property.
 270       *
 271       * @param string $key property name
 272       * @param mixed $value value of the property
 273       */
 274      public function __set($key, $value) {
 275          if (method_exists($this, 'set_'.$key)) {
 276              $this->{'set_'.$key}($value);
 277          }
 278          $this->properties->{$key} = $value;
 279      }
 280  
 281      /**
 282       * Magic get method.
 283       *
 284       * Attempts to call a get_$key method to return the property and ralls over
 285       * to return the raw property.
 286       *
 287       * @param string $key property name
 288       * @return mixed property value
 289       * @throws \coding_exception
 290       */
 291      public function __get($key) {
 292          if (method_exists($this, 'get_'.$key)) {
 293              return $this->{'get_'.$key}();
 294          }
 295          if (!property_exists($this->properties, $key)) {
 296              throw new \coding_exception('Undefined property requested');
 297          }
 298          return $this->properties->{$key};
 299      }
 300  
 301      /**
 302       * Magic isset method.
 303       *
 304       * PHP needs an isset magic method if you use the get magic method and
 305       * still want empty calls to work.
 306       *
 307       * @param string $key $key property name
 308       * @return bool|mixed property value, false if property is not exist
 309       */
 310      public function __isset($key) {
 311          return !empty($this->properties->{$key});
 312      }
 313  
 314      /**
 315       * Calculate the context value needed for an event.
 316       *
 317       * Event's type can be determine by the available value store in $data
 318       * It is important to check for the existence of course/courseid to determine
 319       * the course event.
 320       * Default value is set to CONTEXT_USER
 321       *
 322       * @return \stdClass The context object.
 323       */
 324      protected function calculate_context() {
 325          global $USER, $DB;
 326  
 327          $context = null;
 328          if (isset($this->properties->categoryid) && $this->properties->categoryid > 0) {
 329              $context = \context_coursecat::instance($this->properties->categoryid);
 330          } else if (isset($this->properties->courseid) && $this->properties->courseid > 0) {
 331              $context = \context_course::instance($this->properties->courseid);
 332          } else if (isset($this->properties->course) && $this->properties->course > 0) {
 333              $context = \context_course::instance($this->properties->course);
 334          } else if (isset($this->properties->groupid) && $this->properties->groupid > 0) {
 335              $group = $DB->get_record('groups', array('id' => $this->properties->groupid));
 336              $context = \context_course::instance($group->courseid);
 337          } else if (isset($this->properties->userid) && $this->properties->userid > 0
 338              && $this->properties->userid == $USER->id) {
 339              $context = \context_user::instance($this->properties->userid);
 340          } else if (isset($this->properties->userid) && $this->properties->userid > 0
 341              && $this->properties->userid != $USER->id &&
 342              !empty($this->properties->modulename) &&
 343              isset($this->properties->instance) && $this->properties->instance > 0) {
 344              $cm = get_coursemodule_from_instance($this->properties->modulename, $this->properties->instance, 0,
 345                  false, MUST_EXIST);
 346              $context = \context_course::instance($cm->course);
 347          } else {
 348              $context = \context_user::instance($this->properties->userid);
 349          }
 350  
 351          return $context;
 352      }
 353  
 354      /**
 355       * Returns the context for this event. The context is calculated
 356       * the first time is is requested and then stored in a member
 357       * variable to be returned each subsequent time.
 358       *
 359       * This is a magical getter function that will be called when
 360       * ever the context property is accessed, e.g. $event->context.
 361       *
 362       * @return context
 363       */
 364      protected function get_context() {
 365          if (!isset($this->properties->context)) {
 366              $this->properties->context = $this->calculate_context();
 367          }
 368  
 369          return $this->properties->context;
 370      }
 371  
 372      /**
 373       * Returns an array of editoroptions for this event.
 374       *
 375       * @return array event editor options
 376       */
 377      protected function get_editoroptions() {
 378          return $this->editoroptions;
 379      }
 380  
 381      /**
 382       * Returns an event description: Called by __get
 383       * Please use $blah = $event->description;
 384       *
 385       * @return string event description
 386       */
 387      protected function get_description() {
 388          global $CFG;
 389  
 390          require_once($CFG->libdir . '/filelib.php');
 391  
 392          if ($this->_description === null) {
 393              // Check if we have already resolved the context for this event.
 394              if ($this->editorcontext === null) {
 395                  // Switch on the event type to decide upon the appropriate context to use for this event.
 396                  $this->editorcontext = $this->get_context();
 397                  if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
 398                      return clean_text($this->properties->description, $this->properties->format);
 399                  }
 400              }
 401  
 402              // Work out the item id for the editor, if this is a repeated event
 403              // then the files will be associated with the original.
 404              if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
 405                  $itemid = $this->properties->repeatid;
 406              } else {
 407                  $itemid = $this->properties->id;
 408              }
 409  
 410              // Convert file paths in the description so that things display correctly.
 411              $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php',
 412                  $this->editorcontext->id, 'calendar', 'event_description', $itemid);
 413              // Clean the text so no nasties get through.
 414              $this->_description = clean_text($this->_description, $this->properties->format);
 415          }
 416  
 417          // Finally return the description.
 418          return $this->_description;
 419      }
 420  
 421      /**
 422       * Return the number of repeat events there are in this events series.
 423       *
 424       * @return int number of event repeated
 425       */
 426      public function count_repeats() {
 427          global $DB;
 428          if (!empty($this->properties->repeatid)) {
 429              $this->properties->eventrepeats = $DB->count_records('event',
 430                  array('repeatid' => $this->properties->repeatid));
 431              // We don't want to count ourselves.
 432              $this->properties->eventrepeats--;
 433          }
 434          return $this->properties->eventrepeats;
 435      }
 436  
 437      /**
 438       * Update or create an event within the database
 439       *
 440       * Pass in a object containing the event properties and this function will
 441       * insert it into the database and deal with any associated files
 442       *
 443       * Capability checking should be performed if the user is directly manipulating the event
 444       * and no other capability has been tested. However if the event is not being manipulated
 445       * directly by the user and another capability has been checked for them to do this then
 446       * capabilites should not be checked.
 447       *
 448       * For example if a user is editing an event in the calendar the check should be true,
 449       * but if you are updating an event in an activities settings are changed then the calendar
 450       * capabilites should not be checked.
 451       *
 452       * @see self::create()
 453       * @see self::update()
 454       *
 455       * @param \stdClass $data object of event
 456       * @param bool $checkcapability If Moodle should check the user can manage the calendar events for this call or not.
 457       * @return bool event updated
 458       */
 459      public function update($data, $checkcapability=true) {
 460          global $DB, $USER;
 461  
 462          foreach ($data as $key => $value) {
 463              $this->properties->$key = $value;
 464          }
 465  
 466          $this->properties->timemodified = time();
 467          $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
 468  
 469          // Prepare event data.
 470          $eventargs = array(
 471              'context' => $this->get_context(),
 472              'objectid' => $this->properties->id,
 473              'other' => array(
 474                  'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
 475                  'timestart' => $this->properties->timestart,
 476                  'name' => $this->properties->name
 477              )
 478          );
 479  
 480          if (empty($this->properties->id) || $this->properties->id < 1) {
 481              if ($checkcapability) {
 482                  if (!calendar_add_event_allowed($this->properties)) {
 483                      throw new \moodle_exception('nopermissiontoupdatecalendar');
 484                  }
 485              }
 486  
 487              if ($usingeditor) {
 488                  switch ($this->properties->eventtype) {
 489                      case 'user':
 490                          $this->properties->courseid = 0;
 491                          $this->properties->course = 0;
 492                          $this->properties->groupid = 0;
 493                          $this->properties->userid = $USER->id;
 494                          break;
 495                      case 'site':
 496                          $this->properties->courseid = SITEID;
 497                          $this->properties->course = SITEID;
 498                          $this->properties->groupid = 0;
 499                          $this->properties->userid = $USER->id;
 500                          break;
 501                      case 'course':
 502                          $this->properties->groupid = 0;
 503                          $this->properties->userid = $USER->id;
 504                          break;
 505                      case 'category':
 506                          $this->properties->groupid = 0;
 507                          $this->properties->category = 0;
 508                          $this->properties->userid = $USER->id;
 509                          break;
 510                      case 'group':
 511                          $this->properties->userid = $USER->id;
 512                          break;
 513                      default:
 514                          // We should NEVER get here, but just incase we do lets fail gracefully.
 515                          $usingeditor = false;
 516                          break;
 517                  }
 518  
 519                  // If we are actually using the editor, we recalculate the context because some default values
 520                  // were set when calculate_context() was called from the constructor.
 521                  if ($usingeditor) {
 522                      $this->properties->context = $this->calculate_context();
 523                      $this->editorcontext = $this->get_context();
 524                  }
 525  
 526                  $editor = $this->properties->description;
 527                  $this->properties->format = $this->properties->description['format'];
 528                  $this->properties->description = $this->properties->description['text'];
 529              }
 530  
 531              // Insert the event into the database.
 532              $this->properties->id = $DB->insert_record('event', $this->properties);
 533  
 534              if ($usingeditor) {
 535                  $this->properties->description = file_save_draft_area_files(
 536                      $editor['itemid'],
 537                      $this->editorcontext->id,
 538                      'calendar',
 539                      'event_description',
 540                      $this->properties->id,
 541                      $this->editoroptions,
 542                      $editor['text'],
 543                      $this->editoroptions['forcehttps']);
 544                  $DB->set_field('event', 'description', $this->properties->description,
 545                      array('id' => $this->properties->id));
 546              }
 547  
 548              // Log the event entry.
 549              $eventargs['objectid'] = $this->properties->id;
 550              $eventargs['context'] = $this->get_context();
 551              $event = \core\event\calendar_event_created::create($eventargs);
 552              $event->trigger();
 553  
 554              $repeatedids = array();
 555  
 556              if (!empty($this->properties->repeat)) {
 557                  $this->properties->repeatid = $this->properties->id;
 558                  $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id' => $this->properties->id));
 559  
 560                  $eventcopy = clone($this->properties);
 561                  unset($eventcopy->id);
 562  
 563                  $timestart = new \DateTime('@' . $eventcopy->timestart);
 564                  $timestart->setTimezone(\core_date::get_user_timezone_object());
 565  
 566                  for ($i = 1; $i < $eventcopy->repeats; $i++) {
 567  
 568                      $timestart->add(new \DateInterval('P7D'));
 569                      $eventcopy->timestart = $timestart->getTimestamp();
 570  
 571                      // Get the event id for the log record.
 572                      $eventcopyid = $DB->insert_record('event', $eventcopy);
 573  
 574                      // If the context has been set delete all associated files.
 575                      if ($usingeditor) {
 576                          $fs = get_file_storage();
 577                          $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description',
 578                              $this->properties->id);
 579                          foreach ($files as $file) {
 580                              $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
 581                          }
 582                      }
 583  
 584                      $repeatedids[] = $eventcopyid;
 585  
 586                      // Trigger an event.
 587                      $eventargs['objectid'] = $eventcopyid;
 588                      $eventargs['other']['timestart'] = $eventcopy->timestart;
 589                      $event = \core\event\calendar_event_created::create($eventargs);
 590                      $event->trigger();
 591                  }
 592              }
 593  
 594              return true;
 595          } else {
 596  
 597              if ($checkcapability) {
 598                  if (!calendar_edit_event_allowed($this->properties)) {
 599                      throw new \moodle_exception('nopermissiontoupdatecalendar');
 600                  }
 601              }
 602  
 603              if ($usingeditor) {
 604                  if ($this->editorcontext !== null) {
 605                      $this->properties->description = file_save_draft_area_files(
 606                          $this->properties->description['itemid'],
 607                          $this->editorcontext->id,
 608                          'calendar',
 609                          'event_description',
 610                          $this->properties->id,
 611                          $this->editoroptions,
 612                          $this->properties->description['text'],
 613                          $this->editoroptions['forcehttps']);
 614                  } else {
 615                      $this->properties->format = $this->properties->description['format'];
 616                      $this->properties->description = $this->properties->description['text'];
 617                  }
 618              }
 619  
 620              $event = $DB->get_record('event', array('id' => $this->properties->id));
 621  
 622              $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
 623  
 624              if ($updaterepeated) {
 625  
 626                  $sqlset = 'name = ?,
 627                             description = ?,
 628                             timeduration = ?,
 629                             timemodified = ?,
 630                             groupid = ?,
 631                             courseid = ?';
 632  
 633                  // Note: Group and course id may not be set. If not, keep their current values.
 634                  $params = [
 635                      $this->properties->name,
 636                      $this->properties->description,
 637                      $this->properties->timeduration,
 638                      time(),
 639                      isset($this->properties->groupid) ? $this->properties->groupid : $event->groupid,
 640                      isset($this->properties->courseid) ? $this->properties->courseid : $event->courseid,
 641                  ];
 642  
 643                  // Note: Only update start date, if it was changed by the user.
 644                  if ($this->properties->timestart != $event->timestart) {
 645                      $timestartoffset = $this->properties->timestart - $event->timestart;
 646                      $sqlset .= ', timestart = timestart + ?';
 647                      $params[] = $timestartoffset;
 648                  }
 649  
 650                  // Note: Only update location, if it was changed by the user.
 651                  $updatelocation = (!empty($this->properties->location) && $this->properties->location !== $event->location);
 652                  if ($updatelocation) {
 653                      $sqlset .= ', location = ?';
 654                      $params[] = $this->properties->location;
 655                  }
 656  
 657                  // Update all.
 658                  $sql = "UPDATE {event}
 659                             SET $sqlset
 660                           WHERE repeatid = ?";
 661  
 662                  $params[] = $event->repeatid;
 663                  $DB->execute($sql, $params);
 664  
 665                  // Trigger an update event for each of the calendar event.
 666                  $events = $DB->get_records('event', array('repeatid' => $event->repeatid), '', '*');
 667                  foreach ($events as $calendarevent) {
 668                      $eventargs['objectid'] = $calendarevent->id;
 669                      $eventargs['other']['timestart'] = $calendarevent->timestart;
 670                      $event = \core\event\calendar_event_updated::create($eventargs);
 671                      $event->add_record_snapshot('event', $calendarevent);
 672                      $event->trigger();
 673                  }
 674              } else {
 675                  $DB->update_record('event', $this->properties);
 676                  $event = self::load($this->properties->id);
 677                  $this->properties = $event->properties();
 678  
 679                  // Trigger an update event.
 680                  $event = \core\event\calendar_event_updated::create($eventargs);
 681                  $event->add_record_snapshot('event', $this->properties);
 682                  $event->trigger();
 683              }
 684  
 685              return true;
 686          }
 687      }
 688  
 689      /**
 690       * Deletes an event and if selected an repeated events in the same series
 691       *
 692       * This function deletes an event, any associated events if $deleterepeated=true,
 693       * and cleans up any files associated with the events.
 694       *
 695       * @see self::delete()
 696       *
 697       * @param bool $deleterepeated  delete event repeatedly
 698       * @return bool succession of deleting event
 699       */
 700      public function delete($deleterepeated = false) {
 701          global $DB;
 702  
 703          // If $this->properties->id is not set then something is wrong.
 704          if (empty($this->properties->id)) {
 705              debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
 706              return false;
 707          }
 708          $calevent = $DB->get_record('event',  array('id' => $this->properties->id), '*', MUST_EXIST);
 709          // Delete the event.
 710          $DB->delete_records('event', array('id' => $this->properties->id));
 711  
 712          // Trigger an event for the delete action.
 713          $eventargs = array(
 714              'context' => $this->get_context(),
 715              'objectid' => $this->properties->id,
 716              'other' => array(
 717                  'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
 718                  'timestart' => $this->properties->timestart,
 719                  'name' => $this->properties->name
 720              ));
 721          $event = \core\event\calendar_event_deleted::create($eventargs);
 722          $event->add_record_snapshot('event', $calevent);
 723          $event->trigger();
 724  
 725          // If we are deleting parent of a repeated event series, promote the next event in the series as parent.
 726          if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
 727              $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC",
 728                  array($this->properties->id), IGNORE_MULTIPLE);
 729              if (!empty($newparent)) {
 730                  $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?",
 731                      array($newparent, $this->properties->id));
 732                  // Get all records where the repeatid is the same as the event being removed.
 733                  $events = $DB->get_records('event', array('repeatid' => $newparent));
 734                  // For each of the returned events trigger an update event.
 735                  foreach ($events as $calendarevent) {
 736                      // Trigger an event for the update.
 737                      $eventargs['objectid'] = $calendarevent->id;
 738                      $eventargs['other']['timestart'] = $calendarevent->timestart;
 739                      $event = \core\event\calendar_event_updated::create($eventargs);
 740                      $event->add_record_snapshot('event', $calendarevent);
 741                      $event->trigger();
 742                  }
 743              }
 744          }
 745  
 746          // If the editor context hasn't already been set then set it now.
 747          if ($this->editorcontext === null) {
 748              $this->editorcontext = $this->get_context();
 749          }
 750  
 751          // If the context has been set delete all associated files.
 752          if ($this->editorcontext !== null) {
 753              $fs = get_file_storage();
 754              $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
 755              foreach ($files as $file) {
 756                  $file->delete();
 757              }
 758          }
 759  
 760          // If we need to delete repeated events then we will fetch them all and delete one by one.
 761          if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
 762              // Get all records where the repeatid is the same as the event being removed.
 763              $events = $DB->get_records('event', array('repeatid' => $this->properties->repeatid));
 764              // For each of the returned events populate an event object and call delete.
 765              // make sure the arg passed is false as we are already deleting all repeats.
 766              foreach ($events as $event) {
 767                  $event = new calendar_event($event);
 768                  $event->delete(false);
 769              }
 770          }
 771  
 772          return true;
 773      }
 774  
 775      /**
 776       * Fetch all event properties.
 777       *
 778       * This function returns all of the events properties as an object and optionally
 779       * can prepare an editor for the description field at the same time. This is
 780       * designed to work when the properties are going to be used to set the default
 781       * values of a moodle forms form.
 782       *
 783       * @param bool $prepareeditor If set to true a editor is prepared for use with
 784       *              the mforms editor element. (for description)
 785       * @return \stdClass Object containing event properties
 786       */
 787      public function properties($prepareeditor = false) {
 788          global $DB;
 789  
 790          // First take a copy of the properties. We don't want to actually change the
 791          // properties or we'd forever be converting back and forwards between an
 792          // editor formatted description and not.
 793          $properties = clone($this->properties);
 794          // Clean the description here.
 795          $properties->description = clean_text($properties->description, $properties->format);
 796  
 797          // If set to true we need to prepare the properties for use with an editor
 798          // and prepare the file area.
 799          if ($prepareeditor) {
 800  
 801              // We may or may not have a property id. If we do then we need to work
 802              // out the context so we can copy the existing files to the draft area.
 803              if (!empty($properties->id)) {
 804  
 805                  if ($properties->eventtype === 'site') {
 806                      // Site context.
 807                      $this->editorcontext = $this->get_context();
 808                  } else if ($properties->eventtype === 'user') {
 809                      // User context.
 810                      $this->editorcontext = $this->get_context();
 811                  } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
 812                      // First check the course is valid.
 813                      $course = $DB->get_record('course', array('id' => $properties->courseid));
 814                      if (!$course) {
 815                          throw new \moodle_exception('invalidcourse');
 816                      }
 817                      // Course context.
 818                      $this->editorcontext = $this->get_context();
 819                      // We have a course and are within the course context so we had
 820                      // better use the courses max bytes value.
 821                      $this->editoroptions['maxbytes'] = $course->maxbytes;
 822                  } else if ($properties->eventtype === 'category') {
 823                      // First check the course is valid.
 824                      \core_course_category::get($properties->categoryid, MUST_EXIST, true);
 825                      // Course context.
 826                      $this->editorcontext = $this->get_context();
 827                  } else {
 828                      // If we get here we have a custom event type as used by some
 829                      // modules. In this case the event will have been added by
 830                      // code and we won't need the editor.
 831                      $this->editoroptions['maxbytes'] = 0;
 832                      $this->editoroptions['maxfiles'] = 0;
 833                  }
 834  
 835                  if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
 836                      $contextid = false;
 837                  } else {
 838                      // Get the context id that is what we really want.
 839                      $contextid = $this->editorcontext->id;
 840                  }
 841              } else {
 842  
 843                  // If we get here then this is a new event in which case we don't need a
 844                  // context as there is no existing files to copy to the draft area.
 845                  $contextid = null;
 846              }
 847  
 848              // If the contextid === false we don't support files so no preparing
 849              // a draft area.
 850              if ($contextid !== false) {
 851                  // Just encase it has already been submitted.
 852                  $draftiddescription = file_get_submitted_draft_itemid('description');
 853                  // Prepare the draft area, this copies existing files to the draft area as well.
 854                  $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar',
 855                      'event_description', $properties->id, $this->editoroptions, $properties->description);
 856              } else {
 857                  $draftiddescription = 0;
 858              }
 859  
 860              // Structure the description field as the editor requires.
 861              $properties->description = array('text' => $properties->description, 'format' => $properties->format,
 862                  'itemid' => $draftiddescription);
 863          }
 864  
 865          // Finally return the properties.
 866          return $properties;
 867      }
 868  
 869      /**
 870       * Toggles the visibility of an event
 871       *
 872       * @param null|bool $force If it is left null the events visibility is flipped,
 873       *                   If it is false the event is made hidden, if it is true it
 874       *                   is made visible.
 875       * @return bool if event is successfully updated, toggle will be visible
 876       */
 877      public function toggle_visibility($force = null) {
 878          global $DB;
 879  
 880          // Set visible to the default if it is not already set.
 881          if (empty($this->properties->visible)) {
 882              $this->properties->visible = 1;
 883          }
 884  
 885          if ($force === true || ($force !== false && $this->properties->visible == 0)) {
 886              // Make this event visible.
 887              $this->properties->visible = 1;
 888          } else {
 889              // Make this event hidden.
 890              $this->properties->visible = 0;
 891          }
 892  
 893          // Update the database to reflect this change.
 894          $success = $DB->set_field('event', 'visible', $this->properties->visible, array('id' => $this->properties->id));
 895          $calendarevent = $DB->get_record('event',  array('id' => $this->properties->id), '*', MUST_EXIST);
 896  
 897          // Prepare event data.
 898          $eventargs = array(
 899              'context' => $this->get_context(),
 900              'objectid' => $this->properties->id,
 901              'other' => array(
 902                  'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
 903                  'timestart' => $this->properties->timestart,
 904                  'name' => $this->properties->name
 905              )
 906          );
 907          $event = \core\event\calendar_event_updated::create($eventargs);
 908          $event->add_record_snapshot('event', $calendarevent);
 909          $event->trigger();
 910  
 911          return $success;
 912      }
 913  
 914      /**
 915       * Returns an event object when provided with an event id.
 916       *
 917       * This function makes use of MUST_EXIST, if the event id passed in is invalid
 918       * it will result in an exception being thrown.
 919       *
 920       * @param int|object $param event object or event id
 921       * @return calendar_event
 922       */
 923      public static function load($param) {
 924          global $DB;
 925          if (is_object($param)) {
 926              $event = new calendar_event($param);
 927          } else {
 928              $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST);
 929              $event = new calendar_event($event);
 930          }
 931          return $event;
 932      }
 933  
 934      /**
 935       * Creates a new event and returns an event object.
 936       *
 937       * Capability checking should be performed if the user is directly creating the event
 938       * and no other capability has been tested. However if the event is not being created
 939       * directly by the user and another capability has been checked for them to do this then
 940       * capabilites should not be checked.
 941       *
 942       * For example if a user is creating an event in the calendar the check should be true,
 943       * but if you are creating an event in an activity when it is created then the calendar
 944       * capabilites should not be checked.
 945       *
 946       * @param \stdClass|array $properties An object containing event properties
 947       * @param bool $checkcapability If Moodle should check the user can manage the calendar events for this call or not.
 948       * @throws \coding_exception
 949       *
 950       * @return calendar_event|bool The event object or false if it failed
 951       */
 952      public static function create($properties, $checkcapability = true) {
 953          if (is_array($properties)) {
 954              $properties = (object)$properties;
 955          }
 956          if (!is_object($properties)) {
 957              throw new \coding_exception('When creating an event properties should be either an object or an assoc array');
 958          }
 959          $event = new calendar_event($properties);
 960          if ($event->update($properties, $checkcapability)) {
 961              return $event;
 962          } else {
 963              return false;
 964          }
 965      }
 966  
 967      /**
 968       * Format the event name using the external API.
 969       *
 970       * This function should we used when text formatting is required in external functions.
 971       *
 972       * @return string Formatted name.
 973       */
 974      public function format_external_name() {
 975          if ($this->editorcontext === null) {
 976              // Switch on the event type to decide upon the appropriate context to use for this event.
 977              $this->editorcontext = $this->get_context();
 978          }
 979  
 980          return \core_external\util::format_string($this->properties->name, $this->editorcontext->id);
 981      }
 982  
 983      /**
 984       * Format the text using the external API.
 985       *
 986       * This function should we used when text formatting is required in external functions.
 987       *
 988       * @return array an array containing the text formatted and the text format
 989       */
 990      public function format_external_text() {
 991  
 992          if ($this->editorcontext === null) {
 993              // Switch on the event type to decide upon the appropriate context to use for this event.
 994              $this->editorcontext = $this->get_context();
 995  
 996              if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
 997                  // We don't have a context here, do a normal format_text.
 998                  return \core_external\util::format_text(
 999                      $this->properties->description,
1000                      $this->properties->format,
1001                      $this->editorcontext
1002                  );
1003              }
1004          }
1005  
1006          // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
1007          if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
1008              $itemid = $this->properties->repeatid;
1009          } else {
1010              $itemid = $this->properties->id;
1011          }
1012  
1013          return \core_external\util::format_text(
1014              $this->properties->description,
1015              $this->properties->format,
1016              $this->editorcontext,
1017              'calendar',
1018              'event_description',
1019              $itemid
1020          );
1021      }
1022  }
1023  
1024  /**
1025   * Calendar information class
1026   *
1027   * This class is used simply to organise the information pertaining to a calendar
1028   * and is used primarily to make information easily available.
1029   *
1030   * @package core_calendar
1031   * @category calendar
1032   * @copyright 2010 Sam Hemelryk
1033   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1034   */
1035  class calendar_information {
1036  
1037      /**
1038       * @var int The timestamp
1039       *
1040       * Rather than setting the day, month and year we will set a timestamp which will be able
1041       * to be used by multiple calendars.
1042       */
1043      public $time;
1044  
1045      /** @var int A course id */
1046      public $courseid = null;
1047  
1048      /** @var array An array of categories */
1049      public $categories = array();
1050  
1051      /** @var int The current category */
1052      public $categoryid = null;
1053  
1054      /** @var array An array of courses */
1055      public $courses = array();
1056  
1057      /** @var array An array of groups */
1058      public $groups = array();
1059  
1060      /** @var array An array of users */
1061      public $users = array();
1062  
1063      /** @var context The anticipated context that the calendar is viewed in */
1064      public $context = null;
1065  
1066      /** @var string The calendar's view mode. */
1067      protected $viewmode;
1068  
1069      /** @var \stdClass course data. */
1070      public $course;
1071  
1072      /** @var int day. */
1073      protected $day;
1074  
1075      /** @var int month. */
1076      protected $month;
1077  
1078      /** @var int year. */
1079      protected $year;
1080  
1081      /**
1082       * Creates a new instance
1083       *
1084       * @param int $day the number of the day
1085       * @param int $month the number of the month
1086       * @param int $year the number of the year
1087       * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
1088       *     and $calyear to support multiple calendars
1089       */
1090      public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
1091          // If a day, month and year were passed then convert it to a timestamp. If these were passed
1092          // then we can assume the day, month and year are passed as Gregorian, as no where in core
1093          // should we be passing these values rather than the time. This is done for BC.
1094          if (!empty($day) || !empty($month) || !empty($year)) {
1095              $date = usergetdate(time());
1096              if (empty($day)) {
1097                  $day = $date['mday'];
1098              }
1099              if (empty($month)) {
1100                  $month = $date['mon'];
1101              }
1102              if (empty($year)) {
1103                  $year =  $date['year'];
1104              }
1105              if (checkdate($month, $day, $year)) {
1106                  $time = make_timestamp($year, $month, $day);
1107              } else {
1108                  $time = time();
1109              }
1110          }
1111  
1112          $this->set_time($time);
1113      }
1114  
1115      /**
1116       * Creates and set up a instance.
1117       *
1118       * @param   int                     $time the unixtimestamp representing the date we want to view.
1119       * @param   int                     $courseid The ID of the course the user wishes to view.
1120       * @param   int                     $categoryid The ID of the category the user wishes to view
1121       *                                  If a courseid is specified, this value is ignored.
1122       * @return  calendar_information
1123       */
1124      public static function create($time, int $courseid, int $categoryid = null) : calendar_information {
1125          $calendar = new static(0, 0, 0, $time);
1126          if ($courseid != SITEID && !empty($courseid)) {
1127              // Course ID must be valid and existing.
1128              $course = get_course($courseid);
1129              $calendar->context = context_course::instance($course->id);
1130  
1131              if (!$course->visible && !is_role_switched($course->id)) {
1132                  require_capability('moodle/course:viewhiddencourses', $calendar->context);
1133              }
1134  
1135              $courses = [$course->id => $course];
1136              $category = (\core_course_category::get($course->category, MUST_EXIST, true))->get_db_record();
1137          } else if (!empty($categoryid)) {
1138              $course = get_site();
1139              $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1140  
1141              // Filter available courses to those within this category or it's children.
1142              $ids = [$categoryid];
1143              $category = \core_course_category::get($categoryid);
1144              $ids = array_merge($ids, array_keys($category->get_children()));
1145              $courses = array_filter($courses, function($course) use ($ids) {
1146                  return array_search($course->category, $ids) !== false;
1147              });
1148              $category = $category->get_db_record();
1149  
1150              $calendar->context = context_coursecat::instance($categoryid);
1151          } else {
1152              $course = get_site();
1153              $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1154              $category = null;
1155  
1156              $calendar->context = context_system::instance();
1157          }
1158  
1159          $calendar->set_sources($course, $courses, $category);
1160  
1161          return $calendar;
1162      }
1163  
1164      /**
1165       * Set the time period of this instance.
1166       *
1167       * @param   int $time the unixtimestamp representing the date we want to view.
1168       * @return  $this
1169       */
1170      public function set_time($time = null) {
1171          if (empty($time)) {
1172              $this->time = time();
1173          } else {
1174              $this->time = $time;
1175          }
1176  
1177          return $this;
1178      }
1179  
1180      /**
1181       * Initialize calendar information
1182       *
1183       * @deprecated 3.4
1184       * @param stdClass $course object
1185       * @param array $coursestoload An array of courses [$course->id => $course]
1186       * @param bool $ignorefilters options to use filter
1187       */
1188      public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
1189          debugging('The prepare_for_view() function has been deprecated. Please update your code to use set_sources()',
1190                  DEBUG_DEVELOPER);
1191          $this->set_sources($course, $coursestoload);
1192      }
1193  
1194      /**
1195       * Set the sources for events within the calendar.
1196       *
1197       * If no category is provided, then the category path for the current
1198       * course will be used.
1199       *
1200       * @param   stdClass    $course The current course being viewed.
1201       * @param   stdClass[]  $courses The list of all courses currently accessible.
1202       * @param   stdClass    $category The current category to show.
1203       */
1204      public function set_sources(stdClass $course, array $courses, stdClass $category = null) {
1205          global $USER;
1206  
1207          // A cousre must always be specified.
1208          $this->course = $course;
1209          $this->courseid = $course->id;
1210  
1211          list($courseids, $group, $user) = calendar_set_filters($courses);
1212          $this->courses = $courseids;
1213          $this->groups = $group;
1214          $this->users = $user;
1215  
1216          // Do not show category events by default.
1217          $this->categoryid = null;
1218          $this->categories = null;
1219  
1220          // Determine the correct category information to show.
1221          // When called with a course, the category of that course is usually included too.
1222          // When a category was specifically requested, it should be requested with the site id.
1223          if (SITEID !== $this->courseid) {
1224              // A specific course was requested.
1225              // Fetch the category that this course is in, along with all parents.
1226              // Do not include child categories of this category, as the user many not have enrolments in those siblings or children.
1227              $category = \core_course_category::get($course->category, MUST_EXIST, true);
1228              $this->categoryid = $category->id;
1229  
1230              $this->categories = $category->get_parents();
1231              $this->categories[] = $category->id;
1232          } else if (null !== $category && $category->id > 0) {
1233              // A specific category was requested.
1234              // Fetch all parents of this category, along with all children too.
1235              $category = \core_course_category::get($category->id);
1236              $this->categoryid = $category->id;
1237  
1238              // Build the category list.
1239              // This includes the current category.
1240              $this->categories = $category->get_parents();
1241              $this->categories[] = $category->id;
1242              $this->categories = array_merge($this->categories, $category->get_all_children_ids());
1243          } else if (SITEID === $this->courseid) {
1244              // The site was requested.
1245              // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
1246  
1247              // Grab the list of categories that this user has courses in.
1248              $coursecategories = array_flip(array_map(function($course) {
1249                  return $course->category;
1250              }, $courses));
1251  
1252              $calcatcache = cache::make('core', 'calendar_categories');
1253              $this->categories = $calcatcache->get('site');
1254              if ($this->categories === false) {
1255                  // Use the category id as the key in the following array. That way we do not have to remove duplicates.
1256                  $categories = [];
1257                  foreach (\core_course_category::get_all() as $category) {
1258                      if (isset($coursecategories[$category->id]) ||
1259                              has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
1260                          // If the user has access to a course in this category or can manage the category,
1261                          // then they can see all parent categories too.
1262                          $categories[$category->id] = true;
1263                          foreach ($category->get_parents() as $catid) {
1264                              $categories[$catid] = true;
1265                          }
1266                      }
1267                  }
1268                  $this->categories = array_keys($categories);
1269                  $calcatcache->set('site', $this->categories);
1270              }
1271          }
1272      }
1273  
1274      /**
1275       * Ensures the date for the calendar is correct and either sets it to now
1276       * or throws a moodle_exception if not
1277       *
1278       * @param bool $defaultonow use current time
1279       * @throws moodle_exception
1280       * @return bool validation of checkdate
1281       */
1282      public function checkdate($defaultonow = true) {
1283          if (!checkdate($this->month, $this->day, $this->year)) {
1284              if ($defaultonow) {
1285                  $now = usergetdate(time());
1286                  $this->day = intval($now['mday']);
1287                  $this->month = intval($now['mon']);
1288                  $this->year = intval($now['year']);
1289                  return true;
1290              } else {
1291                  throw new moodle_exception('invaliddate');
1292              }
1293          }
1294          return true;
1295      }
1296  
1297      /**
1298       * Gets todays timestamp for the calendar
1299       *
1300       * @return int today timestamp
1301       */
1302      public function timestamp_today() {
1303          return $this->time;
1304      }
1305      /**
1306       * Gets tomorrows timestamp for the calendar
1307       *
1308       * @return int tomorrow timestamp
1309       */
1310      public function timestamp_tomorrow() {
1311          return strtotime('+1 day', $this->time);
1312      }
1313      /**
1314       * Adds the pretend blocks for the calendar
1315       *
1316       * @param core_calendar_renderer $renderer
1317       * @param bool $showfilters display filters, false is set as default
1318       * @param string|null $view preference view options (eg: day, month, upcoming)
1319       */
1320      public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
1321          global $PAGE;
1322  
1323          if (!has_capability('moodle/block:view', $PAGE->context) ) {
1324              return;
1325          }
1326  
1327          if ($showfilters) {
1328              $filters = new block_contents();
1329              $filters->content = $renderer->event_filter();
1330              $filters->footer = '';
1331              $filters->title = get_string('eventskey', 'calendar');
1332              $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
1333          }
1334      }
1335  
1336      /**
1337       * Getter method for the calendar's view mode.
1338       *
1339       * @return string
1340       */
1341      public function get_viewmode(): string {
1342          return $this->viewmode;
1343      }
1344  
1345      /**
1346       * Setter method for the calendar's view mode.
1347       *
1348       * @param string $viewmode
1349       */
1350      public function set_viewmode(string $viewmode): void {
1351          $this->viewmode = $viewmode;
1352      }
1353  }
1354  
1355  /**
1356   * Get calendar events.
1357   *
1358   * @param int $tstart Start time of time range for events
1359   * @param int $tend End time of time range for events
1360   * @param array|int|boolean $users array of users, user id or boolean for all/no user events
1361   * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
1362   * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
1363   * @param boolean $withduration whether only events starting within time range selected
1364   *                              or events in progress/already started selected as well
1365   * @param boolean $ignorehidden whether to select only visible events or all events
1366   * @param array|int|boolean $categories array of categories, category id or boolean for all/no course events
1367   * @return array $events of selected events or an empty array if there aren't any (or there was an error)
1368   */
1369  function calendar_get_events($tstart, $tend, $users, $groups, $courses,
1370          $withduration = true, $ignorehidden = true, $categories = []) {
1371      global $DB;
1372  
1373      $whereclause = '';
1374      $params = array();
1375      // Quick test.
1376      if (empty($users) && empty($groups) && empty($courses) && empty($categories)) {
1377          return array();
1378      }
1379  
1380      if ((is_array($users) && !empty($users)) or is_numeric($users)) {
1381          // Events from a number of users
1382          if(!empty($whereclause)) $whereclause .= ' OR';
1383          list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED);
1384          $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)";
1385          $params = array_merge($params, $inparamsusers);
1386      } else if($users === true) {
1387          // Events from ALL users
1388          if(!empty($whereclause)) $whereclause .= ' OR';
1389          $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)';
1390      } else if($users === false) {
1391          // No user at all, do nothing
1392      }
1393  
1394      if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
1395          // Events from a number of groups
1396          if(!empty($whereclause)) $whereclause .= ' OR';
1397          list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED);
1398          $whereclause .= " e.groupid $insqlgroups ";
1399          $params = array_merge($params, $inparamsgroups);
1400      } else if($groups === true) {
1401          // Events from ALL groups
1402          if(!empty($whereclause)) $whereclause .= ' OR ';
1403          $whereclause .= ' e.groupid != 0';
1404      }
1405      // boolean false (no groups at all): we don't need to do anything
1406  
1407      if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
1408          if(!empty($whereclause)) $whereclause .= ' OR';
1409          list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED);
1410          $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
1411          $params = array_merge($params, $inparamscourses);
1412      } else if ($courses === true) {
1413          // Events from ALL courses
1414          if(!empty($whereclause)) $whereclause .= ' OR';
1415          $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
1416      }
1417  
1418      if ((is_array($categories) && !empty($categories)) || is_numeric($categories)) {
1419          if (!empty($whereclause)) {
1420              $whereclause .= ' OR';
1421          }
1422          list($insqlcategories, $inparamscategories) = $DB->get_in_or_equal($categories, SQL_PARAMS_NAMED);
1423          $whereclause .= " (e.groupid = 0 AND e.courseid = 0 AND e.categoryid $insqlcategories)";
1424          $params = array_merge($params, $inparamscategories);
1425      } else if ($categories === true) {
1426          // Events from ALL categories.
1427          if (!empty($whereclause)) {
1428              $whereclause .= ' OR';
1429          }
1430          $whereclause .= ' (e.groupid = 0 AND e.courseid = 0 AND e.categoryid != 0)';
1431      }
1432  
1433      // Security check: if, by now, we have NOTHING in $whereclause, then it means
1434      // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
1435      // events no matter what. Allowing the code to proceed might return a completely
1436      // valid query with only time constraints, thus selecting ALL events in that time frame!
1437      if(empty($whereclause)) {
1438          return array();
1439      }
1440  
1441      if($withduration) {
1442          $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1443      }
1444      else {
1445          $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1446      }
1447      if(!empty($whereclause)) {
1448          // We have additional constraints
1449          $whereclause = $timeclause.' AND ('.$whereclause.')';
1450      }
1451      else {
1452          // Just basic time filtering
1453          $whereclause = $timeclause;
1454      }
1455  
1456      if ($ignorehidden) {
1457          $whereclause .= ' AND e.visible = 1';
1458      }
1459  
1460      $sql = "SELECT e.*
1461                FROM {event} e
1462           LEFT JOIN {modules} m ON e.modulename = m.name
1463                  -- Non visible modules will have a value of 0.
1464               WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
1465            ORDER BY e.timestart";
1466      $events = $DB->get_records_sql($sql, $params);
1467  
1468      if ($events === false) {
1469          $events = array();
1470      }
1471      return $events;
1472  }
1473  
1474  /**
1475   * Return the days of the week.
1476   *
1477   * @return array array of days
1478   */
1479  function calendar_get_days() {
1480      $calendartype = \core_calendar\type_factory::get_calendar_instance();
1481      return $calendartype->get_weekdays();
1482  }
1483  
1484  /**
1485   * Get the subscription from a given id.
1486   *
1487   * @since Moodle 2.5
1488   * @param int $id id of the subscription
1489   * @return stdClass Subscription record from DB
1490   * @throws moodle_exception for an invalid id
1491   */
1492  function calendar_get_subscription($id) {
1493      global $DB;
1494  
1495      $cache = \cache::make('core', 'calendar_subscriptions');
1496      $subscription = $cache->get($id);
1497      if (empty($subscription)) {
1498          $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
1499          $cache->set($id, $subscription);
1500      }
1501  
1502      return $subscription;
1503  }
1504  
1505  /**
1506   * Gets the first day of the week.
1507   *
1508   * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
1509   *
1510   * @return int
1511   */
1512  function calendar_get_starting_weekday() {
1513      $calendartype = \core_calendar\type_factory::get_calendar_instance();
1514      return $calendartype->get_starting_weekday();
1515  }
1516  
1517  /**
1518   * Get a HTML link to a course.
1519   *
1520   * @param int|stdClass $course the course id or course object
1521   * @return string a link to the course (as HTML); empty if the course id is invalid
1522   */
1523  function calendar_get_courselink($course) {
1524      if (!$course) {
1525          return '';
1526      }
1527  
1528      if (!is_object($course)) {
1529          $course = calendar_get_course_cached($coursecache, $course);
1530      }
1531      $context = \context_course::instance($course->id);
1532      $fullname = format_string($course->fullname, true, array('context' => $context));
1533      $url = new \moodle_url('/course/view.php', array('id' => $course->id));
1534      $link = \html_writer::link($url, $fullname);
1535  
1536      return $link;
1537  }
1538  
1539  /**
1540   * Get current module cache.
1541   *
1542   * Only use this method if you do not know courseid. Otherwise use:
1543   * get_fast_modinfo($courseid)->instances[$modulename][$instance]
1544   *
1545   * @param array $modulecache in memory module cache
1546   * @param string $modulename name of the module
1547   * @param int $instance module instance number
1548   * @return stdClass|bool $module information
1549   */
1550  function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
1551      if (!isset($modulecache[$modulename . '_' . $instance])) {
1552          $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
1553      }
1554  
1555      return $modulecache[$modulename . '_' . $instance];
1556  }
1557  
1558  /**
1559   * Get current course cache.
1560   *
1561   * @param array $coursecache list of course cache
1562   * @param int $courseid id of the course
1563   * @return stdClass $coursecache[$courseid] return the specific course cache
1564   */
1565  function calendar_get_course_cached(&$coursecache, $courseid) {
1566      if (!isset($coursecache[$courseid])) {
1567          $coursecache[$courseid] = get_course($courseid);
1568      }
1569      return $coursecache[$courseid];
1570  }
1571  
1572  /**
1573   * Get group from groupid for calendar display
1574   *
1575   * @param int $groupid
1576   * @return stdClass group object with fields 'id', 'name' and 'courseid'
1577   */
1578  function calendar_get_group_cached($groupid) {
1579      static $groupscache = array();
1580      if (!isset($groupscache[$groupid])) {
1581          $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1582      }
1583      return $groupscache[$groupid];
1584  }
1585  
1586  /**
1587   * Add calendar event metadata
1588   *
1589   * @deprecated since 3.9
1590   *
1591   * @param stdClass $event event info
1592   * @return stdClass $event metadata
1593   */
1594  function calendar_add_event_metadata($event) {
1595      debugging('This function is no longer used', DEBUG_DEVELOPER);
1596      global $CFG, $OUTPUT;
1597  
1598      // Support multilang in event->name.
1599      $event->name = format_string($event->name, true);
1600  
1601      if (!empty($event->modulename)) { // Activity event.
1602          // The module name is set. I will assume that it has to be displayed, and
1603          // also that it is an automatically-generated event. And of course that the
1604          // instace id and modulename are set correctly.
1605          $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
1606          if (!array_key_exists($event->instance, $instances)) {
1607              return;
1608          }
1609          $module = $instances[$event->instance];
1610  
1611          $modulename = $module->get_module_type_name(false);
1612          if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
1613              // Will be used as alt text if the event icon.
1614              $eventtype = get_string($event->eventtype, $event->modulename);
1615          } else {
1616              $eventtype = '';
1617          }
1618  
1619          $event->icon = '<img src="' . s($module->get_icon_url()) . '" alt="' . s($eventtype) .
1620              '" title="' . s($modulename) . '" class="icon" />';
1621          $event->referer = html_writer::link($module->url, $event->name);
1622          $event->courselink = calendar_get_courselink($module->get_course());
1623          $event->cmid = $module->id;
1624      } else if ($event->courseid == SITEID) { // Site event.
1625          $event->icon = '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
1626              get_string('siteevent', 'calendar') . '" class="icon" />';
1627          $event->cssclass = 'calendar_event_site';
1628      } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event.
1629          $event->icon = '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
1630              get_string('courseevent', 'calendar') . '" class="icon" />';
1631          $event->courselink = calendar_get_courselink($event->courseid);
1632          $event->cssclass = 'calendar_event_course';
1633      } else if ($event->groupid) { // Group event.
1634          if ($group = calendar_get_group_cached($event->groupid)) {
1635              $groupname = format_string($group->name, true, \context_course::instance($group->courseid));
1636          } else {
1637              $groupname = '';
1638          }
1639          $event->icon = \html_writer::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
1640              'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
1641          $event->courselink = calendar_get_courselink($event->courseid) . ', ' . $groupname;
1642          $event->cssclass = 'calendar_event_group';
1643      } else if ($event->userid) { // User event.
1644          $event->icon = '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
1645              get_string('userevent', 'calendar') . '" class="icon" />';
1646          $event->cssclass = 'calendar_event_user';
1647      }
1648  
1649      return $event;
1650  }
1651  
1652  /**
1653   * Get calendar events by id.
1654   *
1655   * @since Moodle 2.5
1656   * @param array $eventids list of event ids
1657   * @return array Array of event entries, empty array if nothing found
1658   */
1659  function calendar_get_events_by_id($eventids) {
1660      global $DB;
1661  
1662      if (!is_array($eventids) || empty($eventids)) {
1663          return array();
1664      }
1665  
1666      list($wheresql, $params) = $DB->get_in_or_equal($eventids);
1667      $wheresql = "id $wheresql";
1668  
1669      return $DB->get_records_select('event', $wheresql, $params);
1670  }
1671  
1672  /**
1673   * Get control options for calendar.
1674   *
1675   * @param string $type of calendar
1676   * @param array $data calendar information
1677   * @return string $content return available control for the calender in html
1678   */
1679  function calendar_top_controls($type, $data) {
1680      global $PAGE, $OUTPUT;
1681  
1682      // Get the calendar type we are using.
1683      $calendartype = \core_calendar\type_factory::get_calendar_instance();
1684  
1685      $content = '';
1686  
1687      // Ensure course id passed if relevant.
1688      $courseid = '';
1689      if (!empty($data['id'])) {
1690          $courseid = '&amp;course=' . $data['id'];
1691      }
1692  
1693      // If we are passing a month and year then we need to convert this to a timestamp to
1694      // support multiple calendars. No where in core should these be passed, this logic
1695      // here is for third party plugins that may use this function.
1696      if (!empty($data['m']) && !empty($date['y'])) {
1697          if (!isset($data['d'])) {
1698              $data['d'] = 1;
1699          }
1700          if (!checkdate($data['m'], $data['d'], $data['y'])) {
1701              $time = time();
1702          } else {
1703              $time = make_timestamp($data['y'], $data['m'], $data['d']);
1704          }
1705      } else if (!empty($data['time'])) {
1706          $time = $data['time'];
1707      } else {
1708          $time = time();
1709      }
1710  
1711      // Get the date for the calendar type.
1712      $date = $calendartype->timestamp_to_date_array($time);
1713  
1714      $urlbase = $PAGE->url;
1715  
1716      // We need to get the previous and next months in certain cases.
1717      if ($type == 'frontpage' || $type == 'course' || $type == 'month') {
1718          $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1719          $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
1720          $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
1721              $prevmonthtime['hour'], $prevmonthtime['minute']);
1722  
1723          $nextmonth = calendar_add_month($date['mon'], $date['year']);
1724          $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
1725          $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
1726              $nextmonthtime['hour'], $nextmonthtime['minute']);
1727      }
1728  
1729      switch ($type) {
1730          case 'frontpage':
1731              $prevlink = calendar_get_link_previous(get_string('monthprev', 'calendar'), $urlbase, false, false, false,
1732                  true, $prevmonthtime);
1733              $nextlink = calendar_get_link_next(get_string('monthnext', 'calendar'), $urlbase, false, false, false, true,
1734                  $nextmonthtime);
1735              $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1736                  false, false, false, $time);
1737  
1738              if (!empty($data['id'])) {
1739                  $calendarlink->param('course', $data['id']);
1740              }
1741  
1742              $right = $nextlink;
1743  
1744              $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1745              $content .= $prevlink . '<span class="hide"> | </span>';
1746              $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1747                  userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1748              ), array('class' => 'current'));
1749              $content .= '<span class="hide"> | </span>' . $right;
1750              $content .= "<span class=\"clearer\"><!-- --></span>\n";
1751              $content .= \html_writer::end_tag('div');
1752  
1753              break;
1754          case 'course':
1755              $prevlink = calendar_get_link_previous(get_string('monthprev', 'calendar'), $urlbase, false, false, false,
1756                  true, $prevmonthtime);
1757              $nextlink = calendar_get_link_next(get_string('monthnext', 'calendar'), $urlbase, false, false, false,
1758                  true, $nextmonthtime);
1759              $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1760                  false, false, false, $time);
1761  
1762              if (!empty($data['id'])) {
1763                  $calendarlink->param('course', $data['id']);
1764              }
1765  
1766              $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1767              $content .= $prevlink . '<span class="hide"> | </span>';
1768              $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1769                  userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1770              ), array('class' => 'current'));
1771              $content .= '<span class="hide"> | </span>' . $nextlink;
1772              $content .= "<span class=\"clearer\"><!-- --></span>";
1773              $content .= \html_writer::end_tag('div');
1774              break;
1775          case 'upcoming':
1776              $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'upcoming')),
1777                  false, false, false, $time);
1778              if (!empty($data['id'])) {
1779                  $calendarlink->param('course', $data['id']);
1780              }
1781              $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1782              $content .= \html_writer::tag('div', $calendarlink, array('class' => 'centered'));
1783              break;
1784          case 'display':
1785              $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1786                  false, false, false, $time);
1787              if (!empty($data['id'])) {
1788                  $calendarlink->param('course', $data['id']);
1789              }
1790              $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1791              $content .= \html_writer::tag('h3', $calendarlink);
1792              break;
1793          case 'month':
1794              $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1795                  'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $prevmonthtime);
1796              $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1797                  'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $nextmonthtime);
1798  
1799              $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1800              $content .= $prevlink . '<span class="hide"> | </span>';
1801              $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1802              $content .= '<span class="hide"> | </span>' . $nextlink;
1803              $content .= '<span class="clearer"><!-- --></span>';
1804              $content .= \html_writer::end_tag('div')."\n";
1805              break;
1806          case 'day':
1807              $days = calendar_get_days();
1808  
1809              $prevtimestamp = strtotime('-1 day', $time);
1810              $nexttimestamp = strtotime('+1 day', $time);
1811  
1812              $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1813              $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1814  
1815              $prevname = $days[$prevdate['wday']]['fullname'];
1816              $nextname = $days[$nextdate['wday']]['fullname'];
1817              $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&amp;', false, false,
1818                  false, false, $prevtimestamp);
1819              $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&amp;', false, false, false,
1820                  false, $nexttimestamp);
1821  
1822              $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1823              $content .= $prevlink;
1824              $content .= '<span class="hide"> | </span><span class="current">' .userdate($time,
1825                      get_string('strftimedaydate')) . '</span>';
1826              $content .= '<span class="hide"> | </span>' . $nextlink;
1827              $content .= "<span class=\"clearer\"><!-- --></span>";
1828              $content .= \html_writer::end_tag('div') . "\n";
1829  
1830              break;
1831      }
1832  
1833      return $content;
1834  }
1835  
1836  /**
1837   * Return the representation day.
1838   *
1839   * @param int $tstamp Timestamp in GMT
1840   * @param int|bool $now current Unix timestamp
1841   * @param bool $usecommonwords
1842   * @return string the formatted date/time
1843   */
1844  function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1845      static $shortformat;
1846  
1847      if (empty($shortformat)) {
1848          $shortformat = get_string('strftimedayshort');
1849      }
1850  
1851      if ($now === false) {
1852          $now = time();
1853      }
1854  
1855      // To have it in one place, if a change is needed.
1856      $formal = userdate($tstamp, $shortformat);
1857  
1858      $datestamp = usergetdate($tstamp);
1859      $datenow = usergetdate($now);
1860  
1861      if ($usecommonwords == false) {
1862          // We don't want words, just a date.
1863          return $formal;
1864      } else if ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1865          return get_string('today', 'calendar');
1866      } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1867          ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12
1868              && $datenow['yday'] == 1)) {
1869          return get_string('yesterday', 'calendar');
1870      } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1871          ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12
1872              && $datestamp['yday'] == 1)) {
1873          return get_string('tomorrow', 'calendar');
1874      } else {
1875          return $formal;
1876      }
1877  }
1878  
1879  /**
1880   * return the formatted representation time.
1881   *
1882  
1883   * @param int $time the timestamp in UTC, as obtained from the database
1884   * @return string the formatted date/time
1885   */
1886  function calendar_time_representation($time) {
1887      static $langtimeformat = null;
1888  
1889      if ($langtimeformat === null) {
1890          $langtimeformat = get_string('strftimetime');
1891      }
1892  
1893      $timeformat = get_user_preferences('calendar_timeformat');
1894      if (empty($timeformat)) {
1895          $timeformat = get_config(null, 'calendar_site_timeformat');
1896      }
1897  
1898      // Allow language customization of selected time format.
1899      if ($timeformat === CALENDAR_TF_12) {
1900          $timeformat = get_string('strftimetime12', 'langconfig');
1901      } else if ($timeformat === CALENDAR_TF_24) {
1902          $timeformat = get_string('strftimetime24', 'langconfig');
1903      }
1904  
1905      return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
1906  }
1907  
1908  /**
1909   * Adds day, month, year arguments to a URL and returns a moodle_url object.
1910   *
1911   * @param string|moodle_url $linkbase
1912   * @param int $d The number of the day.
1913   * @param int $m The number of the month.
1914   * @param int $y The number of the year.
1915   * @param int $time the unixtime, used for multiple calendar support. The values $d,
1916   *     $m and $y are kept for backwards compatibility.
1917   * @return moodle_url|null $linkbase
1918   */
1919  function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1920      if (empty($linkbase)) {
1921          return null;
1922      }
1923  
1924      if (!($linkbase instanceof \moodle_url)) {
1925          $linkbase = new \moodle_url($linkbase);
1926      }
1927  
1928      $linkbase->param('time', calendar_get_timestamp($d, $m, $y, $time));
1929  
1930      return $linkbase;
1931  }
1932  
1933  /**
1934   * Build and return a previous month HTML link, with an arrow.
1935   *
1936   * @param string $text The text label.
1937   * @param string|moodle_url $linkbase The URL stub.
1938   * @param int $d The number of the date.
1939   * @param int $m The number of the month.
1940   * @param int $y year The number of the year.
1941   * @param bool $accesshide Default visible, or hide from all except screenreaders.
1942   * @param int $time the unixtime, used for multiple calendar support. The values $d,
1943   *     $m and $y are kept for backwards compatibility.
1944   * @return string HTML string.
1945   */
1946  function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1947      $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1948  
1949      if (empty($href)) {
1950          return $text;
1951      }
1952  
1953      $attrs = [
1954          'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1955          'data-drop-zone' => 'nav-link',
1956      ];
1957  
1958      return link_arrow_left($text, $href->out(false), $accesshide, 'previous', $attrs);
1959  }
1960  
1961  /**
1962   * Build and return a next month HTML link, with an arrow.
1963   *
1964   * @param string $text The text label.
1965   * @param string|moodle_url $linkbase The URL stub.
1966   * @param int $d the number of the Day
1967   * @param int $m The number of the month.
1968   * @param int $y The number of the year.
1969   * @param bool $accesshide Default visible, or hide from all except screenreaders.
1970   * @param int $time the unixtime, used for multiple calendar support. The values $d,
1971   *     $m and $y are kept for backwards compatibility.
1972   * @return string HTML string.
1973   */
1974  function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1975      $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1976  
1977      if (empty($href)) {
1978          return $text;
1979      }
1980  
1981      $attrs = [
1982          'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1983          'data-drop-zone' => 'nav-link',
1984      ];
1985  
1986      return link_arrow_right($text, $href->out(false), $accesshide, 'next', $attrs);
1987  }
1988  
1989  /**
1990   * Return the number of days in month.
1991   *
1992   * @param int $month the number of the month.
1993   * @param int $year the number of the year
1994   * @return int
1995   */
1996  function calendar_days_in_month($month, $year) {
1997      $calendartype = \core_calendar\type_factory::get_calendar_instance();
1998      return $calendartype->get_num_days_in_month($year, $month);
1999  }
2000  
2001  /**
2002   * Get the next following month.
2003   *
2004   * @param int $month the number of the month.
2005   * @param int $year the number of the year.
2006   * @return array the following month
2007   */
2008  function calendar_add_month($month, $year) {
2009      $calendartype = \core_calendar\type_factory::get_calendar_instance();
2010      return $calendartype->get_next_month($year, $month);
2011  }
2012  
2013  /**
2014   * Get the previous month.
2015   *
2016   * @param int $month the number of the month.
2017   * @param int $year the number of the year.
2018   * @return array previous month
2019   */
2020  function calendar_sub_month($month, $year) {
2021      $calendartype = \core_calendar\type_factory::get_calendar_instance();
2022      return $calendartype->get_prev_month($year, $month);
2023  }
2024  
2025  /**
2026   * Get per-day basis events
2027   *
2028   * @param array $events list of events
2029   * @param int $month the number of the month
2030   * @param int $year the number of the year
2031   * @param array $eventsbyday event on specific day
2032   * @param array $durationbyday duration of the event in days
2033   * @param array $typesbyday event type (eg: site, course, user, or group)
2034   * @param array $courses list of courses
2035   * @return void
2036   */
2037  function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
2038      $calendartype = \core_calendar\type_factory::get_calendar_instance();
2039  
2040      $eventsbyday = array();
2041      $typesbyday = array();
2042      $durationbyday = array();
2043  
2044      if ($events === false) {
2045          return;
2046      }
2047  
2048      foreach ($events as $event) {
2049          $startdate = $calendartype->timestamp_to_date_array($event->timestart);
2050          if ($event->timeduration) {
2051              $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
2052          } else {
2053              $enddate = $startdate;
2054          }
2055  
2056          // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair.
2057          if (!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) &&
2058              ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
2059              continue;
2060          }
2061  
2062          $eventdaystart = intval($startdate['mday']);
2063  
2064          if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2065              // Give the event to its day.
2066              $eventsbyday[$eventdaystart][] = $event->id;
2067  
2068              // Mark the day as having such an event.
2069              if ($event->courseid == SITEID && $event->groupid == 0) {
2070                  $typesbyday[$eventdaystart]['startsite'] = true;
2071                  // Set event class for site event.
2072                  $events[$event->id]->class = 'calendar_event_site';
2073              } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
2074                  $typesbyday[$eventdaystart]['startcourse'] = true;
2075                  // Set event class for course event.
2076                  $events[$event->id]->class = 'calendar_event_course';
2077              } else if ($event->groupid) {
2078                  $typesbyday[$eventdaystart]['startgroup'] = true;
2079                  // Set event class for group event.
2080                  $events[$event->id]->class = 'calendar_event_group';
2081              } else if ($event->userid) {
2082                  $typesbyday[$eventdaystart]['startuser'] = true;
2083                  // Set event class for user event.
2084                  $events[$event->id]->class = 'calendar_event_user';
2085              }
2086          }
2087  
2088          if ($event->timeduration == 0) {
2089              // Proceed with the next.
2090              continue;
2091          }
2092  
2093          // The event starts on $month $year or before.
2094          if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2095              $lowerbound = intval($startdate['mday']);
2096          } else {
2097              $lowerbound = 0;
2098          }
2099  
2100          // Also, it ends on $month $year or later.
2101          if ($enddate['mon'] == $month && $enddate['year'] == $year) {
2102              $upperbound = intval($enddate['mday']);
2103          } else {
2104              $upperbound = calendar_days_in_month($month, $year);
2105          }
2106  
2107          // Mark all days between $lowerbound and $upperbound (inclusive) as duration.
2108          for ($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
2109              $durationbyday[$i][] = $event->id;
2110              if ($event->courseid == SITEID && $event->groupid == 0) {
2111                  $typesbyday[$i]['durationsite'] = true;
2112              } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
2113                  $typesbyday[$i]['durationcourse'] = true;
2114              } else if ($event->groupid) {
2115                  $typesbyday[$i]['durationgroup'] = true;
2116              } else if ($event->userid) {
2117                  $typesbyday[$i]['durationuser'] = true;
2118              }
2119          }
2120  
2121      }
2122      return;
2123  }
2124  
2125  /**
2126   * Returns the courses to load events for.
2127   *
2128   * @param array $courseeventsfrom An array of courses to load calendar events for
2129   * @param bool $ignorefilters specify the use of filters, false is set as default
2130   * @param stdClass $user The user object. This defaults to the global $USER object.
2131   * @return array An array of courses, groups, and user to load calendar events for based upon filters
2132   */
2133  function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false, stdClass $user = null) {
2134      global $CFG, $USER;
2135  
2136      if (is_null($user)) {
2137          $user = $USER;
2138      }
2139  
2140      $courses = array();
2141      $userid = false;
2142      $group = false;
2143  
2144      // Get the capabilities that allow seeing group events from all groups.
2145      $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
2146  
2147      $isvaliduser = !empty($user->id);
2148  
2149      if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE, $user)) {
2150          $courses = array_keys($courseeventsfrom);
2151      }
2152      if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_SITE, $user)) {
2153          $courses[] = SITEID;
2154      }
2155      $courses = array_unique($courses);
2156      sort($courses);
2157  
2158      if (!empty($courses) && in_array(SITEID, $courses)) {
2159          // Sort courses for consistent colour highlighting.
2160          // Effectively ignoring SITEID as setting as last course id.
2161          $key = array_search(SITEID, $courses);
2162          unset($courses[$key]);
2163          $courses[] = SITEID;
2164      }
2165  
2166      if ($ignorefilters || ($isvaliduser && calendar_show_event_type(CALENDAR_EVENT_USER, $user))) {
2167          $userid = $user->id;
2168      }
2169  
2170      if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP, $user) || $ignorefilters)) {
2171  
2172          if (count($courseeventsfrom) == 1) {
2173              $course = reset($courseeventsfrom);
2174              if (has_any_capability($allgroupscaps, \context_course::instance($course->id))) {
2175                  $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
2176                  $group = array_keys($coursegroups);
2177              }
2178          }
2179          if ($group === false) {
2180              if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, \context_system::instance())) {
2181                  $group = true;
2182              } else if ($isvaliduser) {
2183                  $groupids = array();
2184                  foreach ($courseeventsfrom as $courseid => $course) {
2185                      if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2186                          // If this course has groups, show events from all of those related to the current user.
2187                          $coursegroups = groups_get_user_groups($course->id, $user->id);
2188                          $groupids = array_merge($groupids, $coursegroups['0']);
2189                      }
2190                  }
2191                  if (!empty($groupids)) {
2192                      $group = $groupids;
2193                  }
2194              }
2195          }
2196      }
2197      if (empty($courses)) {
2198          $courses = false;
2199      }
2200  
2201      return array($courses, $group, $userid);
2202  }
2203  
2204  /**
2205   * Can current user manage a non user event in system context.
2206   *
2207   * @param calendar_event|stdClass $event event object
2208   * @return boolean
2209   */
2210  function calendar_can_manage_non_user_event_in_system($event) {
2211      $sitecontext = \context_system::instance();
2212      $isuserevent = $event->eventtype == 'user';
2213      $canmanageentries = has_capability('moodle/calendar:manageentries', $sitecontext);
2214      // If user has manageentries at site level and it's not user event, return true.
2215      if ($canmanageentries && !$isuserevent) {
2216          return true;
2217      }
2218  
2219      return false;
2220  }
2221  
2222  /**
2223   * Return the capability for viewing a calendar event.
2224   *
2225   * @param calendar_event $event event object
2226   * @return boolean
2227   */
2228  function calendar_view_event_allowed(calendar_event $event) {
2229      global $USER;
2230  
2231      // Anyone can see site events.
2232      if ($event->courseid && $event->courseid == SITEID) {
2233          return true;
2234      }
2235  
2236      if (calendar_can_manage_non_user_event_in_system($event)) {
2237          return true;
2238      }
2239  
2240      if (!empty($event->groupid)) {
2241          // If it is a group event we need to be able to manage events in the course, or be in the group.
2242          if (has_capability('moodle/calendar:manageentries', $event->context) ||
2243                  has_capability('moodle/calendar:managegroupentries', $event->context)) {
2244              return true;
2245          }
2246  
2247          $mycourses = enrol_get_my_courses('id');
2248          return isset($mycourses[$event->courseid]) && groups_is_member($event->groupid);
2249      } else if ($event->modulename) {
2250          // If this is a module event we need to be able to see the module.
2251          $coursemodules = [];
2252          $courseid = 0;
2253          // Override events do not have the courseid set.
2254          if ($event->courseid) {
2255              $courseid = $event->courseid;
2256              $coursemodules = get_fast_modinfo($event->courseid)->instances;
2257          } else {
2258              $cmraw = get_coursemodule_from_instance($event->modulename, $event->instance, 0, false, MUST_EXIST);
2259              $courseid = $cmraw->course;
2260              $coursemodules = get_fast_modinfo($cmraw->course)->instances;
2261          }
2262          $hasmodule = isset($coursemodules[$event->modulename]);
2263          $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2264  
2265          // If modinfo doesn't know about the module, return false to be safe.
2266          if (!$hasmodule || !$hasinstance) {
2267              return false;
2268          }
2269  
2270          // Must be able to see the course and the module - MDL-59304.
2271          $cm = $coursemodules[$event->modulename][$event->instance];
2272          if (!$cm->uservisible) {
2273              return false;
2274          }
2275          $mycourses = enrol_get_my_courses('id');
2276          return isset($mycourses[$courseid]);
2277      } else if ($event->categoryid) {
2278          // If this is a category we need to be able to see the category.
2279          $cat = \core_course_category::get($event->categoryid, IGNORE_MISSING);
2280          if (!$cat) {
2281              return false;
2282          }
2283          return true;
2284      } else if (!empty($event->courseid)) {
2285          // If it is a course event we need to be able to manage events in the course, or be in the course.
2286          if (has_capability('moodle/calendar:manageentries', $event->context)) {
2287              return true;
2288          }
2289  
2290          return can_access_course(get_course($event->courseid));
2291      } else if ($event->userid) {
2292          return calendar_can_manage_user_event($event);
2293      } else {
2294          throw new moodle_exception('unknown event type');
2295      }
2296  
2297      return false;
2298  }
2299  
2300  /**
2301   * Return the capability for editing calendar event.
2302   *
2303   * @param calendar_event $event event object
2304   * @param bool $manualedit is the event being edited manually by the user
2305   * @return bool capability to edit event
2306   */
2307  function calendar_edit_event_allowed($event, $manualedit = false) {
2308      global $USER, $DB;
2309  
2310      // Must be logged in.
2311      if (!isloggedin()) {
2312          return false;
2313      }
2314  
2315      // Can not be using guest account.
2316      if (isguestuser()) {
2317          return false;
2318      }
2319  
2320      if ($manualedit && !empty($event->modulename)) {
2321          $hascallback = component_callback_exists(
2322              'mod_' . $event->modulename,
2323              'core_calendar_event_timestart_updated'
2324          );
2325  
2326          if (!$hascallback) {
2327              // If the activity hasn't implemented the correct callback
2328              // to handle changes to it's events then don't allow any
2329              // manual changes to them.
2330              return false;
2331          }
2332  
2333          $coursemodules = get_fast_modinfo($event->courseid)->instances;
2334          $hasmodule = isset($coursemodules[$event->modulename]);
2335          $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2336  
2337          // If modinfo doesn't know about the module, return false to be safe.
2338          if (!$hasmodule || !$hasinstance) {
2339              return false;
2340          }
2341  
2342          $coursemodule = $coursemodules[$event->modulename][$event->instance];
2343          $context = context_module::instance($coursemodule->id);
2344          // This is the capability that allows a user to modify the activity
2345          // settings. Since the activity generated this event we need to check
2346          // that the current user has the same capability before allowing them
2347          // to update the event because the changes to the event will be
2348          // reflected within the activity.
2349          return has_capability('moodle/course:manageactivities', $context);
2350      }
2351  
2352      if ($manualedit && !empty($event->component)) {
2353          // TODO possibly we can later add a callback similar to core_calendar_event_timestart_updated in the modules.
2354          return false;
2355      }
2356  
2357      // You cannot edit URL based calendar subscription events presently.
2358      if (!empty($event->subscriptionid)) {
2359          if (!empty($event->subscription->url)) {
2360              // This event can be updated externally, so it cannot be edited.
2361              return false;
2362          }
2363      }
2364  
2365      if (calendar_can_manage_non_user_event_in_system($event)) {
2366          return true;
2367      }
2368  
2369      // If groupid is set, it's definitely a group event.
2370      if (!empty($event->groupid)) {
2371          // Allow users to add/edit group events if -
2372          // 1) They have manageentries for the course OR
2373          // 2) They have managegroupentries AND are in the group.
2374          $group = $DB->get_record('groups', array('id' => $event->groupid));
2375          return $group && (
2376                  has_capability('moodle/calendar:manageentries', $event->context) ||
2377                  (has_capability('moodle/calendar:managegroupentries', $event->context)
2378                      && groups_is_member($event->groupid)));
2379      } else if (!empty($event->courseid)) {
2380          // If groupid is not set, but course is set, it's definitely a course event.
2381          return has_capability('moodle/calendar:manageentries', $event->context);
2382      } else if (!empty($event->categoryid)) {
2383          // If groupid is not set, but category is set, it's definitely a category event.
2384          return has_capability('moodle/calendar:manageentries', $event->context);
2385      } else if (!empty($event->userid) && $event->userid == $USER->id) {
2386          // If course is not set, but userid id set, it's a user event.
2387          return (has_capability('moodle/calendar:manageownentries',
2388              context_user::instance($event->userid)));
2389      } else if (!empty($event->userid)) {
2390          return calendar_can_manage_user_event($event);
2391      }
2392  
2393      return false;
2394  }
2395  
2396  /**
2397   * Can current user edit/delete/add an user event?
2398   *
2399   * @param calendar_event|stdClass $event event object
2400   * @return bool
2401   */
2402  function calendar_can_manage_user_event($event): bool {
2403      global $USER;
2404  
2405      if (!($event instanceof \calendar_event)) {
2406          $event = new \calendar_event(clone($event));
2407      }
2408  
2409      $canmanage = has_capability('moodle/calendar:manageentries', $event->context);
2410      $canmanageown = has_capability('moodle/calendar:manageownentries', $event->context);
2411      $ismyevent = $event->userid == $USER->id;
2412      $isadminevent = is_siteadmin($event->userid);
2413  
2414      if ($canmanageown && $ismyevent) {
2415          return true;
2416      }
2417  
2418      // In site context, user must have login and calendar:manageentries permissions
2419      // ... to manage other user's events except admin users.
2420      if ($canmanage && !$isadminevent) {
2421          return true;
2422      }
2423  
2424      return false;
2425  }
2426  
2427  /**
2428   * Return the capability for deleting a calendar event.
2429   *
2430   * @param calendar_event $event The event object
2431   * @return bool Whether the user has permission to delete the event or not.
2432   */
2433  function calendar_delete_event_allowed($event) {
2434      // Only allow delete if you have capabilities and it is not an module or component event.
2435      return (calendar_edit_event_allowed($event) && empty($event->modulename) && empty($event->component));
2436  }
2437  
2438  /**
2439   * Returns the default courses to display on the calendar when there isn't a specific
2440   * course to display.
2441   *
2442   * @param int $courseid (optional) If passed, an additional course can be returned for admins (the current course).
2443   * @param string $fields Comma separated list of course fields to return.
2444   * @param bool $canmanage If true, this will return the list of courses the user can create events in, rather
2445   *                        than the list of courses they see events from (an admin can always add events in a course
2446   *                        calendar, even if they are not enrolled in the course).
2447   * @param int $userid (optional) The user which this function returns the default courses for.
2448   *                        By default the current user.
2449   * @return array $courses Array of courses to display
2450   */
2451  function calendar_get_default_courses($courseid = null, $fields = '*', $canmanage = false, int $userid = null) {
2452      global $CFG, $USER;
2453  
2454      if (!$userid) {
2455          if (!isloggedin()) {
2456              return array();
2457          }
2458          $userid = $USER->id;
2459      }
2460  
2461      if ((!empty($CFG->calendar_adminseesall) || $canmanage) &&
2462              has_capability('moodle/calendar:manageentries', context_system::instance(), $userid)) {
2463  
2464          // Add a c. prefix to every field as expected by get_courses function.
2465          $fieldlist = explode(',', $fields);
2466  
2467          $prefixedfields = array_map(function($value) {
2468              return 'c.' . trim(strtolower($value));
2469          }, $fieldlist);
2470  
2471          $courses = get_courses('all', 'c.shortname', implode(',', $prefixedfields));
2472      } else {
2473          $courses = enrol_get_users_courses($userid, true, $fields, 'c.shortname');
2474      }
2475  
2476      if ($courseid && $courseid != SITEID) {
2477          if (empty($courses[$courseid]) && has_capability('moodle/calendar:manageentries', context_system::instance(), $userid)) {
2478              // Allow a site admin to see calendars from courses he is not enrolled in.
2479              // This will come from $COURSE.
2480              $courses[$courseid] = get_course($courseid);
2481          }
2482      }
2483  
2484      return $courses;
2485  }
2486  
2487  /**
2488   * Get event format time.
2489   *
2490   * @param calendar_event $event event object
2491   * @param int $now current time in gmt
2492   * @param array $linkparams list of params for event link
2493   * @param bool $usecommonwords the words as formatted date/time.
2494   * @param int $showtime determine the show time GMT timestamp
2495   * @return string $eventtime link/string for event time
2496   */
2497  function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
2498      $starttime = $event->timestart;
2499      $endtime = $event->timestart + $event->timeduration;
2500  
2501      if (empty($linkparams) || !is_array($linkparams)) {
2502          $linkparams = array();
2503      }
2504  
2505      $linkparams['view'] = 'day';
2506  
2507      // OK, now to get a meaningful display.
2508      // Check if there is a duration for this event.
2509      if ($event->timeduration) {
2510          // Get the midnight of the day the event will start.
2511          $usermidnightstart = usergetmidnight($starttime);
2512          // Get the midnight of the day the event will end.
2513          $usermidnightend = usergetmidnight($endtime);
2514          // Check if we will still be on the same day.
2515          if ($usermidnightstart == $usermidnightend) {
2516              // Check if we are running all day.
2517              if ($event->timeduration == DAYSECS) {
2518                  $time = get_string('allday', 'calendar');
2519              } else { // Specify the time we will be running this from.
2520                  $datestart = calendar_time_representation($starttime);
2521                  $dateend = calendar_time_representation($endtime);
2522                  $time = $datestart . ' <strong>&raquo;</strong> ' . $dateend;
2523              }
2524  
2525              // Set printable representation.
2526              if (!$showtime) {
2527                  $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2528                  $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2529                  $eventtime = \html_writer::link($url, $day) . ', ' . $time;
2530              } else {
2531                  $eventtime = $time;
2532              }
2533          } else { // It must spans two or more days.
2534              $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
2535              if ($showtime == $usermidnightstart) {
2536                  $daystart = '';
2537              }
2538              $timestart = calendar_time_representation($event->timestart);
2539              $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
2540              if ($showtime == $usermidnightend) {
2541                  $dayend = '';
2542              }
2543              $timeend = calendar_time_representation($event->timestart + $event->timeduration);
2544  
2545              // Set printable representation.
2546              if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2547                  $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2548                  $eventtime = $timestart . ' <strong>&raquo;</strong> ' . \html_writer::link($url, $dayend) . $timeend;
2549              } else {
2550                  // The event is in the future, print start and end links.
2551                  $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2552                  $eventtime = \html_writer::link($url, $daystart) . $timestart . ' <strong>&raquo;</strong> ';
2553  
2554                  $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams),  0, 0, 0, $endtime);
2555                  $eventtime .= \html_writer::link($url, $dayend) . $timeend;
2556              }
2557          }
2558      } else { // There is no time duration.
2559          $time = calendar_time_representation($event->timestart);
2560          // Set printable representation.
2561          if (!$showtime) {
2562              $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2563              $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams),  0, 0, 0, $starttime);
2564              $eventtime = \html_writer::link($url, $day) . ', ' . trim($time);
2565          } else {
2566              $eventtime = $time;
2567          }
2568      }
2569  
2570      // Check if It has expired.
2571      if ($event->timestart + $event->timeduration < $now) {
2572          $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2573      }
2574  
2575      return $eventtime;
2576  }
2577  
2578  /**
2579   * Format event location property
2580   *
2581   * @param calendar_event $event
2582   * @return string
2583   */
2584  function calendar_format_event_location(calendar_event $event): string {
2585      $location = format_text($event->location, FORMAT_PLAIN, ['context' => $event->context]);
2586  
2587      // If it looks like a link, convert it to one.
2588      if (preg_match('/^https?:\/\//i', $location) && clean_param($location, PARAM_URL)) {
2589          $location = \html_writer::link($location, $location, [
2590              'title' => get_string('eventnamelocation', 'core_calendar', ['name' => $event->name, 'location' => $location]),
2591          ]);
2592      }
2593  
2594      return $location;
2595  }
2596  
2597  /**
2598   * Checks to see if the requested type of event should be shown for the given user.
2599   *
2600   * @param int $type The type to check the display for (default is to display all)
2601   * @param stdClass|int|null $user The user to check for - by default the current user
2602   * @return bool True if the tyep should be displayed false otherwise
2603   */
2604  function calendar_show_event_type($type, $user = null) {
2605      $default = CALENDAR_EVENT_SITE + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
2606  
2607      if ((int)get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2608          global $SESSION;
2609          if (!isset($SESSION->calendarshoweventtype)) {
2610              $SESSION->calendarshoweventtype = $default;
2611          }
2612          return $SESSION->calendarshoweventtype & $type;
2613      } else {
2614          return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2615      }
2616  }
2617  
2618  /**
2619   * Sets the display of the event type given $display.
2620   *
2621   * If $display = true the event type will be shown.
2622   * If $display = false the event type will NOT be shown.
2623   * If $display = null the current value will be toggled and saved.
2624   *
2625   * @param int $type object of CALENDAR_EVENT_XXX
2626   * @param bool $display option to display event type
2627   * @param stdClass|int $user moodle user object or id, null means current user
2628   */
2629  function calendar_set_event_type_display($type, $display = null, $user = null) {
2630      $persist = (int)get_user_preferences('calendar_persistflt', 0, $user);
2631      $default = CALENDAR_EVENT_SITE + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP
2632              + CALENDAR_EVENT_USER + CALENDAR_EVENT_COURSECAT;
2633      if ($persist === 0) {
2634          global $SESSION;
2635          if (!isset($SESSION->calendarshoweventtype)) {
2636              $SESSION->calendarshoweventtype = $default;
2637          }
2638          $preference = $SESSION->calendarshoweventtype;
2639      } else {
2640          $preference = get_user_preferences('calendar_savedflt', $default, $user);
2641      }
2642      $current = $preference & $type;
2643      if ($display === null) {
2644          $display = !$current;
2645      }
2646      if ($display && !$current) {
2647          $preference += $type;
2648      } else if (!$display && $current) {
2649          $preference -= $type;
2650      }
2651      if ($persist === 0) {
2652          $SESSION->calendarshoweventtype = $preference;
2653      } else {
2654          if ($preference == $default) {
2655              unset_user_preference('calendar_savedflt', $user);
2656          } else {
2657              set_user_preference('calendar_savedflt', $preference, $user);
2658          }
2659      }
2660  }
2661  
2662  /**
2663   * Get calendar's allowed types.
2664   *
2665   * @param stdClass $allowed list of allowed edit for event  type
2666   * @param stdClass|int $course object of a course or course id
2667   * @param array $groups array of groups for the given course
2668   * @param stdClass|int $category object of a category
2669   */
2670  function calendar_get_allowed_types(&$allowed, $course = null, $groups = null, $category = null) {
2671      global $USER, $DB;
2672  
2673      $allowed = new \stdClass();
2674      $allowed->user = has_capability('moodle/calendar:manageownentries', \context_system::instance());
2675      $allowed->groups = false;
2676      $allowed->courses = false;
2677      $allowed->categories = false;
2678      $allowed->site = has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID));
2679      $getgroupsfunc = function($course, $context, $user) use ($groups) {
2680          if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2681              if (has_capability('moodle/site:accessallgroups', $context)) {
2682                  return is_null($groups) ? groups_get_all_groups($course->id) : $groups;
2683              } else {
2684                  if (is_null($groups)) {
2685                      return groups_get_all_groups($course->id, $user->id);
2686                  } else {
2687                      return array_filter($groups, function($group) use ($user) {
2688                          return isset($group->members[$user->id]);
2689                      });
2690                  }
2691              }
2692          }
2693  
2694          return false;
2695      };
2696  
2697      if (!empty($course)) {
2698          if (!is_object($course)) {
2699              $course = $DB->get_record('course', array('id' => $course), 'id, groupmode, groupmodeforce', MUST_EXIST);
2700          }
2701          if ($course->id != SITEID) {
2702              $coursecontext = \context_course::instance($course->id);
2703              $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
2704  
2705              if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2706                  $allowed->courses = array($course->id => 1);
2707                  $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2708              } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
2709                  $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2710              }
2711          }
2712      }
2713  
2714      if (!empty($category)) {
2715          $catcontext = \context_coursecat::instance($category->id);
2716          if (has_capability('moodle/category:manage', $catcontext)) {
2717              $allowed->categories = [$category->id => 1];
2718          }
2719      }
2720  }
2721  
2722  /**
2723   * See if user can add calendar entries at all used to print the "New Event" button.
2724   *
2725   * @param stdClass $course object of a course or course id
2726   * @return bool has the capability to add at least one event type
2727   */
2728  function calendar_user_can_add_event($course) {
2729      if (!isloggedin() || isguestuser()) {
2730          return false;
2731      }
2732  
2733      calendar_get_allowed_types($allowed, $course);
2734  
2735      return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->categories || $allowed->site);
2736  }
2737  
2738  /**
2739   * Check wether the current user is permitted to add events.
2740   *
2741   * @param stdClass $event object of event
2742   * @return bool has the capability to add event
2743   */
2744  function calendar_add_event_allowed($event) {
2745      global $USER, $DB;
2746  
2747      // Can not be using guest account.
2748      if (!isloggedin() or isguestuser()) {
2749          return false;
2750      }
2751  
2752      if (calendar_can_manage_non_user_event_in_system($event)) {
2753          return true;
2754      }
2755  
2756      switch ($event->eventtype) {
2757          case 'category':
2758              return has_capability('moodle/category:manage', $event->context);
2759          case 'course':
2760              return has_capability('moodle/calendar:manageentries', $event->context);
2761          case 'group':
2762              // Allow users to add/edit group events if -
2763              // 1) They have manageentries (= entries for whole course).
2764              // 2) They have managegroupentries AND are in the group.
2765              $group = $DB->get_record('groups', array('id' => $event->groupid));
2766              return $group && (
2767                      has_capability('moodle/calendar:manageentries', $event->context) ||
2768                      (has_capability('moodle/calendar:managegroupentries', $event->context)
2769                          && groups_is_member($event->groupid)));
2770          case 'user':
2771              return calendar_can_manage_user_event($event);
2772          case 'site':
2773              return has_capability('moodle/calendar:manageentries', $event->context);
2774          default:
2775              return has_capability('moodle/calendar:manageentries', $event->context);
2776      }
2777  }
2778  
2779  /**
2780   * Returns option list for the poll interval setting.
2781   *
2782   * @return array An array of poll interval options. Interval => description.
2783   */
2784  function calendar_get_pollinterval_choices() {
2785      return array(
2786          '0' => get_string('never', 'calendar'),
2787          HOURSECS => get_string('hourly', 'calendar'),
2788          DAYSECS => get_string('daily', 'calendar'),
2789          WEEKSECS => get_string('weekly', 'calendar'),
2790          '2628000' => get_string('monthly', 'calendar'),
2791          YEARSECS => get_string('annually', 'calendar')
2792      );
2793  }
2794  
2795  /**
2796   * Returns option list of available options for the calendar event type, given the current user and course.
2797   *
2798   * @param int $courseid The id of the course
2799   * @return array An array containing the event types the user can create.
2800   */
2801  function calendar_get_eventtype_choices($courseid) {
2802      $choices = array();
2803      $allowed = new \stdClass;
2804      calendar_get_allowed_types($allowed, $courseid);
2805  
2806      if ($allowed->user) {
2807          $choices['user'] = get_string('userevents', 'calendar');
2808      }
2809      if ($allowed->site) {
2810          $choices['site'] = get_string('siteevents', 'calendar');
2811      }
2812      if (!empty($allowed->courses)) {
2813          $choices['course'] = get_string('courseevents', 'calendar');
2814      }
2815      if (!empty($allowed->categories)) {
2816          $choices['category'] = get_string('categoryevents', 'calendar');
2817      }
2818      if (!empty($allowed->groups) and is_array($allowed->groups)) {
2819          $choices['group'] = get_string('group');
2820      }
2821  
2822      return array($choices, $allowed->groups);
2823  }
2824  
2825  /**
2826   * Add an iCalendar subscription to the database.
2827   *
2828   * @param stdClass $sub The subscription object (e.g. from the form)
2829   * @return int The insert ID, if any.
2830   */
2831  function calendar_add_subscription($sub) {
2832      global $DB, $USER, $SITE;
2833  
2834      // Undo the form definition work around to allow us to have two different
2835      // course selectors present depending on which event type the user selects.
2836      if (!empty($sub->groupcourseid)) {
2837          $sub->courseid = $sub->groupcourseid;
2838          unset($sub->groupcourseid);
2839      }
2840  
2841      // Default course id if none is set.
2842      if (empty($sub->courseid)) {
2843          if ($sub->eventtype === 'site') {
2844              $sub->courseid = SITEID;
2845          } else {
2846              $sub->courseid = 0;
2847          }
2848      }
2849  
2850      if ($sub->eventtype === 'site') {
2851          $sub->courseid = $SITE->id;
2852      } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
2853          $sub->courseid = $sub->courseid;
2854      } else if ($sub->eventtype === 'category') {
2855          $sub->categoryid = $sub->categoryid;
2856      } else {
2857          // User events.
2858          $sub->courseid = 0;
2859      }
2860      $sub->userid = $USER->id;
2861  
2862      // File subscriptions never update.
2863      if (empty($sub->url)) {
2864          $sub->pollinterval = 0;
2865      }
2866  
2867      if (!empty($sub->name)) {
2868          if (empty($sub->id)) {
2869              $id = $DB->insert_record('event_subscriptions', $sub);
2870              // We cannot cache the data here because $sub is not complete.
2871              $sub->id = $id;
2872              // Trigger event, calendar subscription added.
2873              $eventparams = array('objectid' => $sub->id,
2874                  'context' => calendar_get_calendar_context($sub),
2875                  'other' => array(
2876                      'eventtype' => $sub->eventtype,
2877                  )
2878              );
2879              switch ($sub->eventtype) {
2880                  case 'category':
2881                      $eventparams['other']['categoryid'] = $sub->categoryid;
2882                      break;
2883                  case 'course':
2884                      $eventparams['other']['courseid'] = $sub->courseid;
2885                      break;
2886                  case 'group':
2887                      $eventparams['other']['courseid'] = $sub->courseid;
2888                      $eventparams['other']['groupid'] = $sub->groupid;
2889                      break;
2890                  default:
2891                      $eventparams['other']['courseid'] = $sub->courseid;
2892              }
2893  
2894              $event = \core\event\calendar_subscription_created::create($eventparams);
2895              $event->trigger();
2896              return $id;
2897          } else {
2898              // Why are we doing an update here?
2899              calendar_update_subscription($sub);
2900              return $sub->id;
2901          }
2902      } else {
2903          throw new \moodle_exception('errorbadsubscription', 'importcalendar');
2904      }
2905  }
2906  
2907  /**
2908   * Add an iCalendar event to the Moodle calendar.
2909   *
2910   * @param stdClass $event The RFC-2445 iCalendar event
2911   * @param int $unused Deprecated
2912   * @param int $subscriptionid The iCalendar subscription ID
2913   * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2914   * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2915   * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated,  CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2916   */
2917  function calendar_add_icalendar_event($event, $unused, $subscriptionid, $timezone='UTC') {
2918      global $DB;
2919  
2920      // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2921      if (empty($event->properties['SUMMARY'])) {
2922          return 0;
2923      }
2924  
2925      $name = $event->properties['SUMMARY'][0]->value;
2926      $name = str_replace('\n', '<br />', $name);
2927      $name = str_replace('\\', '', $name);
2928      $name = preg_replace('/\s+/u', ' ', $name);
2929  
2930      $eventrecord = new \stdClass;
2931      $eventrecord->name = clean_param($name, PARAM_NOTAGS);
2932  
2933      if (empty($event->properties['DESCRIPTION'][0]->value)) {
2934          $description = '';
2935      } else {
2936          $description = $event->properties['DESCRIPTION'][0]->value;
2937          $description = clean_param($description, PARAM_NOTAGS);
2938          $description = str_replace('\n', '<br />', $description);
2939          $description = str_replace('\\', '', $description);
2940          $description = preg_replace('/\s+/u', ' ', $description);
2941      }
2942      $eventrecord->description = $description;
2943  
2944      // Probably a repeating event with RRULE etc. TODO: skip for now.
2945      if (empty($event->properties['DTSTART'][0]->value)) {
2946          return 0;
2947      }
2948  
2949      if (isset($event->properties['DTSTART'][0]->parameters['TZID'])) {
2950          $tz = $event->properties['DTSTART'][0]->parameters['TZID'];
2951      } else {
2952          $tz = $timezone;
2953      }
2954      $tz = \core_date::normalise_timezone($tz);
2955      $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value . ' ' . $tz);
2956      if (empty($event->properties['DTEND'])) {
2957          $eventrecord->timeduration = 0; // No duration if no end time specified.
2958      } else {
2959          if (isset($event->properties['DTEND'][0]->parameters['TZID'])) {
2960              $endtz = $event->properties['DTEND'][0]->parameters['TZID'];
2961          } else {
2962              $endtz = $timezone;
2963          }
2964          $endtz = \core_date::normalise_timezone($endtz);
2965          $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value . ' ' . $endtz) - $eventrecord->timestart;
2966      }
2967  
2968      // Check to see if it should be treated as an all day event.
2969      if ($eventrecord->timeduration == DAYSECS) {
2970          // Check to see if the event started at Midnight on the imported calendar.
2971          date_default_timezone_set($timezone);
2972          if (date('H:i:s', $eventrecord->timestart) === "00:00:00") {
2973              // This event should be an all day event. This is not correct, we don't do anything differently for all day events.
2974              // See MDL-56227.
2975              $eventrecord->timeduration = 0;
2976          }
2977          \core_date::set_default_server_timezone();
2978      }
2979  
2980      $eventrecord->location = empty($event->properties['LOCATION'][0]->value) ? '' :
2981              trim(str_replace('\\', '', $event->properties['LOCATION'][0]->value));
2982      $eventrecord->uuid = $event->properties['UID'][0]->value;
2983      $eventrecord->timemodified = time();
2984  
2985      // Add the iCal subscription details if required.
2986      // We should never do anything with an event without a subscription reference.
2987      $sub = calendar_get_subscription($subscriptionid);
2988      $eventrecord->subscriptionid = $subscriptionid;
2989      $eventrecord->userid = $sub->userid;
2990      $eventrecord->groupid = $sub->groupid;
2991      $eventrecord->courseid = $sub->courseid;
2992      $eventrecord->categoryid = $sub->categoryid;
2993      $eventrecord->eventtype = $sub->eventtype;
2994  
2995      if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid,
2996          'subscriptionid' => $eventrecord->subscriptionid))) {
2997  
2998          // Compare iCal event data against the moodle event to see if something has changed.
2999          $result = array_diff((array) $eventrecord, (array) $updaterecord);
3000  
3001          // Unset timemodified field because it's always going to be different.
3002          unset($result['timemodified']);
3003  
3004          if (count($result)) {
3005              $eventrecord->id = $updaterecord->id;
3006              $return = CALENDAR_IMPORT_EVENT_UPDATED; // Update.
3007          } else {
3008              return CALENDAR_IMPORT_EVENT_SKIPPED;
3009          }
3010      } else {
3011          $return = CALENDAR_IMPORT_EVENT_INSERTED; // Insert.
3012      }
3013  
3014      if ($createdevent = \calendar_event::create($eventrecord, false)) {
3015          if (!empty($event->properties['RRULE'])) {
3016              // Repeating events.
3017              date_default_timezone_set($tz); // Change time zone to parse all events.
3018              $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
3019              $rrule->parse_rrule();
3020              $rrule->create_events($createdevent);
3021              \core_date::set_default_server_timezone(); // Change time zone back to what it was.
3022          }
3023          return $return;
3024      } else {
3025          return 0;
3026      }
3027  }
3028  
3029  /**
3030   * Delete subscription and all related events.
3031   *
3032   * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
3033   */
3034  function calendar_delete_subscription($subscription) {
3035      global $DB;
3036  
3037      if (!is_object($subscription)) {
3038          $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST);
3039      }
3040  
3041      // Delete subscription and related events.
3042      $DB->delete_records('event', array('subscriptionid' => $subscription->id));
3043      $DB->delete_records('event_subscriptions', array('id' => $subscription->id));
3044      \cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id));
3045  
3046      // Trigger event, calendar subscription deleted.
3047      $eventparams = array('objectid' => $subscription->id,
3048          'context' => calendar_get_calendar_context($subscription),
3049          'other' => array(
3050              'eventtype' => $subscription->eventtype,
3051          )
3052      );
3053      switch ($subscription->eventtype) {
3054          case 'category':
3055              $eventparams['other']['categoryid'] = $subscription->categoryid;
3056              break;
3057          case 'course':
3058              $eventparams['other']['courseid'] = $subscription->courseid;
3059              break;
3060          case 'group':
3061              $eventparams['other']['courseid'] = $subscription->courseid;
3062              $eventparams['other']['groupid'] = $subscription->groupid;
3063              break;
3064          default:
3065              $eventparams['other']['courseid'] = $subscription->courseid;
3066      }
3067      $event = \core\event\calendar_subscription_deleted::create($eventparams);
3068      $event->trigger();
3069  }
3070  
3071  /**
3072   * From a URL, fetch the calendar and return an iCalendar object.
3073   *
3074   * @param string $url The iCalendar URL
3075   * @return iCalendar The iCalendar object
3076   */
3077  function calendar_get_icalendar($url) {
3078      global $CFG;
3079  
3080      require_once($CFG->libdir . '/filelib.php');
3081      require_once($CFG->libdir . '/bennu/bennu.inc.php');
3082  
3083      $curl = new \curl();
3084      $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
3085      $calendar = $curl->get($url);
3086  
3087      // Http code validation should actually be the job of curl class.
3088      if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
3089          throw new \moodle_exception('errorinvalidicalurl', 'calendar');
3090      }
3091  
3092      $ical = new \iCalendar();
3093      $ical->unserialize($calendar);
3094  
3095      return $ical;
3096  }
3097  
3098  /**
3099   * Import events from an iCalendar object into a course calendar.
3100   *
3101   * @param iCalendar $ical The iCalendar object.
3102   * @param int|null $subscriptionid The subscription ID.
3103   * @return array A log of the import progress, including errors.
3104   */
3105  function calendar_import_events_from_ical(iCalendar $ical, int $subscriptionid = null): array {
3106      global $DB;
3107  
3108      $errors = [];
3109      $eventcount = 0;
3110      $updatecount = 0;
3111      $skippedcount = 0;
3112      $deletedcount = 0;
3113  
3114      // Large calendars take a while...
3115      if (!CLI_SCRIPT) {
3116          \core_php_time_limit::raise(300);
3117      }
3118  
3119      // Start with a safe default timezone.
3120      $timezone = 'UTC';
3121  
3122      // Grab the timezone from the iCalendar file to be used later.
3123      if (isset($ical->properties['X-WR-TIMEZONE'][0]->value)) {
3124          $timezone = $ical->properties['X-WR-TIMEZONE'][0]->value;
3125  
3126      } else if (isset($ical->properties['PRODID'][0]->value)) {
3127          // If the timezone was not found, check to se if this is MS exchange / Office 365 which uses Windows timezones.
3128          if (strncmp($ical->properties['PRODID'][0]->value, 'Microsoft', 9) == 0) {
3129              if (isset($ical->components['VTIMEZONE'][0]->properties['TZID'][0]->value)) {
3130                  $tzname = $ical->components['VTIMEZONE'][0]->properties['TZID'][0]->value;
3131                  $timezone = IntlTimeZone::getIDForWindowsID($tzname);
3132              }
3133          }
3134      }
3135  
3136      $icaluuids = [];
3137      foreach ($ical->components['VEVENT'] as $event) {
3138          $icaluuids[] = $event->properties['UID'][0]->value;
3139          $res = calendar_add_icalendar_event($event, null, $subscriptionid, $timezone);
3140          switch ($res) {
3141              case CALENDAR_IMPORT_EVENT_UPDATED:
3142                  $updatecount++;
3143                  break;
3144              case CALENDAR_IMPORT_EVENT_INSERTED:
3145                  $eventcount++;
3146                  break;
3147              case CALENDAR_IMPORT_EVENT_SKIPPED:
3148                  $skippedcount++;
3149                  break;
3150              case 0:
3151                  if (empty($event->properties['SUMMARY'])) {
3152                      $errors[] = '(' . get_string('notitle', 'calendar') . ')';
3153                  } else {
3154                      $errors[] = $event->properties['SUMMARY'][0]->value;
3155                  }
3156                  break;
3157          }
3158      }
3159  
3160      $existing = $DB->get_field('event_subscriptions', 'lastupdated', ['id' => $subscriptionid]);
3161      if (!empty($existing)) {
3162          $eventsuuids = $DB->get_records_menu('event', ['subscriptionid' => $subscriptionid], '', 'id, uuid');
3163  
3164          $icaleventscount = count($icaluuids);
3165          $tobedeleted = [];
3166          if (count($eventsuuids) > $icaleventscount) {
3167              foreach ($eventsuuids as $eventid => $eventuuid) {
3168                  if (!in_array($eventuuid, $icaluuids)) {
3169                      $tobedeleted[] = $eventid;
3170                  }
3171              }
3172              if (!empty($tobedeleted)) {
3173                  $DB->delete_records_list('event', 'id', $tobedeleted);
3174                  $deletedcount = count($tobedeleted);
3175              }
3176          }
3177      }
3178  
3179      $result = [
3180          'eventsimported' => $eventcount,
3181          'eventsskipped' => $skippedcount,
3182          'eventsupdated' => $updatecount,
3183          'eventsdeleted' => $deletedcount,
3184          'haserror' => !empty($errors),
3185          'errors' => $errors,
3186      ];
3187  
3188      return $result;
3189  }
3190  
3191  /**
3192   * Fetch a calendar subscription and update the events in the calendar.
3193   *
3194   * @param int $subscriptionid The course ID for the calendar.
3195   * @return array A log of the import progress, including errors.
3196   */
3197  function calendar_update_subscription_events($subscriptionid) {
3198      $sub = calendar_get_subscription($subscriptionid);
3199  
3200      // Don't update a file subscription.
3201      if (empty($sub->url)) {
3202          return 'File subscription not updated.';
3203      }
3204  
3205      $ical = calendar_get_icalendar($sub->url);
3206      $return = calendar_import_events_from_ical($ical, $subscriptionid);
3207      $sub->lastupdated = time();
3208  
3209      calendar_update_subscription($sub);
3210  
3211      return $return;
3212  }
3213  
3214  /**
3215   * Update a calendar subscription. Also updates the associated cache.
3216   *
3217   * @param stdClass|array $subscription Subscription record.
3218   * @throws coding_exception If something goes wrong
3219   * @since Moodle 2.5
3220   */
3221  function calendar_update_subscription($subscription) {
3222      global $DB;
3223  
3224      if (is_array($subscription)) {
3225          $subscription = (object)$subscription;
3226      }
3227      if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
3228          throw new \coding_exception('Cannot update a subscription without a valid id');
3229      }
3230  
3231      $DB->update_record('event_subscriptions', $subscription);
3232  
3233      // Update cache.
3234      $cache = \cache::make('core', 'calendar_subscriptions');
3235      $cache->set($subscription->id, $subscription);
3236  
3237      // Trigger event, calendar subscription updated.
3238      $eventparams = array('userid' => $subscription->userid,
3239          'objectid' => $subscription->id,
3240          'context' => calendar_get_calendar_context($subscription),
3241          'other' => array(
3242              'eventtype' => $subscription->eventtype,
3243          )
3244      );
3245      switch ($subscription->eventtype) {
3246          case 'category':
3247              $eventparams['other']['categoryid'] = $subscription->categoryid;
3248              break;
3249          case 'course':
3250              $eventparams['other']['courseid'] = $subscription->courseid;
3251              break;
3252          case 'group':
3253              $eventparams['other']['courseid'] = $subscription->courseid;
3254              $eventparams['other']['groupid'] = $subscription->groupid;
3255              break;
3256          default:
3257              $eventparams['other']['courseid'] = $subscription->courseid;
3258      }
3259      $event = \core\event\calendar_subscription_updated::create($eventparams);
3260      $event->trigger();
3261  }
3262  
3263  /**
3264   * Checks to see if the user can edit a given subscription feed.
3265   *
3266   * @param mixed $subscriptionorid Subscription object or id
3267   * @return bool true if current user can edit the subscription else false
3268   */
3269  function calendar_can_edit_subscription($subscriptionorid) {
3270      global $USER;
3271      if (is_array($subscriptionorid)) {
3272          $subscription = (object)$subscriptionorid;
3273      } else if (is_object($subscriptionorid)) {
3274          $subscription = $subscriptionorid;
3275      } else {
3276          $subscription = calendar_get_subscription($subscriptionorid);
3277      }
3278  
3279      $allowed = new \stdClass;
3280      $courseid = $subscription->courseid;
3281      $categoryid = $subscription->categoryid;
3282      $groupid = $subscription->groupid;
3283      $category = null;
3284  
3285      if (!empty($categoryid)) {
3286          $category = \core_course_category::get($categoryid);
3287      }
3288      calendar_get_allowed_types($allowed, $courseid, null, $category);
3289      switch ($subscription->eventtype) {
3290          case 'user':
3291              return ($USER->id == $subscription->userid && $allowed->user);
3292          case 'course':
3293              if (isset($allowed->courses[$courseid])) {
3294                  return $allowed->courses[$courseid];
3295              } else {
3296                  return false;
3297              }
3298          case 'category':
3299              if (isset($allowed->categories[$categoryid])) {
3300                  return $allowed->categories[$categoryid];
3301              } else {
3302                  return false;
3303              }
3304          case 'site':
3305              return $allowed->site;
3306          case 'group':
3307              if (isset($allowed->groups[$groupid])) {
3308                  return $allowed->groups[$groupid];
3309              } else {
3310                  return false;
3311              }
3312          default:
3313              return false;
3314      }
3315  }
3316  
3317  /**
3318   * Helper function to determine the context of a calendar subscription.
3319   * Subscriptions can be created in two contexts COURSE, or USER.
3320   *
3321   * @param stdClass $subscription
3322   * @return context instance
3323   */
3324  function calendar_get_calendar_context($subscription) {
3325      // Determine context based on calendar type.
3326      if ($subscription->eventtype === 'site') {
3327          $context = \context_course::instance(SITEID);
3328      } else if ($subscription->eventtype === 'group' || $subscription->eventtype === 'course') {
3329          $context = \context_course::instance($subscription->courseid);
3330      } else {
3331          $context = \context_user::instance($subscription->userid);
3332      }
3333      return $context;
3334  }
3335  
3336  /**
3337   * Implements callback user_preferences, lists preferences that users are allowed to update directly
3338   *
3339   * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3340   *
3341   * @return array
3342   */
3343  function core_calendar_user_preferences() {
3344      $preferences = [];
3345      $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED, 'default' => '0',
3346          'choices' => array('0', CALENDAR_TF_12, CALENDAR_TF_24)
3347      );
3348      $preferences['calendar_startwday'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3349          'choices' => array(0, 1, 2, 3, 4, 5, 6));
3350      $preferences['calendar_maxevents'] = array('type' => PARAM_INT, 'choices' => range(1, 20));
3351      $preferences['calendar_lookahead'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 365,
3352          'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3353      $preferences['calendar_persistflt'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3354          'choices' => array(0, 1));
3355      return $preferences;
3356  }
3357  
3358  /**
3359   * Get legacy calendar events
3360   *
3361   * @param int $tstart Start time of time range for events
3362   * @param int $tend End time of time range for events
3363   * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3364   * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3365   * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3366   * @param boolean $withduration whether only events starting within time range selected
3367   *                              or events in progress/already started selected as well
3368   * @param boolean $ignorehidden whether to select only visible events or all events
3369   * @param array $categories array of category ids and/or objects.
3370   * @param int $limitnum Number of events to fetch or zero to fetch all.
3371   *
3372   * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3373   */
3374  function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses,
3375          $withduration = true, $ignorehidden = true, $categories = [], $limitnum = 0) {
3376      // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3377      // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3378      // parameters, but with the new API method, only null and arrays are accepted.
3379      list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3380          // If parameter is true, return null.
3381          if ($param === true) {
3382              return null;
3383          }
3384  
3385          // If parameter is false, return an empty array.
3386          if ($param === false) {
3387              return [];
3388          }
3389  
3390          // If the parameter is a scalar value, enclose it in an array.
3391          if (!is_array($param)) {
3392              return [$param];
3393          }
3394  
3395          // No normalisation required.
3396          return $param;
3397      }, [$users, $groups, $courses, $categories]);
3398  
3399      // If a single user is provided, we can use that for capability checks.
3400      // Otherwise current logged in user is used - See MDL-58768.
3401      if (is_array($userparam) && count($userparam) == 1) {
3402          \core_calendar\local\event\container::set_requesting_user($userparam[0]);
3403      }
3404      $mapper = \core_calendar\local\event\container::get_event_mapper();
3405      $events = \core_calendar\local\api::get_events(
3406          $tstart,
3407          $tend,
3408          null,
3409          null,
3410          null,
3411          null,
3412          $limitnum,
3413          null,
3414          $userparam,
3415          $groupparam,
3416          $courseparam,
3417          $categoryparam,
3418          $withduration,
3419          $ignorehidden
3420      );
3421  
3422      return array_reduce($events, function($carry, $event) use ($mapper) {
3423          return $carry + [$event->get_id() => $mapper->from_event_to_stdclass($event)];
3424      }, []);
3425  }
3426  
3427  
3428  /**
3429   * Get the calendar view output.
3430   *
3431   * @param   \calendar_information $calendar The calendar being represented
3432   * @param   string  $view The type of calendar to have displayed
3433   * @param   bool    $includenavigation Whether to include navigation
3434   * @param   bool    $skipevents Whether to load the events or not
3435   * @param   int     $lookahead Overwrites site and users's lookahead setting.
3436   * @return  array[array, string]
3437   */
3438  function calendar_get_view(\calendar_information $calendar, $view, $includenavigation = true, bool $skipevents = false,
3439          ?int $lookahead = null) {
3440      global $PAGE, $CFG;
3441  
3442      $renderer = $PAGE->get_renderer('core_calendar');
3443      $type = \core_calendar\type_factory::get_calendar_instance();
3444  
3445      // Calculate the bounds of the month.
3446      $calendardate = $type->timestamp_to_date_array($calendar->time);
3447  
3448      $date = new \DateTime('now', core_date::get_user_timezone_object(99));
3449      $eventlimit = 0;
3450  
3451      if ($view === 'day') {
3452          $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday']);
3453          $date->setTimestamp($tstart);
3454          $date->modify('+1 day');
3455      } else if ($view === 'upcoming' || $view === 'upcoming_mini') {
3456          // Number of days in the future that will be used to fetch events.
3457          if (!$lookahead) {
3458              if (isset($CFG->calendar_lookahead)) {
3459                  $defaultlookahead = intval($CFG->calendar_lookahead);
3460              } else {
3461                  $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD;
3462              }
3463              $lookahead = get_user_preferences('calendar_lookahead', $defaultlookahead);
3464          }
3465  
3466          // Maximum number of events to be displayed on upcoming view.
3467          $defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS;
3468          if (isset($CFG->calendar_maxevents)) {
3469              $defaultmaxevents = intval($CFG->calendar_maxevents);
3470          }
3471          $eventlimit = get_user_preferences('calendar_maxevents', $defaultmaxevents);
3472  
3473          $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday'],
3474                  $calendardate['hours']);
3475          $date->setTimestamp($tstart);
3476          $date->modify('+' . $lookahead . ' days');
3477      } else {
3478          $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], 1);
3479          $monthdays = $type->get_num_days_in_month($calendardate['year'], $calendardate['mon']);
3480          $date->setTimestamp($tstart);
3481          $date->modify('+' . $monthdays . ' days');
3482  
3483          if ($view === 'mini' || $view === 'minithree') {
3484              $template = 'core_calendar/calendar_mini';
3485          } else {
3486              $template = 'core_calendar/calendar_month';
3487          }
3488      }
3489  
3490      // We need to extract 1 second to ensure that we don't get into the next day.
3491      $date->modify('-1 second');
3492      $tend = $date->getTimestamp();
3493  
3494      list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3495          // If parameter is true, return null.
3496          if ($param === true) {
3497              return null;
3498          }
3499  
3500          // If parameter is false, return an empty array.
3501          if ($param === false) {
3502              return [];
3503          }
3504  
3505          // If the parameter is a scalar value, enclose it in an array.
3506          if (!is_array($param)) {
3507              return [$param];
3508          }
3509  
3510          // No normalisation required.
3511          return $param;
3512      }, [$calendar->users, $calendar->groups, $calendar->courses, $calendar->categories]);
3513  
3514      if ($skipevents) {
3515          $events = [];
3516      } else {
3517          $events = \core_calendar\local\api::get_events(
3518              $tstart,
3519              $tend,
3520              null,
3521              null,
3522              null,
3523              null,
3524              $eventlimit,
3525              null,
3526              $userparam,
3527              $groupparam,
3528              $courseparam,
3529              $categoryparam,
3530              true,
3531              true,
3532              function ($event) {
3533                  if ($proxy = $event->get_course_module()) {
3534                      $cminfo = $proxy->get_proxied_instance();
3535                      return $cminfo->uservisible;
3536                  }
3537  
3538                  if ($proxy = $event->get_category()) {
3539                      $category = $proxy->get_proxied_instance();
3540  
3541                      return $category->is_uservisible();
3542                  }
3543  
3544                  return true;
3545              }
3546          );
3547      }
3548  
3549      $related = [
3550          'events' => $events,
3551          'cache' => new \core_calendar\external\events_related_objects_cache($events),
3552          'type' => $type,
3553      ];
3554  
3555      $data = [];
3556      $calendar->set_viewmode($view);
3557      if ($view == "month" || $view == "monthblock" || $view == "mini" || $view == "minithree" ) {
3558          $month = new \core_calendar\external\month_exporter($calendar, $type, $related);
3559          $month->set_includenavigation($includenavigation);
3560          $month->set_initialeventsloaded(!$skipevents);
3561          $month->set_showcoursefilter(($view == "month" || $view == "monthblock"));
3562          $data = $month->export($renderer);
3563      } else if ($view == "day") {
3564          $day = new \core_calendar\external\calendar_day_exporter($calendar, $related);
3565          $data = $day->export($renderer);
3566          $data->viewingday = true;
3567          $data->showviewselector = true;
3568          $template = 'core_calendar/calendar_day';
3569      } else if ($view == "upcoming" || $view == "upcoming_mini") {
3570          $upcoming = new \core_calendar\external\calendar_upcoming_exporter($calendar, $related);
3571          $data = $upcoming->export($renderer);
3572  
3573          if ($view == "upcoming") {
3574              $template = 'core_calendar/calendar_upcoming';
3575              $data->viewingupcoming = true;
3576              $data->showviewselector = true;
3577          } else if ($view == "upcoming_mini") {
3578              $template = 'core_calendar/calendar_upcoming_mini';
3579          }
3580      }
3581  
3582      return [$data, $template];
3583  }
3584  
3585  /**
3586   * Request and render event form fragment.
3587   *
3588   * @param array $args The fragment arguments.
3589   * @return string The rendered mform fragment.
3590   */
3591  function calendar_output_fragment_event_form($args) {
3592      global $CFG, $OUTPUT, $USER;
3593      require_once($CFG->libdir . '/grouplib.php');
3594      $html = '';
3595      $data = [];
3596      $eventid = isset($args['eventid']) ? clean_param($args['eventid'], PARAM_INT) : null;
3597      $starttime = isset($args['starttime']) ? clean_param($args['starttime'], PARAM_INT) : null;
3598      $courseid = (isset($args['courseid']) && $args['courseid'] != SITEID) ? clean_param($args['courseid'], PARAM_INT) : null;
3599      $categoryid = isset($args['categoryid']) ? clean_param($args['categoryid'], PARAM_INT) : null;
3600      $event = null;
3601      $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
3602      $context = \context_user::instance($USER->id);
3603      $editoroptions = \core_calendar\local\event\forms\create::build_editor_options($context);
3604      $formoptions = ['editoroptions' => $editoroptions, 'courseid' => $courseid];
3605      $draftitemid = 0;
3606  
3607      if ($hasformdata) {
3608          parse_str(clean_param($args['formdata'], PARAM_TEXT), $data);
3609          if (isset($data['description']['itemid'])) {
3610              $draftitemid = $data['description']['itemid'];
3611          }
3612      }
3613  
3614      if ($starttime) {
3615          $formoptions['starttime'] = $starttime;
3616      }
3617      // Let's check first which event types user can add.
3618      $eventtypes = calendar_get_allowed_event_types($courseid);
3619      $formoptions['eventtypes'] = $eventtypes;
3620  
3621      if (is_null($eventid)) {
3622          if (!empty($courseid)) {
3623              $groupcoursedata = groups_get_course_data($courseid);
3624              $formoptions['groups'] = [];
3625              foreach ($groupcoursedata->groups as $groupid => $groupdata) {
3626                  $formoptions['groups'][$groupid] = $groupdata->name;
3627              }
3628          }
3629  
3630          $mform = new \core_calendar\local\event\forms\create(
3631              null,
3632              $formoptions,
3633              'post',
3634              '',
3635              null,
3636              true,
3637              $data
3638          );
3639  
3640          // If the user is on course context and is allowed to add course events set the event type default to course.
3641          if (!empty($courseid) && !empty($eventtypes['course'])) {
3642              $data['eventtype'] = 'course';
3643              $data['courseid'] = $courseid;
3644              $data['groupcourseid'] = $courseid;
3645          } else if (!empty($categoryid) && !empty($eventtypes['category'])) {
3646              $data['eventtype'] = 'category';
3647              $data['categoryid'] = $categoryid;
3648          } else if (!empty($groupcoursedata) && !empty($eventtypes['group'])) {
3649              $data['groupcourseid'] = $courseid;
3650              $data['groups'] = $groupcoursedata->groups;
3651          }
3652          $mform->set_data($data);
3653      } else {
3654          $event = calendar_event::load($eventid);
3655  
3656          if (!calendar_edit_event_allowed($event)) {
3657              throw new \moodle_exception('nopermissiontoupdatecalendar');
3658          }
3659  
3660          $mapper = new \core_calendar\local\event\mappers\create_update_form_mapper();
3661          $eventdata = $mapper->from_legacy_event_to_data($event);
3662          $data = array_merge((array) $eventdata, $data);
3663          $event->count_repeats();
3664          $formoptions['event'] = $event;
3665  
3666          if (!empty($event->courseid)) {
3667              $groupcoursedata = groups_get_course_data($event->courseid);
3668              $formoptions['groups'] = [];
3669              foreach ($groupcoursedata->groups as $groupid => $groupdata) {
3670                  $formoptions['groups'][$groupid] = $groupdata->name;
3671              }
3672          }
3673  
3674          $data['description']['text'] = file_prepare_draft_area(
3675              $draftitemid,
3676              $event->context->id,
3677              'calendar',
3678              'event_description',
3679              $event->id,
3680              null,
3681              $data['description']['text']
3682          );
3683          $data['description']['itemid'] = $draftitemid;
3684  
3685          $mform = new \core_calendar\local\event\forms\update(
3686              null,
3687              $formoptions,
3688              'post',
3689              '',
3690              null,
3691              true,
3692              $data
3693          );
3694          $mform->set_data($data);
3695  
3696          // Check to see if this event is part of a subscription or import.
3697          // If so display a warning on edit.
3698          if (isset($event->subscriptionid) && ($event->subscriptionid != null)) {
3699              $renderable = new \core\output\notification(
3700                  get_string('eventsubscriptioneditwarning', 'calendar'),
3701                  \core\output\notification::NOTIFY_INFO
3702              );
3703  
3704              $html .= $OUTPUT->render($renderable);
3705          }
3706      }
3707  
3708      if ($hasformdata) {
3709          $mform->is_validated();
3710      }
3711  
3712      $html .= $mform->render();
3713      return $html;
3714  }
3715  
3716  /**
3717   * Calculate the timestamp from the supplied Gregorian Year, Month, and Day.
3718   *
3719   * @param   int     $d The day
3720   * @param   int     $m The month
3721   * @param   int     $y The year
3722   * @param   int     $time The timestamp to use instead of a separate y/m/d.
3723   * @return  int     The timestamp
3724   */
3725  function calendar_get_timestamp($d, $m, $y, $time = 0) {
3726      // If a day, month and year were passed then convert it to a timestamp. If these were passed
3727      // then we can assume the day, month and year are passed as Gregorian, as no where in core
3728      // should we be passing these values rather than the time.
3729      if (!empty($d) && !empty($m) && !empty($y)) {
3730          if (checkdate($m, $d, $y)) {
3731              $time = make_timestamp($y, $m, $d);
3732          } else {
3733              $time = time();
3734          }
3735      } else if (empty($time)) {
3736          $time = time();
3737      }
3738  
3739      return $time;
3740  }
3741  
3742  /**
3743   * Get the calendar footer options.
3744   *
3745   * @param calendar_information $calendar The calendar information object.
3746   * @param array $options Display options for the footer. If an option is not set, a default value will be provided.
3747   *                      It consists of:
3748   *                      - showfullcalendarlink - bool - Whether to show the full calendar link or not. Defaults to false.
3749   *
3750   * @return array The data for template and template name.
3751   */
3752  function calendar_get_footer_options($calendar, array $options = []) {
3753      global $CFG, $USER, $PAGE;
3754  
3755      // Generate hash for iCal link.
3756      $authtoken = calendar_get_export_token($USER);
3757  
3758      $renderer = $PAGE->get_renderer('core_calendar');
3759      $footer = new \core_calendar\external\footer_options_exporter($calendar, $USER->id, $authtoken, $options);
3760      $data = $footer->export($renderer);
3761      $template = 'core_calendar/footer_options';
3762  
3763      return [$data, $template];
3764  }
3765  
3766  /**
3767   * Get the list of potential calendar filter types as a type => name
3768   * combination.
3769   *
3770   * @return array
3771   */
3772  function calendar_get_filter_types() {
3773      $types = [
3774          'site',
3775          'category',
3776          'course',
3777          'group',
3778          'user',
3779          'other'
3780      ];
3781  
3782      return array_map(function($type) {
3783          return [
3784              'eventtype' => $type,
3785              'name' => get_string("eventtype{$type}", "calendar"),
3786              'icon' => true,
3787              'key' => 'i/' . $type . 'event',
3788              'component' => 'core'
3789          ];
3790      }, $types);
3791  }
3792  
3793  /**
3794   * Check whether the specified event type is valid.
3795   *
3796   * @param string $type
3797   * @return bool
3798   */
3799  function calendar_is_valid_eventtype($type) {
3800      $validtypes = [
3801          'user',
3802          'group',
3803          'course',
3804          'category',
3805          'site',
3806      ];
3807      return in_array($type, $validtypes);
3808  }
3809  
3810  /**
3811   * Get event types the user can create event based on categories, courses and groups
3812   * the logged in user belongs to.
3813   *
3814   * @param int|null $courseid The course id.
3815   * @return array The array of allowed types.
3816   */
3817  function calendar_get_allowed_event_types(int $courseid = null) {
3818      global $DB, $CFG, $USER;
3819  
3820      $types = [
3821          'user' => false,
3822          'site' => false,
3823          'course' => false,
3824          'group' => false,
3825          'category' => false
3826      ];
3827  
3828      if (!empty($courseid) && $courseid != SITEID) {
3829          $context = \context_course::instance($courseid);
3830          $types['user'] = has_capability('moodle/calendar:manageownentries', $context);
3831          calendar_internal_update_course_and_group_permission($courseid, $context, $types);
3832      }
3833  
3834      if (has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID))) {
3835          $types['site'] = true;
3836      }
3837  
3838      if (has_capability('moodle/calendar:manageownentries', \context_system::instance())) {
3839          $types['user'] = true;
3840      }
3841      if (core_course_category::has_manage_capability_on_any()) {
3842          $types['category'] = true;
3843      }
3844  
3845      // We still don't know if the user can create group and course events, so iterate over the courses to find out
3846      // if the user has capabilities in one of the courses.
3847      if ($types['course'] == false || $types['group'] == false) {
3848          if ($CFG->calendar_adminseesall && has_capability('moodle/calendar:manageentries', context_system::instance())) {
3849              $sql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3850                        FROM {course} c
3851                        JOIN {context} ctx ON ctx.contextlevel = ? AND ctx.instanceid = c.id
3852                       WHERE c.id IN (
3853                              SELECT DISTINCT courseid FROM {groups}
3854                          )";
3855              $courseswithgroups = $DB->get_recordset_sql($sql, [CONTEXT_COURSE]);
3856              foreach ($courseswithgroups as $course) {
3857                  context_helper::preload_from_record($course);
3858                  $context = context_course::instance($course->id);
3859  
3860                  if (has_capability('moodle/calendar:manageentries', $context)) {
3861                      if (has_any_capability(['moodle/site:accessallgroups', 'moodle/calendar:managegroupentries'], $context)) {
3862                          // The user can manage group entries or access any group.
3863                          $types['group'] = true;
3864                          $types['course'] = true;
3865                          break;
3866                      }
3867                  }
3868              }
3869              $courseswithgroups->close();
3870  
3871              if (false === $types['course']) {
3872                  // Course is still not confirmed. There may have been no courses with a group in them.
3873                  $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
3874                  $sql = "SELECT
3875                              c.id, c.visible, {$ctxfields}
3876                          FROM {course} c
3877                          JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
3878                  $params = [
3879                      'contextlevel' => CONTEXT_COURSE,
3880                  ];
3881                  $courses = $DB->get_recordset_sql($sql, $params);
3882                  foreach ($courses as $course) {
3883                      context_helper::preload_from_record($course);
3884                      $context = context_course::instance($course->id);
3885                      if (has_capability('moodle/calendar:manageentries', $context)) {
3886                          $types['course'] = true;
3887                          break;
3888                      }
3889                  }
3890                  $courses->close();
3891              }
3892  
3893          } else {
3894              $courses = calendar_get_default_courses(null, 'id');
3895              if (empty($courses)) {
3896                  return $types;
3897              }
3898  
3899              $courseids = array_map(function($c) {
3900                  return $c->id;
3901              }, $courses);
3902  
3903              // Check whether the user has access to create events within courses which have groups.
3904              list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
3905              $sql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3906                        FROM {course} c
3907                        JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3908                       WHERE c.id $insql
3909                         AND c.id IN (SELECT DISTINCT courseid FROM {groups})";
3910              $params['contextlevel'] = CONTEXT_COURSE;
3911              $courseswithgroups = $DB->get_recordset_sql($sql, $params);
3912              foreach ($courseswithgroups as $coursewithgroup) {
3913                  context_helper::preload_from_record($coursewithgroup);
3914                  $context = context_course::instance($coursewithgroup->id);
3915  
3916                  calendar_internal_update_course_and_group_permission($coursewithgroup->id, $context, $types);
3917  
3918                  // Okay, course and group event types are allowed, no need to keep the loop iteration.
3919                  if ($types['course'] == true && $types['group'] == true) {
3920                      break;
3921                  }
3922              }
3923              $courseswithgroups->close();
3924  
3925              if (false === $types['course']) {
3926                  list($insql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
3927                  $contextsql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3928                                  FROM {course} c
3929                                  JOIN {context} ctx ON ctx.contextlevel = :contextlevel AND ctx.instanceid = c.id
3930                                  WHERE c.id $insql";
3931                  $params['contextlevel'] = CONTEXT_COURSE;
3932                  $contextrecords = $DB->get_recordset_sql($contextsql, $params);
3933                  foreach ($contextrecords as $course) {
3934                      context_helper::preload_from_record($course);
3935                      $coursecontext = context_course::instance($course->id);
3936                      if (has_capability('moodle/calendar:manageentries', $coursecontext)
3937                              && ($courseid == $course->id || empty($courseid))) {
3938                          $types['course'] = true;
3939                          break;
3940                      }
3941                  }
3942                  $contextrecords->close();
3943              }
3944  
3945          }
3946      }
3947  
3948      return $types;
3949  }
3950  
3951  /**
3952   * Given a course id, and context, updates the permission types array to add the 'course' or 'group'
3953   * permission if it is relevant for that course.
3954   *
3955   * For efficiency, if they already have 'course' or 'group' then it skips checks.
3956   *
3957   * Do not call this function directly, it is only for use by calendar_get_allowed_event_types().
3958   *
3959   * @param int $courseid Course id
3960   * @param context $context Context for that course
3961   * @param array $types Current permissions
3962   */
3963  function calendar_internal_update_course_and_group_permission(int $courseid, context $context, array &$types) {
3964      if (!$types['course']) {
3965          // If they have manageentries permission on the course, then they can update this course.
3966          if (has_capability('moodle/calendar:manageentries', $context)) {
3967              $types['course'] = true;
3968          }
3969      }
3970      // To update group events they must have EITHER manageentries OR managegroupentries.
3971      if (!$types['group'] && (has_capability('moodle/calendar:manageentries', $context) ||
3972              has_capability('moodle/calendar:managegroupentries', $context))) {
3973          // And they also need for a group to exist on the course.
3974          $groups = groups_get_all_groups($courseid);
3975          if (!empty($groups)) {
3976              // And either accessallgroups, or belong to one of the groups.
3977              if (has_capability('moodle/site:accessallgroups', $context)) {
3978                  $types['group'] = true;
3979              } else {
3980                  foreach ($groups as $group) {
3981                      if (groups_is_member($group->id)) {
3982                          $types['group'] = true;
3983                          break;
3984                      }
3985                  }
3986              }
3987          }
3988      }
3989  }
3990  
3991  /**
3992   * Get the auth token for exporting the given user calendar.
3993   * @param stdClass $user The user to export the calendar for
3994   *
3995   * @return string The export token.
3996   */
3997  function calendar_get_export_token(stdClass $user): string {
3998      global $CFG, $DB;
3999  
4000      return sha1($user->id . $DB->get_field('user', 'password', ['id' => $user->id]) . $CFG->calendar_exportsalt);
4001  }
4002  
4003  /**
4004   * Get the list of URL parameters for calendar expport and import links.
4005   *
4006   * @return array
4007   */
4008  function calendar_get_export_import_link_params(): array {
4009      global $PAGE;
4010  
4011      $params = [];
4012      if ($courseid = $PAGE->url->get_param('course')) {
4013          $params['course'] = $courseid;
4014      }
4015      if ($categoryid = $PAGE->url->get_param('category')) {
4016          $params['category'] = $categoryid;
4017      }
4018  
4019      return $params;
4020  }
4021  
4022  /**
4023   * Implements the inplace editable feature.
4024   *
4025   * @param string $itemtype Type of the inplace editable element
4026   * @param int $itemid Id of the item to edit
4027   * @param int $newvalue New value of the item
4028   * @return \core\output\inplace_editable
4029   */
4030  function calendar_inplace_editable(string $itemtype, int $itemid, int $newvalue): \core\output\inplace_editable {
4031      global $OUTPUT;
4032  
4033      if ($itemtype === 'refreshinterval') {
4034  
4035          $subscription = calendar_get_subscription($itemid);
4036          $context = calendar_get_calendar_context($subscription);
4037          external_api::validate_context($context);
4038  
4039          $updateresult = \core_calendar\output\refreshintervalcollection::update($itemid, $newvalue);
4040  
4041          $refreshresults = calendar_update_subscription_events($itemid);
4042          \core\notification::add($OUTPUT->render_from_template(
4043              'core_calendar/subscription_update_result',
4044              array_merge($refreshresults, [
4045                  'subscriptionname' => s($subscription->name),
4046              ])
4047          ), \core\notification::INFO);
4048  
4049          return $updateresult;
4050      }
4051  
4052      external_api::validate_context(context_system::instance());
4053  }