MDL-62384 tool_monitor: Update to sql to fix performance.
[moodle.git] / calendar / lib.php
blob0f684dd9c4ade079009db84ce936cf97d3f0b9c8
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Calendar extension
20 * @package core_calendar
21 * @copyright 2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
22 * Avgoustos Tsinakos
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 if (!defined('MOODLE_INTERNAL')) {
27 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
30 require_once($CFG->libdir . '/coursecatlib.php');
32 /**
33 * These are read by the administration component to provide default values
36 /**
37 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
39 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
41 /**
42 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
44 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
46 /**
47 * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
49 define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
51 // This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
52 // Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
54 /**
55 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
57 define('CALENDAR_DEFAULT_WEEKEND', 65);
59 /**
60 * CALENDAR_URL - path to calendar's folder
62 define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
64 /**
65 * CALENDAR_TF_24 - Calendar time in 24 hours format
67 define('CALENDAR_TF_24', '%H:%M');
69 /**
70 * CALENDAR_TF_12 - Calendar time in 12 hours format
72 define('CALENDAR_TF_12', '%I:%M %p');
74 /**
75 * CALENDAR_EVENT_GLOBAL - Global calendar event types
77 define('CALENDAR_EVENT_GLOBAL', 1);
79 /**
80 * CALENDAR_EVENT_COURSE - Course calendar event types
82 define('CALENDAR_EVENT_COURSE', 2);
84 /**
85 * CALENDAR_EVENT_GROUP - group calendar event types
87 define('CALENDAR_EVENT_GROUP', 4);
89 /**
90 * CALENDAR_EVENT_USER - user calendar event types
92 define('CALENDAR_EVENT_USER', 8);
94 /**
95 * CALENDAR_EVENT_COURSECAT - Course category calendar event types
97 define('CALENDAR_EVENT_COURSECAT', 16);
99 /**
100 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
102 define('CALENDAR_IMPORT_FROM_FILE', 0);
105 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
107 define('CALENDAR_IMPORT_FROM_URL', 1);
110 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
112 define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
115 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
117 define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
120 * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
122 define('CALENDAR_SUBSCRIPTION_UPDATE', 1);
125 * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
127 define('CALENDAR_SUBSCRIPTION_REMOVE', 2);
130 * CALENDAR_EVENT_USER_OVERRIDE_PRIORITY - Constant for the user override priority.
132 define('CALENDAR_EVENT_USER_OVERRIDE_PRIORITY', 0);
135 * CALENDAR_EVENT_TYPE_STANDARD - Standard events.
137 define('CALENDAR_EVENT_TYPE_STANDARD', 0);
140 * CALENDAR_EVENT_TYPE_ACTION - Action events.
142 define('CALENDAR_EVENT_TYPE_ACTION', 1);
145 * Manage calendar events.
147 * This class provides the required functionality in order to manage calendar events.
148 * It was introduced as part of Moodle 2.0 and was created in order to provide a
149 * better framework for dealing with calendar events in particular regard to file
150 * handling through the new file API.
152 * @package core_calendar
153 * @category calendar
154 * @copyright 2009 Sam Hemelryk
155 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
157 * @property int $id The id within the event table
158 * @property string $name The name of the event
159 * @property string $description The description of the event
160 * @property int $format The format of the description FORMAT_?
161 * @property int $courseid The course the event is associated with (0 if none)
162 * @property int $groupid The group the event is associated with (0 if none)
163 * @property int $userid The user the event is associated with (0 if none)
164 * @property int $repeatid If this is a repeated event this will be set to the
165 * id of the original
166 * @property string $modulename If added by a module this will be the module name
167 * @property int $instance If added by a module this will be the module instance
168 * @property string $eventtype The event type
169 * @property int $timestart The start time as a timestamp
170 * @property int $timeduration The duration of the event in seconds
171 * @property int $visible 1 if the event is visible
172 * @property int $uuid ?
173 * @property int $sequence ?
174 * @property int $timemodified The time last modified as a timestamp
176 class calendar_event {
178 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
179 protected $properties = null;
181 /** @var string The converted event discription with file paths resolved.
182 * This gets populated when someone requests description for the first time */
183 protected $_description = null;
185 /** @var array The options to use with this description editor */
186 protected $editoroptions = array(
187 'subdirs' => false,
188 'forcehttps' => false,
189 'maxfiles' => -1,
190 'maxbytes' => null,
191 'trusttext' => false);
193 /** @var object The context to use with the description editor */
194 protected $editorcontext = null;
197 * Instantiates a new event and optionally populates its properties with the data provided.
199 * @param \stdClass $data Optional. An object containing the properties to for
200 * an event
202 public function __construct($data = null) {
203 global $CFG, $USER;
205 // First convert to object if it is not already (should either be object or assoc array).
206 if (!is_object($data)) {
207 $data = (object) $data;
210 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
212 $data->eventrepeats = 0;
214 if (empty($data->id)) {
215 $data->id = null;
218 if (!empty($data->subscriptionid)) {
219 $data->subscription = calendar_get_subscription($data->subscriptionid);
222 // Default to a user event.
223 if (empty($data->eventtype)) {
224 $data->eventtype = 'user';
227 // Default to the current user.
228 if (empty($data->userid)) {
229 $data->userid = $USER->id;
232 if (!empty($data->timeduration) && is_array($data->timeduration)) {
233 $data->timeduration = make_timestamp(
234 $data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'],
235 $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
238 if (!empty($data->description) && is_array($data->description)) {
239 $data->format = $data->description['format'];
240 $data->description = $data->description['text'];
241 } else if (empty($data->description)) {
242 $data->description = '';
243 $data->format = editors_get_preferred_format();
246 // Ensure form is defaulted correctly.
247 if (empty($data->format)) {
248 $data->format = editors_get_preferred_format();
251 $this->properties = $data;
255 * Magic set method.
257 * Attempts to call a set_$key method if one exists otherwise falls back
258 * to simply set the property.
260 * @param string $key property name
261 * @param mixed $value value of the property
263 public function __set($key, $value) {
264 if (method_exists($this, 'set_'.$key)) {
265 $this->{'set_'.$key}($value);
267 $this->properties->{$key} = $value;
271 * Magic get method.
273 * Attempts to call a get_$key method to return the property and ralls over
274 * to return the raw property.
276 * @param string $key property name
277 * @return mixed property value
278 * @throws \coding_exception
280 public function __get($key) {
281 if (method_exists($this, 'get_'.$key)) {
282 return $this->{'get_'.$key}();
284 if (!property_exists($this->properties, $key)) {
285 throw new \coding_exception('Undefined property requested');
287 return $this->properties->{$key};
291 * Magic isset method.
293 * PHP needs an isset magic method if you use the get magic method and
294 * still want empty calls to work.
296 * @param string $key $key property name
297 * @return bool|mixed property value, false if property is not exist
299 public function __isset($key) {
300 return !empty($this->properties->{$key});
304 * Calculate the context value needed for an event.
306 * Event's type can be determine by the available value store in $data
307 * It is important to check for the existence of course/courseid to determine
308 * the course event.
309 * Default value is set to CONTEXT_USER
311 * @return \stdClass The context object.
313 protected function calculate_context() {
314 global $USER, $DB;
316 $context = null;
317 if (isset($this->properties->categoryid) && $this->properties->categoryid > 0) {
318 $context = \context_coursecat::instance($this->properties->categoryid);
319 } else if (isset($this->properties->courseid) && $this->properties->courseid > 0) {
320 $context = \context_course::instance($this->properties->courseid);
321 } else if (isset($this->properties->course) && $this->properties->course > 0) {
322 $context = \context_course::instance($this->properties->course);
323 } else if (isset($this->properties->groupid) && $this->properties->groupid > 0) {
324 $group = $DB->get_record('groups', array('id' => $this->properties->groupid));
325 $context = \context_course::instance($group->courseid);
326 } else if (isset($this->properties->userid) && $this->properties->userid > 0
327 && $this->properties->userid == $USER->id) {
328 $context = \context_user::instance($this->properties->userid);
329 } else if (isset($this->properties->userid) && $this->properties->userid > 0
330 && $this->properties->userid != $USER->id &&
331 isset($this->properties->instance) && $this->properties->instance > 0) {
332 $cm = get_coursemodule_from_instance($this->properties->modulename, $this->properties->instance, 0,
333 false, MUST_EXIST);
334 $context = \context_course::instance($cm->course);
335 } else {
336 $context = \context_user::instance($this->properties->userid);
339 return $context;
343 * Returns the context for this event. The context is calculated
344 * the first time is is requested and then stored in a member
345 * variable to be returned each subsequent time.
347 * This is a magical getter function that will be called when
348 * ever the context property is accessed, e.g. $event->context.
350 * @return context
352 protected function get_context() {
353 if (!isset($this->properties->context)) {
354 $this->properties->context = $this->calculate_context();
357 return $this->properties->context;
361 * Returns an array of editoroptions for this event.
363 * @return array event editor options
365 protected function get_editoroptions() {
366 return $this->editoroptions;
370 * Returns an event description: Called by __get
371 * Please use $blah = $event->description;
373 * @return string event description
375 protected function get_description() {
376 global $CFG;
378 require_once($CFG->libdir . '/filelib.php');
380 if ($this->_description === null) {
381 // Check if we have already resolved the context for this event.
382 if ($this->editorcontext === null) {
383 // Switch on the event type to decide upon the appropriate context to use for this event.
384 $this->editorcontext = $this->get_context();
385 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
386 return clean_text($this->properties->description, $this->properties->format);
390 // Work out the item id for the editor, if this is a repeated event
391 // then the files will be associated with the original.
392 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
393 $itemid = $this->properties->repeatid;
394 } else {
395 $itemid = $this->properties->id;
398 // Convert file paths in the description so that things display correctly.
399 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php',
400 $this->editorcontext->id, 'calendar', 'event_description', $itemid);
401 // Clean the text so no nasties get through.
402 $this->_description = clean_text($this->_description, $this->properties->format);
405 // Finally return the description.
406 return $this->_description;
410 * Return the number of repeat events there are in this events series.
412 * @return int number of event repeated
414 public function count_repeats() {
415 global $DB;
416 if (!empty($this->properties->repeatid)) {
417 $this->properties->eventrepeats = $DB->count_records('event',
418 array('repeatid' => $this->properties->repeatid));
419 // We don't want to count ourselves.
420 $this->properties->eventrepeats--;
422 return $this->properties->eventrepeats;
426 * Update or create an event within the database
428 * Pass in a object containing the event properties and this function will
429 * insert it into the database and deal with any associated files
431 * @see self::create()
432 * @see self::update()
434 * @param \stdClass $data object of event
435 * @param bool $checkcapability if moodle should check calendar managing capability or not
436 * @return bool event updated
438 public function update($data, $checkcapability=true) {
439 global $DB, $USER;
441 foreach ($data as $key => $value) {
442 $this->properties->$key = $value;
445 $this->properties->timemodified = time();
446 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
448 // Prepare event data.
449 $eventargs = array(
450 'context' => $this->get_context(),
451 'objectid' => $this->properties->id,
452 'other' => array(
453 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
454 'timestart' => $this->properties->timestart,
455 'name' => $this->properties->name
459 if (empty($this->properties->id) || $this->properties->id < 1) {
460 if ($checkcapability) {
461 if (!calendar_add_event_allowed($this->properties)) {
462 print_error('nopermissiontoupdatecalendar');
466 if ($usingeditor) {
467 switch ($this->properties->eventtype) {
468 case 'user':
469 $this->properties->courseid = 0;
470 $this->properties->course = 0;
471 $this->properties->groupid = 0;
472 $this->properties->userid = $USER->id;
473 break;
474 case 'site':
475 $this->properties->courseid = SITEID;
476 $this->properties->course = SITEID;
477 $this->properties->groupid = 0;
478 $this->properties->userid = $USER->id;
479 break;
480 case 'course':
481 $this->properties->groupid = 0;
482 $this->properties->userid = $USER->id;
483 break;
484 case 'category':
485 $this->properties->groupid = 0;
486 $this->properties->category = 0;
487 $this->properties->userid = $USER->id;
488 break;
489 case 'group':
490 $this->properties->userid = $USER->id;
491 break;
492 default:
493 // We should NEVER get here, but just incase we do lets fail gracefully.
494 $usingeditor = false;
495 break;
498 // If we are actually using the editor, we recalculate the context because some default values
499 // were set when calculate_context() was called from the constructor.
500 if ($usingeditor) {
501 $this->properties->context = $this->calculate_context();
502 $this->editorcontext = $this->get_context();
505 $editor = $this->properties->description;
506 $this->properties->format = $this->properties->description['format'];
507 $this->properties->description = $this->properties->description['text'];
510 // Insert the event into the database.
511 $this->properties->id = $DB->insert_record('event', $this->properties);
513 if ($usingeditor) {
514 $this->properties->description = file_save_draft_area_files(
515 $editor['itemid'],
516 $this->editorcontext->id,
517 'calendar',
518 'event_description',
519 $this->properties->id,
520 $this->editoroptions,
521 $editor['text'],
522 $this->editoroptions['forcehttps']);
523 $DB->set_field('event', 'description', $this->properties->description,
524 array('id' => $this->properties->id));
527 // Log the event entry.
528 $eventargs['objectid'] = $this->properties->id;
529 $eventargs['context'] = $this->get_context();
530 $event = \core\event\calendar_event_created::create($eventargs);
531 $event->trigger();
533 $repeatedids = array();
535 if (!empty($this->properties->repeat)) {
536 $this->properties->repeatid = $this->properties->id;
537 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id' => $this->properties->id));
539 $eventcopy = clone($this->properties);
540 unset($eventcopy->id);
542 $timestart = new \DateTime('@' . $eventcopy->timestart);
543 $timestart->setTimezone(\core_date::get_user_timezone_object());
545 for ($i = 1; $i < $eventcopy->repeats; $i++) {
547 $timestart->add(new \DateInterval('P7D'));
548 $eventcopy->timestart = $timestart->getTimestamp();
550 // Get the event id for the log record.
551 $eventcopyid = $DB->insert_record('event', $eventcopy);
553 // If the context has been set delete all associated files.
554 if ($usingeditor) {
555 $fs = get_file_storage();
556 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description',
557 $this->properties->id);
558 foreach ($files as $file) {
559 $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
563 $repeatedids[] = $eventcopyid;
565 // Trigger an event.
566 $eventargs['objectid'] = $eventcopyid;
567 $eventargs['other']['timestart'] = $eventcopy->timestart;
568 $event = \core\event\calendar_event_created::create($eventargs);
569 $event->trigger();
573 return true;
574 } else {
576 if ($checkcapability) {
577 if (!calendar_edit_event_allowed($this->properties)) {
578 print_error('nopermissiontoupdatecalendar');
582 if ($usingeditor) {
583 if ($this->editorcontext !== null) {
584 $this->properties->description = file_save_draft_area_files(
585 $this->properties->description['itemid'],
586 $this->editorcontext->id,
587 'calendar',
588 'event_description',
589 $this->properties->id,
590 $this->editoroptions,
591 $this->properties->description['text'],
592 $this->editoroptions['forcehttps']);
593 } else {
594 $this->properties->format = $this->properties->description['format'];
595 $this->properties->description = $this->properties->description['text'];
599 $event = $DB->get_record('event', array('id' => $this->properties->id));
601 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
603 if ($updaterepeated) {
604 // Update all.
605 if ($this->properties->timestart != $event->timestart) {
606 $timestartoffset = $this->properties->timestart - $event->timestart;
607 $sql = "UPDATE {event}
608 SET name = ?,
609 description = ?,
610 timestart = timestart + ?,
611 timeduration = ?,
612 timemodified = ?,
613 groupid = ?,
614 courseid = ?
615 WHERE repeatid = ?";
616 // Note: Group and course id may not be set. If not, keep their current values.
617 $params = [
618 $this->properties->name,
619 $this->properties->description,
620 $timestartoffset,
621 $this->properties->timeduration,
622 time(),
623 isset($this->properties->groupid) ? $this->properties->groupid : $event->groupid,
624 isset($this->properties->courseid) ? $this->properties->courseid : $event->courseid,
625 $event->repeatid
627 } else {
628 $sql = "UPDATE {event}
629 SET name = ?,
630 description = ?,
631 timeduration = ?,
632 timemodified = ?,
633 groupid = ?,
634 courseid = ?
635 WHERE repeatid = ?";
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 $event->repeatid
647 $DB->execute($sql, $params);
649 // Trigger an update event for each of the calendar event.
650 $events = $DB->get_records('event', array('repeatid' => $event->repeatid), '', '*');
651 foreach ($events as $calendarevent) {
652 $eventargs['objectid'] = $calendarevent->id;
653 $eventargs['other']['timestart'] = $calendarevent->timestart;
654 $event = \core\event\calendar_event_updated::create($eventargs);
655 $event->add_record_snapshot('event', $calendarevent);
656 $event->trigger();
658 } else {
659 $DB->update_record('event', $this->properties);
660 $event = self::load($this->properties->id);
661 $this->properties = $event->properties();
663 // Trigger an update event.
664 $event = \core\event\calendar_event_updated::create($eventargs);
665 $event->add_record_snapshot('event', $this->properties);
666 $event->trigger();
669 return true;
674 * Deletes an event and if selected an repeated events in the same series
676 * This function deletes an event, any associated events if $deleterepeated=true,
677 * and cleans up any files associated with the events.
679 * @see self::delete()
681 * @param bool $deleterepeated delete event repeatedly
682 * @return bool succession of deleting event
684 public function delete($deleterepeated = false) {
685 global $DB;
687 // If $this->properties->id is not set then something is wrong.
688 if (empty($this->properties->id)) {
689 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
690 return false;
692 $calevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
693 // Delete the event.
694 $DB->delete_records('event', array('id' => $this->properties->id));
696 // Trigger an event for the delete action.
697 $eventargs = array(
698 'context' => $this->get_context(),
699 'objectid' => $this->properties->id,
700 'other' => array(
701 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
702 'timestart' => $this->properties->timestart,
703 'name' => $this->properties->name
705 $event = \core\event\calendar_event_deleted::create($eventargs);
706 $event->add_record_snapshot('event', $calevent);
707 $event->trigger();
709 // If we are deleting parent of a repeated event series, promote the next event in the series as parent.
710 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
711 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC",
712 array($this->properties->id), IGNORE_MULTIPLE);
713 if (!empty($newparent)) {
714 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?",
715 array($newparent, $this->properties->id));
716 // Get all records where the repeatid is the same as the event being removed.
717 $events = $DB->get_records('event', array('repeatid' => $newparent));
718 // For each of the returned events trigger an update event.
719 foreach ($events as $calendarevent) {
720 // Trigger an event for the update.
721 $eventargs['objectid'] = $calendarevent->id;
722 $eventargs['other']['timestart'] = $calendarevent->timestart;
723 $event = \core\event\calendar_event_updated::create($eventargs);
724 $event->add_record_snapshot('event', $calendarevent);
725 $event->trigger();
730 // If the editor context hasn't already been set then set it now.
731 if ($this->editorcontext === null) {
732 $this->editorcontext = $this->get_context();
735 // If the context has been set delete all associated files.
736 if ($this->editorcontext !== null) {
737 $fs = get_file_storage();
738 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
739 foreach ($files as $file) {
740 $file->delete();
744 // If we need to delete repeated events then we will fetch them all and delete one by one.
745 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
746 // Get all records where the repeatid is the same as the event being removed.
747 $events = $DB->get_records('event', array('repeatid' => $this->properties->repeatid));
748 // For each of the returned events populate an event object and call delete.
749 // make sure the arg passed is false as we are already deleting all repeats.
750 foreach ($events as $event) {
751 $event = new calendar_event($event);
752 $event->delete(false);
756 return true;
760 * Fetch all event properties.
762 * This function returns all of the events properties as an object and optionally
763 * can prepare an editor for the description field at the same time. This is
764 * designed to work when the properties are going to be used to set the default
765 * values of a moodle forms form.
767 * @param bool $prepareeditor If set to true a editor is prepared for use with
768 * the mforms editor element. (for description)
769 * @return \stdClass Object containing event properties
771 public function properties($prepareeditor = false) {
772 global $DB;
774 // First take a copy of the properties. We don't want to actually change the
775 // properties or we'd forever be converting back and forwards between an
776 // editor formatted description and not.
777 $properties = clone($this->properties);
778 // Clean the description here.
779 $properties->description = clean_text($properties->description, $properties->format);
781 // If set to true we need to prepare the properties for use with an editor
782 // and prepare the file area.
783 if ($prepareeditor) {
785 // We may or may not have a property id. If we do then we need to work
786 // out the context so we can copy the existing files to the draft area.
787 if (!empty($properties->id)) {
789 if ($properties->eventtype === 'site') {
790 // Site context.
791 $this->editorcontext = $this->get_context();
792 } else if ($properties->eventtype === 'user') {
793 // User context.
794 $this->editorcontext = $this->get_context();
795 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
796 // First check the course is valid.
797 $course = $DB->get_record('course', array('id' => $properties->courseid));
798 if (!$course) {
799 print_error('invalidcourse');
801 // Course context.
802 $this->editorcontext = $this->get_context();
803 // We have a course and are within the course context so we had
804 // better use the courses max bytes value.
805 $this->editoroptions['maxbytes'] = $course->maxbytes;
806 } else if ($properties->eventtype === 'category') {
807 // First check the course is valid.
808 \coursecat::get($properties->categoryid, MUST_EXIST, true);
809 // Course context.
810 $this->editorcontext = $this->get_context();
811 } else {
812 // If we get here we have a custom event type as used by some
813 // modules. In this case the event will have been added by
814 // code and we won't need the editor.
815 $this->editoroptions['maxbytes'] = 0;
816 $this->editoroptions['maxfiles'] = 0;
819 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
820 $contextid = false;
821 } else {
822 // Get the context id that is what we really want.
823 $contextid = $this->editorcontext->id;
825 } else {
827 // If we get here then this is a new event in which case we don't need a
828 // context as there is no existing files to copy to the draft area.
829 $contextid = null;
832 // If the contextid === false we don't support files so no preparing
833 // a draft area.
834 if ($contextid !== false) {
835 // Just encase it has already been submitted.
836 $draftiddescription = file_get_submitted_draft_itemid('description');
837 // Prepare the draft area, this copies existing files to the draft area as well.
838 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar',
839 'event_description', $properties->id, $this->editoroptions, $properties->description);
840 } else {
841 $draftiddescription = 0;
844 // Structure the description field as the editor requires.
845 $properties->description = array('text' => $properties->description, 'format' => $properties->format,
846 'itemid' => $draftiddescription);
849 // Finally return the properties.
850 return $properties;
854 * Toggles the visibility of an event
856 * @param null|bool $force If it is left null the events visibility is flipped,
857 * If it is false the event is made hidden, if it is true it
858 * is made visible.
859 * @return bool if event is successfully updated, toggle will be visible
861 public function toggle_visibility($force = null) {
862 global $DB;
864 // Set visible to the default if it is not already set.
865 if (empty($this->properties->visible)) {
866 $this->properties->visible = 1;
869 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
870 // Make this event visible.
871 $this->properties->visible = 1;
872 } else {
873 // Make this event hidden.
874 $this->properties->visible = 0;
877 // Update the database to reflect this change.
878 $success = $DB->set_field('event', 'visible', $this->properties->visible, array('id' => $this->properties->id));
879 $calendarevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
881 // Prepare event data.
882 $eventargs = array(
883 'context' => $this->get_context(),
884 'objectid' => $this->properties->id,
885 'other' => array(
886 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
887 'timestart' => $this->properties->timestart,
888 'name' => $this->properties->name
891 $event = \core\event\calendar_event_updated::create($eventargs);
892 $event->add_record_snapshot('event', $calendarevent);
893 $event->trigger();
895 return $success;
899 * Returns an event object when provided with an event id.
901 * This function makes use of MUST_EXIST, if the event id passed in is invalid
902 * it will result in an exception being thrown.
904 * @param int|object $param event object or event id
905 * @return calendar_event
907 public static function load($param) {
908 global $DB;
909 if (is_object($param)) {
910 $event = new calendar_event($param);
911 } else {
912 $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST);
913 $event = new calendar_event($event);
915 return $event;
919 * Creates a new event and returns an event object
921 * @param \stdClass|array $properties An object containing event properties
922 * @param bool $checkcapability Check caps or not
923 * @throws \coding_exception
925 * @return calendar_event|bool The event object or false if it failed
927 public static function create($properties, $checkcapability = true) {
928 if (is_array($properties)) {
929 $properties = (object)$properties;
931 if (!is_object($properties)) {
932 throw new \coding_exception('When creating an event properties should be either an object or an assoc array');
934 $event = new calendar_event($properties);
935 if ($event->update($properties, $checkcapability)) {
936 return $event;
937 } else {
938 return false;
943 * Format the text using the external API.
945 * This function should we used when text formatting is required in external functions.
947 * @return array an array containing the text formatted and the text format
949 public function format_external_text() {
951 if ($this->editorcontext === null) {
952 // Switch on the event type to decide upon the appropriate context to use for this event.
953 $this->editorcontext = $this->get_context();
955 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
956 // We don't have a context here, do a normal format_text.
957 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id);
961 // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
962 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
963 $itemid = $this->properties->repeatid;
964 } else {
965 $itemid = $this->properties->id;
968 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id,
969 'calendar', 'event_description', $itemid);
974 * Calendar information class
976 * This class is used simply to organise the information pertaining to a calendar
977 * and is used primarily to make information easily available.
979 * @package core_calendar
980 * @category calendar
981 * @copyright 2010 Sam Hemelryk
982 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
984 class calendar_information {
987 * @var int The timestamp
989 * Rather than setting the day, month and year we will set a timestamp which will be able
990 * to be used by multiple calendars.
992 public $time;
994 /** @var int A course id */
995 public $courseid = null;
997 /** @var array An array of categories */
998 public $categories = array();
1000 /** @var int The current category */
1001 public $categoryid = null;
1003 /** @var array An array of courses */
1004 public $courses = array();
1006 /** @var array An array of groups */
1007 public $groups = array();
1009 /** @var array An array of users */
1010 public $users = array();
1012 /** @var context The anticipated context that the calendar is viewed in */
1013 public $context = null;
1016 * Creates a new instance
1018 * @param int $day the number of the day
1019 * @param int $month the number of the month
1020 * @param int $year the number of the year
1021 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
1022 * and $calyear to support multiple calendars
1024 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
1025 // If a day, month and year were passed then convert it to a timestamp. If these were passed
1026 // then we can assume the day, month and year are passed as Gregorian, as no where in core
1027 // should we be passing these values rather than the time. This is done for BC.
1028 if (!empty($day) || !empty($month) || !empty($year)) {
1029 $date = usergetdate(time());
1030 if (empty($day)) {
1031 $day = $date['mday'];
1033 if (empty($month)) {
1034 $month = $date['mon'];
1036 if (empty($year)) {
1037 $year = $date['year'];
1039 if (checkdate($month, $day, $year)) {
1040 $time = make_timestamp($year, $month, $day);
1041 } else {
1042 $time = time();
1046 $this->set_time($time);
1050 * Creates and set up a instance.
1052 * @param int $time the unixtimestamp representing the date we want to view.
1053 * @param int $courseid The ID of the course the user wishes to view.
1054 * @param int $categoryid The ID of the category the user wishes to view
1055 * If a courseid is specified, this value is ignored.
1056 * @return calendar_information
1058 public static function create($time, int $courseid, int $categoryid = null) : calendar_information {
1059 $calendar = new static(0, 0, 0, $time);
1060 if ($courseid != SITEID && !empty($courseid)) {
1061 // Course ID must be valid and existing.
1062 $course = get_course($courseid);
1063 $calendar->context = context_course::instance($course->id);
1065 if (!$course->visible && !is_role_switched($course->id)) {
1066 require_capability('moodle/course:viewhiddencourses', $calendar->context);
1069 $courses = [$course->id => $course];
1070 $category = (\coursecat::get($course->category, MUST_EXIST, true))->get_db_record();
1071 } else if (!empty($categoryid)) {
1072 $course = get_site();
1073 $courses = calendar_get_default_courses();
1075 // Filter available courses to those within this category or it's children.
1076 $ids = [$categoryid];
1077 $category = \coursecat::get($categoryid);
1078 $ids = array_merge($ids, array_keys($category->get_children()));
1079 $courses = array_filter($courses, function($course) use ($ids) {
1080 return array_search($course->category, $ids) !== false;
1082 $category = $category->get_db_record();
1084 $calendar->context = context_coursecat::instance($categoryid);
1085 } else {
1086 $course = get_site();
1087 $courses = calendar_get_default_courses();
1088 $category = null;
1090 $calendar->context = context_system::instance();
1093 $calendar->set_sources($course, $courses, $category);
1095 return $calendar;
1099 * Set the time period of this instance.
1101 * @param int $time the unixtimestamp representing the date we want to view.
1102 * @return $this
1104 public function set_time($time = null) {
1105 if (empty($time)) {
1106 $this->time = time();
1107 } else {
1108 $this->time = $time;
1111 return $this;
1115 * Initialize calendar information
1117 * @deprecated 3.4
1118 * @param stdClass $course object
1119 * @param array $coursestoload An array of courses [$course->id => $course]
1120 * @param bool $ignorefilters options to use filter
1122 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
1123 debugging('The prepare_for_view() function has been deprecated. Please update your code to use set_sources()',
1124 DEBUG_DEVELOPER);
1125 $this->set_sources($course, $coursestoload);
1129 * Set the sources for events within the calendar.
1131 * If no category is provided, then the category path for the current
1132 * course will be used.
1134 * @param stdClass $course The current course being viewed.
1135 * @param stdClass[] $courses The list of all courses currently accessible.
1136 * @param stdClass $category The current category to show.
1138 public function set_sources(stdClass $course, array $courses, stdClass $category = null) {
1139 global $USER;
1141 // A cousre must always be specified.
1142 $this->course = $course;
1143 $this->courseid = $course->id;
1145 list($courseids, $group, $user) = calendar_set_filters($courses);
1146 $this->courses = $courseids;
1147 $this->groups = $group;
1148 $this->users = $user;
1150 // Do not show category events by default.
1151 $this->categoryid = null;
1152 $this->categories = null;
1154 // Determine the correct category information to show.
1155 // When called with a course, the category of that course is usually included too.
1156 // When a category was specifically requested, it should be requested with the site id.
1157 if (SITEID !== $this->courseid) {
1158 // A specific course was requested.
1159 // Fetch the category that this course is in, along with all parents.
1160 // Do not include child categories of this category, as the user many not have enrolments in those siblings or children.
1161 $category = \coursecat::get($course->category, MUST_EXIST, true);
1162 $this->categoryid = $category->id;
1164 $this->categories = $category->get_parents();
1165 $this->categories[] = $category->id;
1166 } else if (null !== $category && $category->id > 0) {
1167 // A specific category was requested.
1168 // Fetch all parents of this category, along with all children too.
1169 $category = \coursecat::get($category->id);
1170 $this->categoryid = $category->id;
1172 // Build the category list.
1173 // This includes the current category.
1174 $this->categories = $category->get_parents();
1175 $this->categories[] = $category->id;
1176 $this->categories = array_merge($this->categories, $category->get_all_children_ids());
1177 } else if (SITEID === $this->courseid) {
1178 // The site was requested.
1179 // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
1181 // Grab the list of categories that this user has courses in.
1182 $coursecategories = array_flip(array_map(function($course) {
1183 return $course->category;
1184 }, $courses));
1186 $calcatcache = cache::make('core', 'calendar_categories');
1187 $this->categories = $calcatcache->get('site');
1188 if ($this->categories === false) {
1189 // Use the category id as the key in the following array. That way we do not have to remove duplicates.
1190 $categories = [];
1191 foreach (\coursecat::get_all() as $category) {
1192 if (isset($coursecategories[$category->id]) ||
1193 has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
1194 // If the user has access to a course in this category or can manage the category,
1195 // then they can see all parent categories too.
1196 $categories[$category->id] = true;
1197 foreach ($category->get_parents() as $catid) {
1198 $categories[$catid] = true;
1202 $this->categories = array_keys($categories);
1203 $calcatcache->set('site', $this->categories);
1209 * Ensures the date for the calendar is correct and either sets it to now
1210 * or throws a moodle_exception if not
1212 * @param bool $defaultonow use current time
1213 * @throws moodle_exception
1214 * @return bool validation of checkdate
1216 public function checkdate($defaultonow = true) {
1217 if (!checkdate($this->month, $this->day, $this->year)) {
1218 if ($defaultonow) {
1219 $now = usergetdate(time());
1220 $this->day = intval($now['mday']);
1221 $this->month = intval($now['mon']);
1222 $this->year = intval($now['year']);
1223 return true;
1224 } else {
1225 throw new moodle_exception('invaliddate');
1228 return true;
1232 * Gets todays timestamp for the calendar
1234 * @return int today timestamp
1236 public function timestamp_today() {
1237 return $this->time;
1240 * Gets tomorrows timestamp for the calendar
1242 * @return int tomorrow timestamp
1244 public function timestamp_tomorrow() {
1245 return strtotime('+1 day', $this->time);
1248 * Adds the pretend blocks for the calendar
1250 * @param core_calendar_renderer $renderer
1251 * @param bool $showfilters display filters, false is set as default
1252 * @param string|null $view preference view options (eg: day, month, upcoming)
1254 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
1255 if ($showfilters) {
1256 $filters = new block_contents();
1257 $filters->content = $renderer->event_filter();
1258 $filters->footer = '';
1259 $filters->title = get_string('eventskey', 'calendar');
1260 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
1262 $block = new block_contents;
1263 $block->content = $renderer->fake_block_threemonths($this);
1264 $block->footer = '';
1265 $block->title = get_string('monthlyview', 'calendar');
1266 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
1271 * Get calendar events.
1273 * @param int $tstart Start time of time range for events
1274 * @param int $tend End time of time range for events
1275 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
1276 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
1277 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
1278 * @param boolean $withduration whether only events starting within time range selected
1279 * or events in progress/already started selected as well
1280 * @param boolean $ignorehidden whether to select only visible events or all events
1281 * @param array|int|boolean $categories array of categories, category id or boolean for all/no course events
1282 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
1284 function calendar_get_events($tstart, $tend, $users, $groups, $courses,
1285 $withduration = true, $ignorehidden = true, $categories = []) {
1286 global $DB;
1288 $whereclause = '';
1289 $params = array();
1290 // Quick test.
1291 if (empty($users) && empty($groups) && empty($courses) && empty($categories)) {
1292 return array();
1295 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
1296 // Events from a number of users
1297 if(!empty($whereclause)) $whereclause .= ' OR';
1298 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED);
1299 $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)";
1300 $params = array_merge($params, $inparamsusers);
1301 } else if($users === true) {
1302 // Events from ALL users
1303 if(!empty($whereclause)) $whereclause .= ' OR';
1304 $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)';
1305 } else if($users === false) {
1306 // No user at all, do nothing
1309 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
1310 // Events from a number of groups
1311 if(!empty($whereclause)) $whereclause .= ' OR';
1312 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED);
1313 $whereclause .= " e.groupid $insqlgroups ";
1314 $params = array_merge($params, $inparamsgroups);
1315 } else if($groups === true) {
1316 // Events from ALL groups
1317 if(!empty($whereclause)) $whereclause .= ' OR ';
1318 $whereclause .= ' e.groupid != 0';
1320 // boolean false (no groups at all): we don't need to do anything
1322 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
1323 if(!empty($whereclause)) $whereclause .= ' OR';
1324 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED);
1325 $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
1326 $params = array_merge($params, $inparamscourses);
1327 } else if ($courses === true) {
1328 // Events from ALL courses
1329 if(!empty($whereclause)) $whereclause .= ' OR';
1330 $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
1333 if ((is_array($categories) && !empty($categories)) || is_numeric($categories)) {
1334 if (!empty($whereclause)) {
1335 $whereclause .= ' OR';
1337 list($insqlcategories, $inparamscategories) = $DB->get_in_or_equal($categories, SQL_PARAMS_NAMED);
1338 $whereclause .= " (e.groupid = 0 AND e.courseid = 0 AND e.categoryid $insqlcategories)";
1339 $params = array_merge($params, $inparamscategories);
1340 } else if ($categories === true) {
1341 // Events from ALL categories.
1342 if (!empty($whereclause)) {
1343 $whereclause .= ' OR';
1345 $whereclause .= ' (e.groupid = 0 AND e.courseid = 0 AND e.categoryid != 0)';
1348 // Security check: if, by now, we have NOTHING in $whereclause, then it means
1349 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
1350 // events no matter what. Allowing the code to proceed might return a completely
1351 // valid query with only time constraints, thus selecting ALL events in that time frame!
1352 if(empty($whereclause)) {
1353 return array();
1356 if($withduration) {
1357 $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1359 else {
1360 $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1362 if(!empty($whereclause)) {
1363 // We have additional constraints
1364 $whereclause = $timeclause.' AND ('.$whereclause.')';
1366 else {
1367 // Just basic time filtering
1368 $whereclause = $timeclause;
1371 if ($ignorehidden) {
1372 $whereclause .= ' AND e.visible = 1';
1375 $sql = "SELECT e.*
1376 FROM {event} e
1377 LEFT JOIN {modules} m ON e.modulename = m.name
1378 -- Non visible modules will have a value of 0.
1379 WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
1380 ORDER BY e.timestart";
1381 $events = $DB->get_records_sql($sql, $params);
1383 if ($events === false) {
1384 $events = array();
1386 return $events;
1390 * Return the days of the week.
1392 * @return array array of days
1394 function calendar_get_days() {
1395 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1396 return $calendartype->get_weekdays();
1400 * Get the subscription from a given id.
1402 * @since Moodle 2.5
1403 * @param int $id id of the subscription
1404 * @return stdClass Subscription record from DB
1405 * @throws moodle_exception for an invalid id
1407 function calendar_get_subscription($id) {
1408 global $DB;
1410 $cache = \cache::make('core', 'calendar_subscriptions');
1411 $subscription = $cache->get($id);
1412 if (empty($subscription)) {
1413 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
1414 $cache->set($id, $subscription);
1417 return $subscription;
1421 * Gets the first day of the week.
1423 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
1425 * @return int
1427 function calendar_get_starting_weekday() {
1428 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1429 return $calendartype->get_starting_weekday();
1433 * Get a HTML link to a course.
1435 * @param int|stdClass $course the course id or course object
1436 * @return string a link to the course (as HTML); empty if the course id is invalid
1438 function calendar_get_courselink($course) {
1439 if (!$course) {
1440 return '';
1443 if (!is_object($course)) {
1444 $course = calendar_get_course_cached($coursecache, $course);
1446 $context = \context_course::instance($course->id);
1447 $fullname = format_string($course->fullname, true, array('context' => $context));
1448 $url = new \moodle_url('/course/view.php', array('id' => $course->id));
1449 $link = \html_writer::link($url, $fullname);
1451 return $link;
1455 * Get current module cache.
1457 * Only use this method if you do not know courseid. Otherwise use:
1458 * get_fast_modinfo($courseid)->instances[$modulename][$instance]
1460 * @param array $modulecache in memory module cache
1461 * @param string $modulename name of the module
1462 * @param int $instance module instance number
1463 * @return stdClass|bool $module information
1465 function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
1466 if (!isset($modulecache[$modulename . '_' . $instance])) {
1467 $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
1470 return $modulecache[$modulename . '_' . $instance];
1474 * Get current course cache.
1476 * @param array $coursecache list of course cache
1477 * @param int $courseid id of the course
1478 * @return stdClass $coursecache[$courseid] return the specific course cache
1480 function calendar_get_course_cached(&$coursecache, $courseid) {
1481 if (!isset($coursecache[$courseid])) {
1482 $coursecache[$courseid] = get_course($courseid);
1484 return $coursecache[$courseid];
1488 * Get group from groupid for calendar display
1490 * @param int $groupid
1491 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1493 function calendar_get_group_cached($groupid) {
1494 static $groupscache = array();
1495 if (!isset($groupscache[$groupid])) {
1496 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1498 return $groupscache[$groupid];
1502 * Add calendar event metadata
1504 * @param stdClass $event event info
1505 * @return stdClass $event metadata
1507 function calendar_add_event_metadata($event) {
1508 global $CFG, $OUTPUT;
1510 // Support multilang in event->name.
1511 $event->name = format_string($event->name, true);
1513 if (!empty($event->modulename)) { // Activity event.
1514 // The module name is set. I will assume that it has to be displayed, and
1515 // also that it is an automatically-generated event. And of course that the
1516 // instace id and modulename are set correctly.
1517 $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
1518 if (!array_key_exists($event->instance, $instances)) {
1519 return;
1521 $module = $instances[$event->instance];
1523 $modulename = $module->get_module_type_name(false);
1524 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
1525 // Will be used as alt text if the event icon.
1526 $eventtype = get_string($event->eventtype, $event->modulename);
1527 } else {
1528 $eventtype = '';
1531 $event->icon = '<img src="' . s($module->get_icon_url()) . '" alt="' . s($eventtype) .
1532 '" title="' . s($modulename) . '" class="icon" />';
1533 $event->referer = html_writer::link($module->url, $event->name);
1534 $event->courselink = calendar_get_courselink($module->get_course());
1535 $event->cmid = $module->id;
1536 } else if ($event->courseid == SITEID) { // Site event.
1537 $event->icon = '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
1538 get_string('globalevent', 'calendar') . '" class="icon" />';
1539 $event->cssclass = 'calendar_event_global';
1540 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event.
1541 $event->icon = '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
1542 get_string('courseevent', 'calendar') . '" class="icon" />';
1543 $event->courselink = calendar_get_courselink($event->courseid);
1544 $event->cssclass = 'calendar_event_course';
1545 } else if ($event->groupid) { // Group event.
1546 if ($group = calendar_get_group_cached($event->groupid)) {
1547 $groupname = format_string($group->name, true, \context_course::instance($group->courseid));
1548 } else {
1549 $groupname = '';
1551 $event->icon = \html_writer::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
1552 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
1553 $event->courselink = calendar_get_courselink($event->courseid) . ', ' . $groupname;
1554 $event->cssclass = 'calendar_event_group';
1555 } else if ($event->userid) { // User event.
1556 $event->icon = '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
1557 get_string('userevent', 'calendar') . '" class="icon" />';
1558 $event->cssclass = 'calendar_event_user';
1561 return $event;
1565 * Get calendar events by id.
1567 * @since Moodle 2.5
1568 * @param array $eventids list of event ids
1569 * @return array Array of event entries, empty array if nothing found
1571 function calendar_get_events_by_id($eventids) {
1572 global $DB;
1574 if (!is_array($eventids) || empty($eventids)) {
1575 return array();
1578 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
1579 $wheresql = "id $wheresql";
1581 return $DB->get_records_select('event', $wheresql, $params);
1585 * Get control options for calendar.
1587 * @param string $type of calendar
1588 * @param array $data calendar information
1589 * @return string $content return available control for the calender in html
1591 function calendar_top_controls($type, $data) {
1592 global $PAGE, $OUTPUT;
1594 // Get the calendar type we are using.
1595 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1597 $content = '';
1599 // Ensure course id passed if relevant.
1600 $courseid = '';
1601 if (!empty($data['id'])) {
1602 $courseid = '&amp;course=' . $data['id'];
1605 // If we are passing a month and year then we need to convert this to a timestamp to
1606 // support multiple calendars. No where in core should these be passed, this logic
1607 // here is for third party plugins that may use this function.
1608 if (!empty($data['m']) && !empty($date['y'])) {
1609 if (!isset($data['d'])) {
1610 $data['d'] = 1;
1612 if (!checkdate($data['m'], $data['d'], $data['y'])) {
1613 $time = time();
1614 } else {
1615 $time = make_timestamp($data['y'], $data['m'], $data['d']);
1617 } else if (!empty($data['time'])) {
1618 $time = $data['time'];
1619 } else {
1620 $time = time();
1623 // Get the date for the calendar type.
1624 $date = $calendartype->timestamp_to_date_array($time);
1626 $urlbase = $PAGE->url;
1628 // We need to get the previous and next months in certain cases.
1629 if ($type == 'frontpage' || $type == 'course' || $type == 'month') {
1630 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1631 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
1632 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
1633 $prevmonthtime['hour'], $prevmonthtime['minute']);
1635 $nextmonth = calendar_add_month($date['mon'], $date['year']);
1636 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
1637 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
1638 $nextmonthtime['hour'], $nextmonthtime['minute']);
1641 switch ($type) {
1642 case 'frontpage':
1643 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1644 true, $prevmonthtime);
1645 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true,
1646 $nextmonthtime);
1647 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1648 false, false, false, $time);
1650 if (!empty($data['id'])) {
1651 $calendarlink->param('course', $data['id']);
1654 $right = $nextlink;
1656 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1657 $content .= $prevlink . '<span class="hide"> | </span>';
1658 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1659 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1660 ), array('class' => 'current'));
1661 $content .= '<span class="hide"> | </span>' . $right;
1662 $content .= "<span class=\"clearer\"><!-- --></span>\n";
1663 $content .= \html_writer::end_tag('div');
1665 break;
1666 case 'course':
1667 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1668 true, $prevmonthtime);
1669 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false,
1670 true, $nextmonthtime);
1671 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1672 false, false, false, $time);
1674 if (!empty($data['id'])) {
1675 $calendarlink->param('course', $data['id']);
1678 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1679 $content .= $prevlink . '<span class="hide"> | </span>';
1680 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1681 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1682 ), array('class' => 'current'));
1683 $content .= '<span class="hide"> | </span>' . $nextlink;
1684 $content .= "<span class=\"clearer\"><!-- --></span>";
1685 $content .= \html_writer::end_tag('div');
1686 break;
1687 case 'upcoming':
1688 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'upcoming')),
1689 false, false, false, $time);
1690 if (!empty($data['id'])) {
1691 $calendarlink->param('course', $data['id']);
1693 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1694 $content .= \html_writer::tag('div', $calendarlink, array('class' => 'centered'));
1695 break;
1696 case 'display':
1697 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1698 false, false, false, $time);
1699 if (!empty($data['id'])) {
1700 $calendarlink->param('course', $data['id']);
1702 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1703 $content .= \html_writer::tag('h3', $calendarlink);
1704 break;
1705 case 'month':
1706 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1707 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $prevmonthtime);
1708 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1709 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $nextmonthtime);
1711 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1712 $content .= $prevlink . '<span class="hide"> | </span>';
1713 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1714 $content .= '<span class="hide"> | </span>' . $nextlink;
1715 $content .= '<span class="clearer"><!-- --></span>';
1716 $content .= \html_writer::end_tag('div')."\n";
1717 break;
1718 case 'day':
1719 $days = calendar_get_days();
1721 $prevtimestamp = strtotime('-1 day', $time);
1722 $nexttimestamp = strtotime('+1 day', $time);
1724 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1725 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1727 $prevname = $days[$prevdate['wday']]['fullname'];
1728 $nextname = $days[$nextdate['wday']]['fullname'];
1729 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&amp;', false, false,
1730 false, false, $prevtimestamp);
1731 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&amp;', false, false, false,
1732 false, $nexttimestamp);
1734 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1735 $content .= $prevlink;
1736 $content .= '<span class="hide"> | </span><span class="current">' .userdate($time,
1737 get_string('strftimedaydate')) . '</span>';
1738 $content .= '<span class="hide"> | </span>' . $nextlink;
1739 $content .= "<span class=\"clearer\"><!-- --></span>";
1740 $content .= \html_writer::end_tag('div') . "\n";
1742 break;
1745 return $content;
1749 * Return the representation day.
1751 * @param int $tstamp Timestamp in GMT
1752 * @param int|bool $now current Unix timestamp
1753 * @param bool $usecommonwords
1754 * @return string the formatted date/time
1756 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1757 static $shortformat;
1759 if (empty($shortformat)) {
1760 $shortformat = get_string('strftimedayshort');
1763 if ($now === false) {
1764 $now = time();
1767 // To have it in one place, if a change is needed.
1768 $formal = userdate($tstamp, $shortformat);
1770 $datestamp = usergetdate($tstamp);
1771 $datenow = usergetdate($now);
1773 if ($usecommonwords == false) {
1774 // We don't want words, just a date.
1775 return $formal;
1776 } else if ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1777 return get_string('today', 'calendar');
1778 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1779 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12
1780 && $datenow['yday'] == 1)) {
1781 return get_string('yesterday', 'calendar');
1782 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1783 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12
1784 && $datestamp['yday'] == 1)) {
1785 return get_string('tomorrow', 'calendar');
1786 } else {
1787 return $formal;
1792 * return the formatted representation time.
1795 * @param int $time the timestamp in UTC, as obtained from the database
1796 * @return string the formatted date/time
1798 function calendar_time_representation($time) {
1799 static $langtimeformat = null;
1801 if ($langtimeformat === null) {
1802 $langtimeformat = get_string('strftimetime');
1805 $timeformat = get_user_preferences('calendar_timeformat');
1806 if (empty($timeformat)) {
1807 $timeformat = get_config(null, 'calendar_site_timeformat');
1810 // Allow language customization of selected time format.
1811 if ($timeformat === CALENDAR_TF_12) {
1812 $timeformat = get_string('strftimetime12', 'langconfig');
1813 } else if ($timeformat === CALENDAR_TF_24) {
1814 $timeformat = get_string('strftimetime24', 'langconfig');
1817 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
1821 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1823 * @param string|moodle_url $linkbase
1824 * @param int $d The number of the day.
1825 * @param int $m The number of the month.
1826 * @param int $y The number of the year.
1827 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1828 * $m and $y are kept for backwards compatibility.
1829 * @return moodle_url|null $linkbase
1831 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1832 if (empty($linkbase)) {
1833 return null;
1836 if (!($linkbase instanceof \moodle_url)) {
1837 $linkbase = new \moodle_url($linkbase);
1840 $linkbase->param('time', calendar_get_timestamp($d, $m, $y, $time));
1842 return $linkbase;
1846 * Build and return a previous month HTML link, with an arrow.
1848 * @param string $text The text label.
1849 * @param string|moodle_url $linkbase The URL stub.
1850 * @param int $d The number of the date.
1851 * @param int $m The number of the month.
1852 * @param int $y year The number of the year.
1853 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1854 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1855 * $m and $y are kept for backwards compatibility.
1856 * @return string HTML string.
1858 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1859 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1861 if (empty($href)) {
1862 return $text;
1865 $attrs = [
1866 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1867 'data-drop-zone' => 'nav-link',
1870 return link_arrow_left($text, $href->out(false), $accesshide, 'previous', $attrs);
1874 * Build and return a next month HTML link, with an arrow.
1876 * @param string $text The text label.
1877 * @param string|moodle_url $linkbase The URL stub.
1878 * @param int $d the number of the Day
1879 * @param int $m The number of the month.
1880 * @param int $y The number of the year.
1881 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1882 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1883 * $m and $y are kept for backwards compatibility.
1884 * @return string HTML string.
1886 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1887 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1889 if (empty($href)) {
1890 return $text;
1893 $attrs = [
1894 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1895 'data-drop-zone' => 'nav-link',
1898 return link_arrow_right($text, $href->out(false), $accesshide, 'next', $attrs);
1902 * Return the number of days in month.
1904 * @param int $month the number of the month.
1905 * @param int $year the number of the year
1906 * @return int
1908 function calendar_days_in_month($month, $year) {
1909 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1910 return $calendartype->get_num_days_in_month($year, $month);
1914 * Get the next following month.
1916 * @param int $month the number of the month.
1917 * @param int $year the number of the year.
1918 * @return array the following month
1920 function calendar_add_month($month, $year) {
1921 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1922 return $calendartype->get_next_month($year, $month);
1926 * Get the previous month.
1928 * @param int $month the number of the month.
1929 * @param int $year the number of the year.
1930 * @return array previous month
1932 function calendar_sub_month($month, $year) {
1933 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1934 return $calendartype->get_prev_month($year, $month);
1938 * Get per-day basis events
1940 * @param array $events list of events
1941 * @param int $month the number of the month
1942 * @param int $year the number of the year
1943 * @param array $eventsbyday event on specific day
1944 * @param array $durationbyday duration of the event in days
1945 * @param array $typesbyday event type (eg: global, course, user, or group)
1946 * @param array $courses list of courses
1947 * @return void
1949 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1950 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1952 $eventsbyday = array();
1953 $typesbyday = array();
1954 $durationbyday = array();
1956 if ($events === false) {
1957 return;
1960 foreach ($events as $event) {
1961 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
1962 if ($event->timeduration) {
1963 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
1964 } else {
1965 $enddate = $startdate;
1968 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair.
1969 if (!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) &&
1970 ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1971 continue;
1974 $eventdaystart = intval($startdate['mday']);
1976 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
1977 // Give the event to its day.
1978 $eventsbyday[$eventdaystart][] = $event->id;
1980 // Mark the day as having such an event.
1981 if ($event->courseid == SITEID && $event->groupid == 0) {
1982 $typesbyday[$eventdaystart]['startglobal'] = true;
1983 // Set event class for global event.
1984 $events[$event->id]->class = 'calendar_event_global';
1985 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1986 $typesbyday[$eventdaystart]['startcourse'] = true;
1987 // Set event class for course event.
1988 $events[$event->id]->class = 'calendar_event_course';
1989 } else if ($event->groupid) {
1990 $typesbyday[$eventdaystart]['startgroup'] = true;
1991 // Set event class for group event.
1992 $events[$event->id]->class = 'calendar_event_group';
1993 } else if ($event->userid) {
1994 $typesbyday[$eventdaystart]['startuser'] = true;
1995 // Set event class for user event.
1996 $events[$event->id]->class = 'calendar_event_user';
2000 if ($event->timeduration == 0) {
2001 // Proceed with the next.
2002 continue;
2005 // The event starts on $month $year or before.
2006 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2007 $lowerbound = intval($startdate['mday']);
2008 } else {
2009 $lowerbound = 0;
2012 // Also, it ends on $month $year or later.
2013 if ($enddate['mon'] == $month && $enddate['year'] == $year) {
2014 $upperbound = intval($enddate['mday']);
2015 } else {
2016 $upperbound = calendar_days_in_month($month, $year);
2019 // Mark all days between $lowerbound and $upperbound (inclusive) as duration.
2020 for ($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
2021 $durationbyday[$i][] = $event->id;
2022 if ($event->courseid == SITEID && $event->groupid == 0) {
2023 $typesbyday[$i]['durationglobal'] = true;
2024 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
2025 $typesbyday[$i]['durationcourse'] = true;
2026 } else if ($event->groupid) {
2027 $typesbyday[$i]['durationgroup'] = true;
2028 } else if ($event->userid) {
2029 $typesbyday[$i]['durationuser'] = true;
2034 return;
2038 * Returns the courses to load events for.
2040 * @param array $courseeventsfrom An array of courses to load calendar events for
2041 * @param bool $ignorefilters specify the use of filters, false is set as default
2042 * @return array An array of courses, groups, and user to load calendar events for based upon filters
2044 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
2045 global $USER, $CFG;
2047 // For backwards compatability we have to check whether the courses array contains
2048 // just id's in which case we need to load course objects.
2049 $coursestoload = array();
2050 foreach ($courseeventsfrom as $id => $something) {
2051 if (!is_object($something)) {
2052 $coursestoload[] = $id;
2053 unset($courseeventsfrom[$id]);
2057 $courses = array();
2058 $user = false;
2059 $group = false;
2061 // Get the capabilities that allow seeing group events from all groups.
2062 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
2064 $isloggedin = isloggedin();
2066 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
2067 $courses = array_keys($courseeventsfrom);
2069 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
2070 $courses[] = SITEID;
2072 $courses = array_unique($courses);
2073 sort($courses);
2075 if (!empty($courses) && in_array(SITEID, $courses)) {
2076 // Sort courses for consistent colour highlighting.
2077 // Effectively ignoring SITEID as setting as last course id.
2078 $key = array_search(SITEID, $courses);
2079 unset($courses[$key]);
2080 $courses[] = SITEID;
2083 if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
2084 $user = $USER->id;
2087 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
2089 if (count($courseeventsfrom) == 1) {
2090 $course = reset($courseeventsfrom);
2091 if (has_any_capability($allgroupscaps, \context_course::instance($course->id))) {
2092 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
2093 $group = array_keys($coursegroups);
2096 if ($group === false) {
2097 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, \context_system::instance())) {
2098 $group = true;
2099 } else if ($isloggedin) {
2100 $groupids = array();
2101 foreach ($courseeventsfrom as $courseid => $course) {
2102 // If the user is an editing teacher in there.
2103 if (!empty($USER->groupmember[$course->id])) {
2104 // We've already cached the users groups for this course so we can just use that.
2105 $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
2106 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2107 // If this course has groups, show events from all of those related to the current user.
2108 $coursegroups = groups_get_user_groups($course->id, $USER->id);
2109 $groupids = array_merge($groupids, $coursegroups['0']);
2112 if (!empty($groupids)) {
2113 $group = $groupids;
2118 if (empty($courses)) {
2119 $courses = false;
2122 return array($courses, $group, $user);
2126 * Return the capability for viewing a calendar event.
2128 * @param calendar_event $event event object
2129 * @return boolean
2131 function calendar_view_event_allowed(calendar_event $event) {
2132 global $USER;
2134 // Anyone can see site events.
2135 if ($event->courseid && $event->courseid == SITEID) {
2136 return true;
2139 // If a user can manage events at the site level they can see any event.
2140 $sitecontext = \context_system::instance();
2141 // If user has manageentries at site level, return true.
2142 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2143 return true;
2146 if (!empty($event->groupid)) {
2147 // If it is a group event we need to be able to manage events in the course, or be in the group.
2148 if (has_capability('moodle/calendar:manageentries', $event->context) ||
2149 has_capability('moodle/calendar:managegroupentries', $event->context)) {
2150 return true;
2153 $mycourses = enrol_get_my_courses('id');
2154 return isset($mycourses[$event->courseid]) && groups_is_member($event->groupid);
2155 } else if ($event->modulename) {
2156 // If this is a module event we need to be able to see the module.
2157 $coursemodules = [];
2158 $courseid = 0;
2159 // Override events do not have the courseid set.
2160 if ($event->courseid) {
2161 $courseid = $event->courseid;
2162 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2163 } else {
2164 $cmraw = get_coursemodule_from_instance($event->modulename, $event->instance, 0, false, MUST_EXIST);
2165 $courseid = $cmraw->course;
2166 $coursemodules = get_fast_modinfo($cmraw->course)->instances;
2168 $hasmodule = isset($coursemodules[$event->modulename]);
2169 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2171 // If modinfo doesn't know about the module, return false to be safe.
2172 if (!$hasmodule || !$hasinstance) {
2173 return false;
2176 // Must be able to see the course and the module - MDL-59304.
2177 $cm = $coursemodules[$event->modulename][$event->instance];
2178 if (!$cm->uservisible) {
2179 return false;
2181 $mycourses = enrol_get_my_courses('id');
2182 return isset($mycourses[$courseid]);
2183 } else if ($event->categoryid) {
2184 // If this is a category we need to be able to see the category.
2185 $cat = \coursecat::get($event->categoryid, IGNORE_MISSING);
2186 if (!$cat) {
2187 return false;
2189 return true;
2190 } else if (!empty($event->courseid)) {
2191 // If it is a course event we need to be able to manage events in the course, or be in the course.
2192 if (has_capability('moodle/calendar:manageentries', $event->context)) {
2193 return true;
2195 $mycourses = enrol_get_my_courses('id');
2196 return isset($mycourses[$event->courseid]);
2197 } else if ($event->userid) {
2198 if ($event->userid != $USER->id) {
2199 // No-one can ever see another users events.
2200 return false;
2202 return true;
2203 } else {
2204 throw new moodle_exception('unknown event type');
2207 return false;
2211 * Return the capability for editing calendar event.
2213 * @param calendar_event $event event object
2214 * @param bool $manualedit is the event being edited manually by the user
2215 * @return bool capability to edit event
2217 function calendar_edit_event_allowed($event, $manualedit = false) {
2218 global $USER, $DB;
2220 // Must be logged in.
2221 if (!isloggedin()) {
2222 return false;
2225 // Can not be using guest account.
2226 if (isguestuser()) {
2227 return false;
2230 if ($manualedit && !empty($event->modulename)) {
2231 $hascallback = component_callback_exists(
2232 'mod_' . $event->modulename,
2233 'core_calendar_event_timestart_updated'
2236 if (!$hascallback) {
2237 // If the activity hasn't implemented the correct callback
2238 // to handle changes to it's events then don't allow any
2239 // manual changes to them.
2240 return false;
2243 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2244 $hasmodule = isset($coursemodules[$event->modulename]);
2245 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2247 // If modinfo doesn't know about the module, return false to be safe.
2248 if (!$hasmodule || !$hasinstance) {
2249 return false;
2252 $coursemodule = $coursemodules[$event->modulename][$event->instance];
2253 $context = context_module::instance($coursemodule->id);
2254 // This is the capability that allows a user to modify the activity
2255 // settings. Since the activity generated this event we need to check
2256 // that the current user has the same capability before allowing them
2257 // to update the event because the changes to the event will be
2258 // reflected within the activity.
2259 return has_capability('moodle/course:manageactivities', $context);
2262 // You cannot edit URL based calendar subscription events presently.
2263 if (!empty($event->subscriptionid)) {
2264 if (!empty($event->subscription->url)) {
2265 // This event can be updated externally, so it cannot be edited.
2266 return false;
2270 $sitecontext = \context_system::instance();
2272 // If user has manageentries at site level, return true.
2273 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2274 return true;
2277 // If groupid is set, it's definitely a group event.
2278 if (!empty($event->groupid)) {
2279 // Allow users to add/edit group events if -
2280 // 1) They have manageentries for the course OR
2281 // 2) They have managegroupentries AND are in the group.
2282 $group = $DB->get_record('groups', array('id' => $event->groupid));
2283 return $group && (
2284 has_capability('moodle/calendar:manageentries', $event->context) ||
2285 (has_capability('moodle/calendar:managegroupentries', $event->context)
2286 && groups_is_member($event->groupid)));
2287 } else if (!empty($event->courseid)) {
2288 // If groupid is not set, but course is set, it's definitely a course event.
2289 return has_capability('moodle/calendar:manageentries', $event->context);
2290 } else if (!empty($event->categoryid)) {
2291 // If groupid is not set, but category is set, it's definitely a category event.
2292 return has_capability('moodle/calendar:manageentries', $event->context);
2293 } else if (!empty($event->userid) && $event->userid == $USER->id) {
2294 // If course is not set, but userid id set, it's a user event.
2295 return (has_capability('moodle/calendar:manageownentries', $event->context));
2296 } else if (!empty($event->userid)) {
2297 return (has_capability('moodle/calendar:manageentries', $event->context));
2300 return false;
2304 * Return the capability for deleting a calendar event.
2306 * @param calendar_event $event The event object
2307 * @return bool Whether the user has permission to delete the event or not.
2309 function calendar_delete_event_allowed($event) {
2310 // Only allow delete if you have capabilities and it is not an module event.
2311 return (calendar_edit_event_allowed($event) && empty($event->modulename));
2315 * Returns the default courses to display on the calendar when there isn't a specific
2316 * course to display.
2318 * @param int $courseid (optional) If passed, an additional course can be returned for admins (the current course).
2319 * @param string $fields Comma separated list of course fields to return.
2320 * @param bool $canmanage If true, this will return the list of courses the current user can create events in, rather
2321 * than the list of courses they see events from (an admin can always add events in a course
2322 * calendar, even if they are not enrolled in the course).
2323 * @return array $courses Array of courses to display
2325 function calendar_get_default_courses($courseid = null, $fields = '*', $canmanage=false) {
2326 global $CFG, $DB;
2328 if (!isloggedin()) {
2329 return array();
2332 if (has_capability('moodle/calendar:manageentries', context_system::instance()) &&
2333 (!empty($CFG->calendar_adminseesall) || $canmanage)) {
2335 // Add a c. prefix to every field as expected by get_courses function.
2336 $fieldlist = explode(',', $fields);
2338 $prefixedfields = array_map(function($value) {
2339 return 'c.' . trim($value);
2340 }, $fieldlist);
2341 $courses = get_courses('all', 'c.shortname', implode(',', $prefixedfields));
2342 } else {
2343 $courses = enrol_get_my_courses($fields);
2346 if ($courseid && $courseid != SITEID) {
2347 if (empty($courses[$courseid]) && has_capability('moodle/calendar:manageentries', context_system::instance())) {
2348 // Allow a site admin to see calendars from courses he is not enrolled in.
2349 // This will come from $COURSE.
2350 $courses[$courseid] = get_course($courseid);
2354 return $courses;
2358 * Get event format time.
2360 * @param calendar_event $event event object
2361 * @param int $now current time in gmt
2362 * @param array $linkparams list of params for event link
2363 * @param bool $usecommonwords the words as formatted date/time.
2364 * @param int $showtime determine the show time GMT timestamp
2365 * @return string $eventtime link/string for event time
2367 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
2368 $starttime = $event->timestart;
2369 $endtime = $event->timestart + $event->timeduration;
2371 if (empty($linkparams) || !is_array($linkparams)) {
2372 $linkparams = array();
2375 $linkparams['view'] = 'day';
2377 // OK, now to get a meaningful display.
2378 // Check if there is a duration for this event.
2379 if ($event->timeduration) {
2380 // Get the midnight of the day the event will start.
2381 $usermidnightstart = usergetmidnight($starttime);
2382 // Get the midnight of the day the event will end.
2383 $usermidnightend = usergetmidnight($endtime);
2384 // Check if we will still be on the same day.
2385 if ($usermidnightstart == $usermidnightend) {
2386 // Check if we are running all day.
2387 if ($event->timeduration == DAYSECS) {
2388 $time = get_string('allday', 'calendar');
2389 } else { // Specify the time we will be running this from.
2390 $datestart = calendar_time_representation($starttime);
2391 $dateend = calendar_time_representation($endtime);
2392 $time = $datestart . ' <strong>&raquo;</strong> ' . $dateend;
2395 // Set printable representation.
2396 if (!$showtime) {
2397 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2398 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2399 $eventtime = \html_writer::link($url, $day) . ', ' . $time;
2400 } else {
2401 $eventtime = $time;
2403 } else { // It must spans two or more days.
2404 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
2405 if ($showtime == $usermidnightstart) {
2406 $daystart = '';
2408 $timestart = calendar_time_representation($event->timestart);
2409 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
2410 if ($showtime == $usermidnightend) {
2411 $dayend = '';
2413 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
2415 // Set printable representation.
2416 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2417 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2418 $eventtime = $timestart . ' <strong>&raquo;</strong> ' . \html_writer::link($url, $dayend) . $timeend;
2419 } else {
2420 // The event is in the future, print start and end links.
2421 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2422 $eventtime = \html_writer::link($url, $daystart) . $timestart . ' <strong>&raquo;</strong> ';
2424 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2425 $eventtime .= \html_writer::link($url, $dayend) . $timeend;
2428 } else { // There is no time duration.
2429 $time = calendar_time_representation($event->timestart);
2430 // Set printable representation.
2431 if (!$showtime) {
2432 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2433 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2434 $eventtime = \html_writer::link($url, $day) . ', ' . trim($time);
2435 } else {
2436 $eventtime = $time;
2440 // Check if It has expired.
2441 if ($event->timestart + $event->timeduration < $now) {
2442 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2445 return $eventtime;
2449 * Checks to see if the requested type of event should be shown for the given user.
2451 * @param int $type The type to check the display for (default is to display all)
2452 * @param stdClass|int|null $user The user to check for - by default the current user
2453 * @return bool True if the tyep should be displayed false otherwise
2455 function calendar_show_event_type($type, $user = null) {
2456 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
2458 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2459 global $SESSION;
2460 if (!isset($SESSION->calendarshoweventtype)) {
2461 $SESSION->calendarshoweventtype = $default;
2463 return $SESSION->calendarshoweventtype & $type;
2464 } else {
2465 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2470 * Sets the display of the event type given $display.
2472 * If $display = true the event type will be shown.
2473 * If $display = false the event type will NOT be shown.
2474 * If $display = null the current value will be toggled and saved.
2476 * @param int $type object of CALENDAR_EVENT_XXX
2477 * @param bool $display option to display event type
2478 * @param stdClass|int $user moodle user object or id, null means current user
2480 function calendar_set_event_type_display($type, $display = null, $user = null) {
2481 $persist = get_user_preferences('calendar_persistflt', 0, $user);
2482 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP
2483 + CALENDAR_EVENT_USER + CALENDAR_EVENT_COURSECAT;
2484 if ($persist === 0) {
2485 global $SESSION;
2486 if (!isset($SESSION->calendarshoweventtype)) {
2487 $SESSION->calendarshoweventtype = $default;
2489 $preference = $SESSION->calendarshoweventtype;
2490 } else {
2491 $preference = get_user_preferences('calendar_savedflt', $default, $user);
2493 $current = $preference & $type;
2494 if ($display === null) {
2495 $display = !$current;
2497 if ($display && !$current) {
2498 $preference += $type;
2499 } else if (!$display && $current) {
2500 $preference -= $type;
2502 if ($persist === 0) {
2503 $SESSION->calendarshoweventtype = $preference;
2504 } else {
2505 if ($preference == $default) {
2506 unset_user_preference('calendar_savedflt', $user);
2507 } else {
2508 set_user_preference('calendar_savedflt', $preference, $user);
2514 * Get calendar's allowed types.
2516 * @param stdClass $allowed list of allowed edit for event type
2517 * @param stdClass|int $course object of a course or course id
2518 * @param array $groups array of groups for the given course
2519 * @param stdClass|int $category object of a category
2521 function calendar_get_allowed_types(&$allowed, $course = null, $groups = null, $category = null) {
2522 global $USER, $DB;
2524 $allowed = new \stdClass();
2525 $allowed->user = has_capability('moodle/calendar:manageownentries', \context_system::instance());
2526 $allowed->groups = false;
2527 $allowed->courses = false;
2528 $allowed->categories = false;
2529 $allowed->site = has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID));
2530 $getgroupsfunc = function($course, $context, $user) use ($groups) {
2531 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2532 if (has_capability('moodle/site:accessallgroups', $context)) {
2533 return is_null($groups) ? groups_get_all_groups($course->id) : $groups;
2534 } else {
2535 if (is_null($groups)) {
2536 return groups_get_all_groups($course->id, $user->id);
2537 } else {
2538 return array_filter($groups, function($group) use ($user) {
2539 return isset($group->members[$user->id]);
2545 return false;
2548 if (!empty($course)) {
2549 if (!is_object($course)) {
2550 $course = $DB->get_record('course', array('id' => $course), 'id, groupmode, groupmodeforce', MUST_EXIST);
2552 if ($course->id != SITEID) {
2553 $coursecontext = \context_course::instance($course->id);
2554 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
2556 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2557 $allowed->courses = array($course->id => 1);
2558 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2559 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
2560 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2565 if (!empty($category)) {
2566 $catcontext = \context_coursecat::instance($category->id);
2567 if (has_capability('moodle/category:manage', $catcontext)) {
2568 $allowed->categories = [$category->id => 1];
2574 * Get all of the allowed types for all of the courses and groups
2575 * the logged in user belongs to.
2577 * The returned array will optionally have 5 keys:
2578 * 'user' : true if the logged in user can create user events
2579 * 'site' : true if the logged in user can create site events
2580 * 'category' : array of course categories that the user can create events for
2581 * 'course' : array of courses that the user can create events for
2582 * 'group': array of groups that the user can create events for
2583 * 'groupcourses' : array of courses that the groups belong to (can
2584 * be different from the list in 'course'.
2586 * @return array The array of allowed types.
2588 function calendar_get_all_allowed_types() {
2589 global $CFG, $USER, $DB;
2591 require_once($CFG->libdir . '/enrollib.php');
2593 $types = [];
2595 $allowed = new stdClass();
2597 calendar_get_allowed_types($allowed);
2599 if ($allowed->user) {
2600 $types['user'] = true;
2603 if ($allowed->site) {
2604 $types['site'] = true;
2607 if (coursecat::has_manage_capability_on_any()) {
2608 $types['category'] = coursecat::make_categories_list('moodle/category:manage');
2611 // This function warms the context cache for the course so the calls
2612 // to load the course context in calendar_get_allowed_types don't result
2613 // in additional DB queries.
2614 $courses = calendar_get_default_courses(null, 'id, groupmode, groupmodeforce', true);
2616 // We want to pre-fetch all of the groups for each course in a single
2617 // query to avoid calendar_get_allowed_types from hitting the DB for
2618 // each separate course.
2619 $groups = groups_get_all_groups_for_courses($courses);
2621 foreach ($courses as $course) {
2622 $coursegroups = isset($groups[$course->id]) ? $groups[$course->id] : null;
2623 calendar_get_allowed_types($allowed, $course, $coursegroups);
2625 if (!empty($allowed->courses)) {
2626 $types['course'][$course->id] = $course;
2629 if (!empty($allowed->groups)) {
2630 $types['groupcourses'][$course->id] = $course;
2632 if (!isset($types['group'])) {
2633 $types['group'] = array_values($allowed->groups);
2634 } else {
2635 $types['group'] = array_merge($types['group'], array_values($allowed->groups));
2640 return $types;
2644 * See if user can add calendar entries at all used to print the "New Event" button.
2646 * @param stdClass $course object of a course or course id
2647 * @return bool has the capability to add at least one event type
2649 function calendar_user_can_add_event($course) {
2650 if (!isloggedin() || isguestuser()) {
2651 return false;
2654 calendar_get_allowed_types($allowed, $course);
2656 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->categories || $allowed->site);
2660 * Check wether the current user is permitted to add events.
2662 * @param stdClass $event object of event
2663 * @return bool has the capability to add event
2665 function calendar_add_event_allowed($event) {
2666 global $USER, $DB;
2668 // Can not be using guest account.
2669 if (!isloggedin() or isguestuser()) {
2670 return false;
2673 $sitecontext = \context_system::instance();
2675 // If user has manageentries at site level, always return true.
2676 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2677 return true;
2680 switch ($event->eventtype) {
2681 case 'category':
2682 return has_capability('moodle/category:manage', $event->context);
2683 case 'course':
2684 return has_capability('moodle/calendar:manageentries', $event->context);
2685 case 'group':
2686 // Allow users to add/edit group events if -
2687 // 1) They have manageentries (= entries for whole course).
2688 // 2) They have managegroupentries AND are in the group.
2689 $group = $DB->get_record('groups', array('id' => $event->groupid));
2690 return $group && (
2691 has_capability('moodle/calendar:manageentries', $event->context) ||
2692 (has_capability('moodle/calendar:managegroupentries', $event->context)
2693 && groups_is_member($event->groupid)));
2694 case 'user':
2695 if ($event->userid == $USER->id) {
2696 return (has_capability('moodle/calendar:manageownentries', $event->context));
2698 // There is intentionally no 'break'.
2699 case 'site':
2700 return has_capability('moodle/calendar:manageentries', $event->context);
2701 default:
2702 return has_capability('moodle/calendar:manageentries', $event->context);
2707 * Returns option list for the poll interval setting.
2709 * @return array An array of poll interval options. Interval => description.
2711 function calendar_get_pollinterval_choices() {
2712 return array(
2713 '0' => new \lang_string('never', 'calendar'),
2714 HOURSECS => new \lang_string('hourly', 'calendar'),
2715 DAYSECS => new \lang_string('daily', 'calendar'),
2716 WEEKSECS => new \lang_string('weekly', 'calendar'),
2717 '2628000' => new \lang_string('monthly', 'calendar'),
2718 YEARSECS => new \lang_string('annually', 'calendar')
2723 * Returns option list of available options for the calendar event type, given the current user and course.
2725 * @param int $courseid The id of the course
2726 * @return array An array containing the event types the user can create.
2728 function calendar_get_eventtype_choices($courseid) {
2729 $choices = array();
2730 $allowed = new \stdClass;
2731 calendar_get_allowed_types($allowed, $courseid);
2733 if ($allowed->user) {
2734 $choices['user'] = get_string('userevents', 'calendar');
2736 if ($allowed->site) {
2737 $choices['site'] = get_string('siteevents', 'calendar');
2739 if (!empty($allowed->courses)) {
2740 $choices['course'] = get_string('courseevents', 'calendar');
2742 if (!empty($allowed->categories)) {
2743 $choices['category'] = get_string('categoryevents', 'calendar');
2745 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2746 $choices['group'] = get_string('group');
2749 return array($choices, $allowed->groups);
2753 * Add an iCalendar subscription to the database.
2755 * @param stdClass $sub The subscription object (e.g. from the form)
2756 * @return int The insert ID, if any.
2758 function calendar_add_subscription($sub) {
2759 global $DB, $USER, $SITE;
2761 // Undo the form definition work around to allow us to have two different
2762 // course selectors present depending on which event type the user selects.
2763 if (!empty($sub->groupcourseid)) {
2764 $sub->courseid = $sub->groupcourseid;
2765 unset($sub->groupcourseid);
2768 // Pull the group id back out of the value. The form saves the value
2769 // as "<courseid>-<groupid>" to allow the javascript to work correctly.
2770 if (!empty($sub->groupid)) {
2771 list($courseid, $groupid) = explode('-', $sub->groupid);
2772 $sub->courseid = $courseid;
2773 $sub->groupid = $groupid;
2776 // Default course id if none is set.
2777 if (empty($sub->courseid)) {
2778 if ($sub->eventtype === 'site') {
2779 $sub->courseid = SITEID;
2780 } else {
2781 $sub->courseid = 0;
2785 if ($sub->eventtype === 'site') {
2786 $sub->courseid = $SITE->id;
2787 } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
2788 $sub->courseid = $sub->courseid;
2789 } else if ($sub->eventtype === 'category') {
2790 $sub->categoryid = $sub->categoryid;
2791 } else {
2792 // User events.
2793 $sub->courseid = 0;
2795 $sub->userid = $USER->id;
2797 // File subscriptions never update.
2798 if (empty($sub->url)) {
2799 $sub->pollinterval = 0;
2802 if (!empty($sub->name)) {
2803 if (empty($sub->id)) {
2804 $id = $DB->insert_record('event_subscriptions', $sub);
2805 // We cannot cache the data here because $sub is not complete.
2806 $sub->id = $id;
2807 // Trigger event, calendar subscription added.
2808 $eventparams = array('objectid' => $sub->id,
2809 'context' => calendar_get_calendar_context($sub),
2810 'other' => array(
2811 'eventtype' => $sub->eventtype,
2814 switch ($sub->eventtype) {
2815 case 'category':
2816 $eventparams['other']['categoryid'] = $sub->categoryid;
2817 break;
2818 case 'course':
2819 $eventparams['other']['courseid'] = $sub->courseid;
2820 break;
2821 case 'group':
2822 $eventparams['other']['courseid'] = $sub->courseid;
2823 $eventparams['other']['groupid'] = $sub->groupid;
2824 break;
2825 default:
2826 $eventparams['other']['courseid'] = $sub->courseid;
2829 $event = \core\event\calendar_subscription_created::create($eventparams);
2830 $event->trigger();
2831 return $id;
2832 } else {
2833 // Why are we doing an update here?
2834 calendar_update_subscription($sub);
2835 return $sub->id;
2837 } else {
2838 print_error('errorbadsubscription', 'importcalendar');
2843 * Add an iCalendar event to the Moodle calendar.
2845 * @param stdClass $event The RFC-2445 iCalendar event
2846 * @param int $unused Deprecated
2847 * @param int $subscriptionid The iCalendar subscription ID
2848 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2849 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2850 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2852 function calendar_add_icalendar_event($event, $unused = null, $subscriptionid, $timezone='UTC') {
2853 global $DB;
2855 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2856 if (empty($event->properties['SUMMARY'])) {
2857 return 0;
2860 $name = $event->properties['SUMMARY'][0]->value;
2861 $name = str_replace('\n', '<br />', $name);
2862 $name = str_replace('\\', '', $name);
2863 $name = preg_replace('/\s+/u', ' ', $name);
2865 $eventrecord = new \stdClass;
2866 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
2868 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2869 $description = '';
2870 } else {
2871 $description = $event->properties['DESCRIPTION'][0]->value;
2872 $description = clean_param($description, PARAM_NOTAGS);
2873 $description = str_replace('\n', '<br />', $description);
2874 $description = str_replace('\\', '', $description);
2875 $description = preg_replace('/\s+/u', ' ', $description);
2877 $eventrecord->description = $description;
2879 // Probably a repeating event with RRULE etc. TODO: skip for now.
2880 if (empty($event->properties['DTSTART'][0]->value)) {
2881 return 0;
2884 if (isset($event->properties['DTSTART'][0]->parameters['TZID'])) {
2885 $tz = $event->properties['DTSTART'][0]->parameters['TZID'];
2886 } else {
2887 $tz = $timezone;
2889 $tz = \core_date::normalise_timezone($tz);
2890 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value . ' ' . $tz);
2891 if (empty($event->properties['DTEND'])) {
2892 $eventrecord->timeduration = 0; // No duration if no end time specified.
2893 } else {
2894 if (isset($event->properties['DTEND'][0]->parameters['TZID'])) {
2895 $endtz = $event->properties['DTEND'][0]->parameters['TZID'];
2896 } else {
2897 $endtz = $timezone;
2899 $endtz = \core_date::normalise_timezone($endtz);
2900 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value . ' ' . $endtz) - $eventrecord->timestart;
2903 // Check to see if it should be treated as an all day event.
2904 if ($eventrecord->timeduration == DAYSECS) {
2905 // Check to see if the event started at Midnight on the imported calendar.
2906 date_default_timezone_set($timezone);
2907 if (date('H:i:s', $eventrecord->timestart) === "00:00:00") {
2908 // This event should be an all day event. This is not correct, we don't do anything differently for all day events.
2909 // See MDL-56227.
2910 $eventrecord->timeduration = 0;
2912 \core_date::set_default_server_timezone();
2915 $eventrecord->uuid = $event->properties['UID'][0]->value;
2916 $eventrecord->timemodified = time();
2918 // Add the iCal subscription details if required.
2919 // We should never do anything with an event without a subscription reference.
2920 $sub = calendar_get_subscription($subscriptionid);
2921 $eventrecord->subscriptionid = $subscriptionid;
2922 $eventrecord->userid = $sub->userid;
2923 $eventrecord->groupid = $sub->groupid;
2924 $eventrecord->courseid = $sub->courseid;
2925 $eventrecord->categoryid = $sub->categoryid;
2926 $eventrecord->eventtype = $sub->eventtype;
2928 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid,
2929 'subscriptionid' => $eventrecord->subscriptionid))) {
2930 $eventrecord->id = $updaterecord->id;
2931 $return = CALENDAR_IMPORT_EVENT_UPDATED; // Update.
2932 } else {
2933 $return = CALENDAR_IMPORT_EVENT_INSERTED; // Insert.
2935 if ($createdevent = \calendar_event::create($eventrecord, false)) {
2936 if (!empty($event->properties['RRULE'])) {
2937 // Repeating events.
2938 date_default_timezone_set($tz); // Change time zone to parse all events.
2939 $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
2940 $rrule->parse_rrule();
2941 $rrule->create_events($createdevent);
2942 \core_date::set_default_server_timezone(); // Change time zone back to what it was.
2944 return $return;
2945 } else {
2946 return 0;
2951 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2953 * @param int $subscriptionid The ID of the subscription we are acting upon.
2954 * @param int $pollinterval The poll interval to use.
2955 * @param int $action The action to be performed. One of update or remove.
2956 * @throws dml_exception if invalid subscriptionid is provided
2957 * @return string A log of the import progress, including errors
2959 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2960 // Fetch the subscription from the database making sure it exists.
2961 $sub = calendar_get_subscription($subscriptionid);
2963 // Update or remove the subscription, based on action.
2964 switch ($action) {
2965 case CALENDAR_SUBSCRIPTION_UPDATE:
2966 // Skip updating file subscriptions.
2967 if (empty($sub->url)) {
2968 break;
2970 $sub->pollinterval = $pollinterval;
2971 calendar_update_subscription($sub);
2973 // Update the events.
2974 return "<p>" . get_string('subscriptionupdated', 'calendar', $sub->name) . "</p>" .
2975 calendar_update_subscription_events($subscriptionid);
2976 case CALENDAR_SUBSCRIPTION_REMOVE:
2977 calendar_delete_subscription($subscriptionid);
2978 return get_string('subscriptionremoved', 'calendar', $sub->name);
2979 break;
2980 default:
2981 break;
2983 return '';
2987 * Delete subscription and all related events.
2989 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
2991 function calendar_delete_subscription($subscription) {
2992 global $DB;
2994 if (!is_object($subscription)) {
2995 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST);
2998 // Delete subscription and related events.
2999 $DB->delete_records('event', array('subscriptionid' => $subscription->id));
3000 $DB->delete_records('event_subscriptions', array('id' => $subscription->id));
3001 \cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id));
3003 // Trigger event, calendar subscription deleted.
3004 $eventparams = array('objectid' => $subscription->id,
3005 'context' => calendar_get_calendar_context($subscription),
3006 'other' => array(
3007 'eventtype' => $subscription->eventtype,
3010 switch ($subscription->eventtype) {
3011 case 'category':
3012 $eventparams['other']['categoryid'] = $subscription->categoryid;
3013 break;
3014 case 'course':
3015 $eventparams['other']['courseid'] = $subscription->courseid;
3016 break;
3017 case 'group':
3018 $eventparams['other']['courseid'] = $subscription->courseid;
3019 $eventparams['other']['groupid'] = $subscription->groupid;
3020 break;
3021 default:
3022 $eventparams['other']['courseid'] = $subscription->courseid;
3024 $event = \core\event\calendar_subscription_deleted::create($eventparams);
3025 $event->trigger();
3029 * From a URL, fetch the calendar and return an iCalendar object.
3031 * @param string $url The iCalendar URL
3032 * @return iCalendar The iCalendar object
3034 function calendar_get_icalendar($url) {
3035 global $CFG;
3037 require_once($CFG->libdir . '/filelib.php');
3039 $curl = new \curl();
3040 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
3041 $calendar = $curl->get($url);
3043 // Http code validation should actually be the job of curl class.
3044 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
3045 throw new \moodle_exception('errorinvalidicalurl', 'calendar');
3048 $ical = new \iCalendar();
3049 $ical->unserialize($calendar);
3051 return $ical;
3055 * Import events from an iCalendar object into a course calendar.
3057 * @param iCalendar $ical The iCalendar object.
3058 * @param int $courseid The course ID for the calendar.
3059 * @param int $subscriptionid The subscription ID.
3060 * @return string A log of the import progress, including errors.
3062 function calendar_import_icalendar_events($ical, $unused = null, $subscriptionid = null) {
3063 global $DB;
3065 $return = '';
3066 $eventcount = 0;
3067 $updatecount = 0;
3069 // Large calendars take a while...
3070 if (!CLI_SCRIPT) {
3071 \core_php_time_limit::raise(300);
3074 // Mark all events in a subscription with a zero timestamp.
3075 if (!empty($subscriptionid)) {
3076 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
3077 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3080 // Grab the timezone from the iCalendar file to be used later.
3081 if (isset($ical->properties['X-WR-TIMEZONE'][0]->value)) {
3082 $timezone = $ical->properties['X-WR-TIMEZONE'][0]->value;
3083 } else {
3084 $timezone = 'UTC';
3087 $return = '';
3088 foreach ($ical->components['VEVENT'] as $event) {
3089 $res = calendar_add_icalendar_event($event, null, $subscriptionid, $timezone);
3090 switch ($res) {
3091 case CALENDAR_IMPORT_EVENT_UPDATED:
3092 $updatecount++;
3093 break;
3094 case CALENDAR_IMPORT_EVENT_INSERTED:
3095 $eventcount++;
3096 break;
3097 case 0:
3098 $return .= '<p>' . get_string('erroraddingevent', 'calendar') . ': ';
3099 if (empty($event->properties['SUMMARY'])) {
3100 $return .= '(' . get_string('notitle', 'calendar') . ')';
3101 } else {
3102 $return .= $event->properties['SUMMARY'][0]->value;
3104 $return .= "</p>\n";
3105 break;
3109 $return .= "<p>" . get_string('eventsimported', 'calendar', $eventcount) . "</p> ";
3110 $return .= "<p>" . get_string('eventsupdated', 'calendar', $updatecount) . "</p>";
3112 // Delete remaining zero-marked events since they're not in remote calendar.
3113 if (!empty($subscriptionid)) {
3114 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3115 if (!empty($deletecount)) {
3116 $DB->delete_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3117 $return .= "<p> " . get_string('eventsdeleted', 'calendar') . ": {$deletecount} </p>\n";
3121 return $return;
3125 * Fetch a calendar subscription and update the events in the calendar.
3127 * @param int $subscriptionid The course ID for the calendar.
3128 * @return string A log of the import progress, including errors.
3130 function calendar_update_subscription_events($subscriptionid) {
3131 $sub = calendar_get_subscription($subscriptionid);
3133 // Don't update a file subscription.
3134 if (empty($sub->url)) {
3135 return 'File subscription not updated.';
3138 $ical = calendar_get_icalendar($sub->url);
3139 $return = calendar_import_icalendar_events($ical, null, $subscriptionid);
3140 $sub->lastupdated = time();
3142 calendar_update_subscription($sub);
3144 return $return;
3148 * Update a calendar subscription. Also updates the associated cache.
3150 * @param stdClass|array $subscription Subscription record.
3151 * @throws coding_exception If something goes wrong
3152 * @since Moodle 2.5
3154 function calendar_update_subscription($subscription) {
3155 global $DB;
3157 if (is_array($subscription)) {
3158 $subscription = (object)$subscription;
3160 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
3161 throw new \coding_exception('Cannot update a subscription without a valid id');
3164 $DB->update_record('event_subscriptions', $subscription);
3166 // Update cache.
3167 $cache = \cache::make('core', 'calendar_subscriptions');
3168 $cache->set($subscription->id, $subscription);
3170 // Trigger event, calendar subscription updated.
3171 $eventparams = array('userid' => $subscription->userid,
3172 'objectid' => $subscription->id,
3173 'context' => calendar_get_calendar_context($subscription),
3174 'other' => array(
3175 'eventtype' => $subscription->eventtype,
3178 switch ($subscription->eventtype) {
3179 case 'category':
3180 $eventparams['other']['categoryid'] = $subscription->categoryid;
3181 break;
3182 case 'course':
3183 $eventparams['other']['courseid'] = $subscription->courseid;
3184 break;
3185 case 'group':
3186 $eventparams['other']['courseid'] = $subscription->courseid;
3187 $eventparams['other']['groupid'] = $subscription->groupid;
3188 break;
3189 default:
3190 $eventparams['other']['courseid'] = $subscription->courseid;
3192 $event = \core\event\calendar_subscription_updated::create($eventparams);
3193 $event->trigger();
3197 * Checks to see if the user can edit a given subscription feed.
3199 * @param mixed $subscriptionorid Subscription object or id
3200 * @return bool true if current user can edit the subscription else false
3202 function calendar_can_edit_subscription($subscriptionorid) {
3203 if (is_array($subscriptionorid)) {
3204 $subscription = (object)$subscriptionorid;
3205 } else if (is_object($subscriptionorid)) {
3206 $subscription = $subscriptionorid;
3207 } else {
3208 $subscription = calendar_get_subscription($subscriptionorid);
3211 $allowed = new \stdClass;
3212 $courseid = $subscription->courseid;
3213 $categoryid = $subscription->categoryid;
3214 $groupid = $subscription->groupid;
3215 $category = null;
3217 if (!empty($categoryid)) {
3218 $category = \coursecat::get($categoryid);
3220 calendar_get_allowed_types($allowed, $courseid, null, $category);
3221 switch ($subscription->eventtype) {
3222 case 'user':
3223 return $allowed->user;
3224 case 'course':
3225 if (isset($allowed->courses[$courseid])) {
3226 return $allowed->courses[$courseid];
3227 } else {
3228 return false;
3230 case 'category':
3231 if (isset($allowed->categories[$categoryid])) {
3232 return $allowed->categories[$categoryid];
3233 } else {
3234 return false;
3236 case 'site':
3237 return $allowed->site;
3238 case 'group':
3239 if (isset($allowed->groups[$groupid])) {
3240 return $allowed->groups[$groupid];
3241 } else {
3242 return false;
3244 default:
3245 return false;
3250 * Helper function to determine the context of a calendar subscription.
3251 * Subscriptions can be created in two contexts COURSE, or USER.
3253 * @param stdClass $subscription
3254 * @return context instance
3256 function calendar_get_calendar_context($subscription) {
3257 // Determine context based on calendar type.
3258 if ($subscription->eventtype === 'site') {
3259 $context = \context_course::instance(SITEID);
3260 } else if ($subscription->eventtype === 'group' || $subscription->eventtype === 'course') {
3261 $context = \context_course::instance($subscription->courseid);
3262 } else {
3263 $context = \context_user::instance($subscription->userid);
3265 return $context;
3269 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
3271 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3273 * @return array
3275 function core_calendar_user_preferences() {
3276 $preferences = [];
3277 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED, 'default' => '0',
3278 'choices' => array('0', CALENDAR_TF_12, CALENDAR_TF_24)
3280 $preferences['calendar_startwday'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3281 'choices' => array(0, 1, 2, 3, 4, 5, 6));
3282 $preferences['calendar_maxevents'] = array('type' => PARAM_INT, 'choices' => range(1, 20));
3283 $preferences['calendar_lookahead'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 365,
3284 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3285 $preferences['calendar_persistflt'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3286 'choices' => array(0, 1));
3287 return $preferences;
3291 * Get legacy calendar events
3293 * @param int $tstart Start time of time range for events
3294 * @param int $tend End time of time range for events
3295 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3296 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3297 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3298 * @param boolean $withduration whether only events starting within time range selected
3299 * or events in progress/already started selected as well
3300 * @param boolean $ignorehidden whether to select only visible events or all events
3301 * @param array $categories array of category ids and/or objects.
3302 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3304 function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses,
3305 $withduration = true, $ignorehidden = true, $categories = []) {
3306 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3307 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3308 // parameters, but with the new API method, only null and arrays are accepted.
3309 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3310 // If parameter is true, return null.
3311 if ($param === true) {
3312 return null;
3315 // If parameter is false, return an empty array.
3316 if ($param === false) {
3317 return [];
3320 // If the parameter is a scalar value, enclose it in an array.
3321 if (!is_array($param)) {
3322 return [$param];
3325 // No normalisation required.
3326 return $param;
3327 }, [$users, $groups, $courses, $categories]);
3329 $mapper = \core_calendar\local\event\container::get_event_mapper();
3330 $events = \core_calendar\local\api::get_events(
3331 $tstart,
3332 $tend,
3333 null,
3334 null,
3335 null,
3336 null,
3338 null,
3339 $userparam,
3340 $groupparam,
3341 $courseparam,
3342 $categoryparam,
3343 $withduration,
3344 $ignorehidden
3347 return array_reduce($events, function($carry, $event) use ($mapper) {
3348 return $carry + [$event->get_id() => $mapper->from_event_to_stdclass($event)];
3349 }, []);
3354 * Get the calendar view output.
3356 * @param \calendar_information $calendar The calendar being represented
3357 * @param string $view The type of calendar to have displayed
3358 * @param bool $includenavigation Whether to include navigation
3359 * @param bool $skipevents Whether to load the events or not
3360 * @return array[array, string]
3362 function calendar_get_view(\calendar_information $calendar, $view, $includenavigation = true, bool $skipevents = false) {
3363 global $PAGE, $CFG;
3365 $renderer = $PAGE->get_renderer('core_calendar');
3366 $type = \core_calendar\type_factory::get_calendar_instance();
3368 // Calculate the bounds of the month.
3369 $calendardate = $type->timestamp_to_date_array($calendar->time);
3371 $date = new \DateTime('now', core_date::get_user_timezone_object(99));
3372 $eventlimit = 200;
3374 if ($view === 'day') {
3375 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday']);
3376 $date->setTimestamp($tstart);
3377 $date->modify('+1 day');
3378 } else if ($view === 'upcoming' || $view === 'upcoming_mini') {
3379 // Number of days in the future that will be used to fetch events.
3380 if (isset($CFG->calendar_lookahead)) {
3381 $defaultlookahead = intval($CFG->calendar_lookahead);
3382 } else {
3383 $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD;
3385 $lookahead = get_user_preferences('calendar_lookahead', $defaultlookahead);
3387 // Maximum number of events to be displayed on upcoming view.
3388 $defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS;
3389 if (isset($CFG->calendar_maxevents)) {
3390 $defaultmaxevents = intval($CFG->calendar_maxevents);
3392 $eventlimit = get_user_preferences('calendar_maxevents', $defaultmaxevents);
3394 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday'],
3395 $calendardate['hours']);
3396 $date->setTimestamp($tstart);
3397 $date->modify('+' . $lookahead . ' days');
3398 } else {
3399 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], 1);
3400 $monthdays = $type->get_num_days_in_month($calendardate['year'], $calendardate['mon']);
3401 $date->setTimestamp($tstart);
3402 $date->modify('+' . $monthdays . ' days');
3404 if ($view === 'mini' || $view === 'minithree') {
3405 $template = 'core_calendar/calendar_mini';
3406 } else {
3407 $template = 'core_calendar/calendar_month';
3411 // We need to extract 1 second to ensure that we don't get into the next day.
3412 $date->modify('-1 second');
3413 $tend = $date->getTimestamp();
3415 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3416 // If parameter is true, return null.
3417 if ($param === true) {
3418 return null;
3421 // If parameter is false, return an empty array.
3422 if ($param === false) {
3423 return [];
3426 // If the parameter is a scalar value, enclose it in an array.
3427 if (!is_array($param)) {
3428 return [$param];
3431 // No normalisation required.
3432 return $param;
3433 }, [$calendar->users, $calendar->groups, $calendar->courses, $calendar->categories]);
3435 if ($skipevents) {
3436 $events = [];
3437 } else {
3438 $events = \core_calendar\local\api::get_events(
3439 $tstart,
3440 $tend,
3441 null,
3442 null,
3443 null,
3444 null,
3445 $eventlimit,
3446 null,
3447 $userparam,
3448 $groupparam,
3449 $courseparam,
3450 $categoryparam,
3451 true,
3452 true,
3453 function ($event) {
3454 if ($proxy = $event->get_course_module()) {
3455 $cminfo = $proxy->get_proxied_instance();
3456 return $cminfo->uservisible;
3459 if ($proxy = $event->get_category()) {
3460 $category = $proxy->get_proxied_instance();
3462 return $category->is_uservisible();
3465 return true;
3470 $related = [
3471 'events' => $events,
3472 'cache' => new \core_calendar\external\events_related_objects_cache($events),
3473 'type' => $type,
3476 $data = [];
3477 if ($view == "month" || $view == "mini" || $view == "minithree") {
3478 $month = new \core_calendar\external\month_exporter($calendar, $type, $related);
3479 $month->set_includenavigation($includenavigation);
3480 $month->set_initialeventsloaded(!$skipevents);
3481 $month->set_showcoursefilter($view == "month");
3482 $data = $month->export($renderer);
3483 } else if ($view == "day") {
3484 $day = new \core_calendar\external\calendar_day_exporter($calendar, $related);
3485 $data = $day->export($renderer);
3486 $template = 'core_calendar/calendar_day';
3487 } else if ($view == "upcoming" || $view == "upcoming_mini") {
3488 $upcoming = new \core_calendar\external\calendar_upcoming_exporter($calendar, $related);
3489 $data = $upcoming->export($renderer);
3491 if ($view == "upcoming") {
3492 $template = 'core_calendar/calendar_upcoming';
3493 } else if ($view == "upcoming_mini") {
3494 $template = 'core_calendar/calendar_upcoming_mini';
3498 return [$data, $template];
3502 * Request and render event form fragment.
3504 * @param array $args The fragment arguments.
3505 * @return string The rendered mform fragment.
3507 function calendar_output_fragment_event_form($args) {
3508 global $CFG, $OUTPUT, $USER;
3510 $html = '';
3511 $data = [];
3512 $eventid = isset($args['eventid']) ? clean_param($args['eventid'], PARAM_INT) : null;
3513 $starttime = isset($args['starttime']) ? clean_param($args['starttime'], PARAM_INT) : null;
3514 $courseid = isset($args['courseid']) ? clean_param($args['courseid'], PARAM_INT) : null;
3515 $categoryid = isset($args['categoryid']) ? clean_param($args['categoryid'], PARAM_INT) : null;
3516 $event = null;
3517 $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
3518 $context = \context_user::instance($USER->id);
3519 $editoroptions = \core_calendar\local\event\forms\create::build_editor_options($context);
3520 $formoptions = ['editoroptions' => $editoroptions];
3521 $draftitemid = 0;
3523 if ($hasformdata) {
3524 parse_str(clean_param($args['formdata'], PARAM_TEXT), $data);
3525 if (isset($data['description']['itemid'])) {
3526 $draftitemid = $data['description']['itemid'];
3530 if ($starttime) {
3531 $formoptions['starttime'] = $starttime;
3534 if (is_null($eventid)) {
3535 $mform = new \core_calendar\local\event\forms\create(
3536 null,
3537 $formoptions,
3538 'post',
3540 null,
3541 true,
3542 $data
3545 // Let's check first which event types user can add.
3546 calendar_get_allowed_types($allowed, $courseid);
3548 // If the user is on course context and is allowed to add course events set the event type default to course.
3549 if ($courseid != SITEID && !empty($allowed->courses)) {
3550 $data['eventtype'] = 'course';
3551 $data['courseid'] = $courseid;
3552 $data['groupcourseid'] = $courseid;
3553 } else if (!empty($categoryid) && !empty($allowed->category)) {
3554 $data['eventtype'] = 'category';
3555 $data['categoryid'] = $categoryid;
3557 $mform->set_data($data);
3558 } else {
3559 $event = calendar_event::load($eventid);
3560 $mapper = new \core_calendar\local\event\mappers\create_update_form_mapper();
3561 $eventdata = $mapper->from_legacy_event_to_data($event);
3562 $data = array_merge((array) $eventdata, $data);
3563 $event->count_repeats();
3564 $formoptions['event'] = $event;
3565 $data['description']['text'] = file_prepare_draft_area(
3566 $draftitemid,
3567 $event->context->id,
3568 'calendar',
3569 'event_description',
3570 $event->id,
3571 null,
3572 $data['description']['text']
3574 $data['description']['itemid'] = $draftitemid;
3576 $mform = new \core_calendar\local\event\forms\update(
3577 null,
3578 $formoptions,
3579 'post',
3581 null,
3582 true,
3583 $data
3585 $mform->set_data($data);
3587 // Check to see if this event is part of a subscription or import.
3588 // If so display a warning on edit.
3589 if (isset($event->subscriptionid) && ($event->subscriptionid != null)) {
3590 $renderable = new \core\output\notification(
3591 get_string('eventsubscriptioneditwarning', 'calendar'),
3592 \core\output\notification::NOTIFY_INFO
3595 $html .= $OUTPUT->render($renderable);
3599 if ($hasformdata) {
3600 $mform->is_validated();
3603 $html .= $mform->render();
3604 return $html;
3608 * Calculate the timestamp from the supplied Gregorian Year, Month, and Day.
3610 * @param int $d The day
3611 * @param int $m The month
3612 * @param int $y The year
3613 * @param int $time The timestamp to use instead of a separate y/m/d.
3614 * @return int The timestamp
3616 function calendar_get_timestamp($d, $m, $y, $time = 0) {
3617 // If a day, month and year were passed then convert it to a timestamp. If these were passed
3618 // then we can assume the day, month and year are passed as Gregorian, as no where in core
3619 // should we be passing these values rather than the time.
3620 if (!empty($d) && !empty($m) && !empty($y)) {
3621 if (checkdate($m, $d, $y)) {
3622 $time = make_timestamp($y, $m, $d);
3623 } else {
3624 $time = time();
3626 } else if (empty($time)) {
3627 $time = time();
3630 return $time;
3634 * Get the calendar footer options.
3636 * @param calendar_information $calendar The calendar information object.
3637 * @return array The data for template and template name.
3639 function calendar_get_footer_options($calendar) {
3640 global $CFG, $USER, $DB, $PAGE;
3642 // Generate hash for iCal link.
3643 $rawhash = $USER->id . $DB->get_field('user', 'password', ['id' => $USER->id]) . $CFG->calendar_exportsalt;
3644 $authtoken = sha1($rawhash);
3646 $renderer = $PAGE->get_renderer('core_calendar');
3647 $footer = new \core_calendar\external\footer_options_exporter($calendar, $USER->id, $authtoken);
3648 $data = $footer->export($renderer);
3649 $template = 'core_calendar/footer_options';
3651 return [$data, $template];
3655 * Get the list of potential calendar filter types as a type => name
3656 * combination.
3658 * @return array
3660 function calendar_get_filter_types() {
3661 $types = [
3662 'site',
3663 'category',
3664 'course',
3665 'group',
3666 'user',
3669 return array_map(function($type) {
3670 return [
3671 'eventtype' => $type,
3672 'name' => get_string("eventtype{$type}", "calendar"),
3674 }, $types);
3678 * Check whether the specified event type is valid.
3680 * @param string $type
3681 * @return bool
3683 function calendar_is_valid_eventtype($type) {
3684 $validtypes = [
3685 'user',
3686 'group',
3687 'course',
3688 'category',
3689 'site',
3691 return in_array($type, $validtypes);