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