MDL-43648 form: fix hours and minutes in date_time_selector
[moodle.git] / calendar / lib.php
blob423f6059eac7be77fe17f4e3af27ea6d49709038
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 // We have a course and are within the course context so we had
812 // better use the courses max bytes value.
813 $this->editoroptions['maxbytes'] = $course->maxbytes;
814 } else {
815 // If we get here we have a custom event type as used by some
816 // modules. In this case the event will have been added by
817 // code and we won't need the editor.
818 $this->editoroptions['maxbytes'] = 0;
819 $this->editoroptions['maxfiles'] = 0;
822 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
823 $contextid = false;
824 } else {
825 // Get the context id that is what we really want.
826 $contextid = $this->editorcontext->id;
828 } else {
830 // If we get here then this is a new event in which case we don't need a
831 // context as there is no existing files to copy to the draft area.
832 $contextid = null;
835 // If the contextid === false we don't support files so no preparing
836 // a draft area.
837 if ($contextid !== false) {
838 // Just encase it has already been submitted.
839 $draftiddescription = file_get_submitted_draft_itemid('description');
840 // Prepare the draft area, this copies existing files to the draft area as well.
841 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar',
842 'event_description', $properties->id, $this->editoroptions, $properties->description);
843 } else {
844 $draftiddescription = 0;
847 // Structure the description field as the editor requires.
848 $properties->description = array('text' => $properties->description, 'format' => $properties->format,
849 'itemid' => $draftiddescription);
852 // Finally return the properties.
853 return $properties;
857 * Toggles the visibility of an event
859 * @param null|bool $force If it is left null the events visibility is flipped,
860 * If it is false the event is made hidden, if it is true it
861 * is made visible.
862 * @return bool if event is successfully updated, toggle will be visible
864 public function toggle_visibility($force = null) {
865 global $DB;
867 // Set visible to the default if it is not already set.
868 if (empty($this->properties->visible)) {
869 $this->properties->visible = 1;
872 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
873 // Make this event visible.
874 $this->properties->visible = 1;
875 } else {
876 // Make this event hidden.
877 $this->properties->visible = 0;
880 // Update the database to reflect this change.
881 $success = $DB->set_field('event', 'visible', $this->properties->visible, array('id' => $this->properties->id));
882 $calendarevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
884 // Prepare event data.
885 $eventargs = array(
886 'context' => $this->get_context(),
887 'objectid' => $this->properties->id,
888 'other' => array(
889 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
890 'timestart' => $this->properties->timestart,
891 'name' => $this->properties->name
894 $event = \core\event\calendar_event_updated::create($eventargs);
895 $event->add_record_snapshot('event', $calendarevent);
896 $event->trigger();
898 return $success;
902 * Returns an event object when provided with an event id.
904 * This function makes use of MUST_EXIST, if the event id passed in is invalid
905 * it will result in an exception being thrown.
907 * @param int|object $param event object or event id
908 * @return calendar_event
910 public static function load($param) {
911 global $DB;
912 if (is_object($param)) {
913 $event = new calendar_event($param);
914 } else {
915 $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST);
916 $event = new calendar_event($event);
918 return $event;
922 * Creates a new event and returns an event object
924 * @param \stdClass|array $properties An object containing event properties
925 * @param bool $checkcapability Check caps or not
926 * @throws \coding_exception
928 * @return calendar_event|bool The event object or false if it failed
930 public static function create($properties, $checkcapability = true) {
931 if (is_array($properties)) {
932 $properties = (object)$properties;
934 if (!is_object($properties)) {
935 throw new \coding_exception('When creating an event properties should be either an object or an assoc array');
937 $event = new calendar_event($properties);
938 if ($event->update($properties, $checkcapability)) {
939 return $event;
940 } else {
941 return false;
946 * Format the text using the external API.
948 * This function should we used when text formatting is required in external functions.
950 * @return array an array containing the text formatted and the text format
952 public function format_external_text() {
954 if ($this->editorcontext === null) {
955 // Switch on the event type to decide upon the appropriate context to use for this event.
956 $this->editorcontext = $this->get_context();
958 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
959 // We don't have a context here, do a normal format_text.
960 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id);
964 // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
965 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
966 $itemid = $this->properties->repeatid;
967 } else {
968 $itemid = $this->properties->id;
971 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id,
972 'calendar', 'event_description', $itemid);
977 * Calendar information class
979 * This class is used simply to organise the information pertaining to a calendar
980 * and is used primarily to make information easily available.
982 * @package core_calendar
983 * @category calendar
984 * @copyright 2010 Sam Hemelryk
985 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
987 class calendar_information {
990 * @var int The timestamp
992 * Rather than setting the day, month and year we will set a timestamp which will be able
993 * to be used by multiple calendars.
995 public $time;
997 /** @var int A course id */
998 public $courseid = null;
1000 /** @var array An array of categories */
1001 public $categories = array();
1003 /** @var int The current category */
1004 public $categoryid = null;
1006 /** @var array An array of courses */
1007 public $courses = array();
1009 /** @var array An array of groups */
1010 public $groups = array();
1012 /** @var array An array of users */
1013 public $users = array();
1015 /** @var context The anticipated context that the calendar is viewed in */
1016 public $context = null;
1019 * Creates a new instance
1021 * @param int $day the number of the day
1022 * @param int $month the number of the month
1023 * @param int $year the number of the year
1024 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
1025 * and $calyear to support multiple calendars
1027 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
1028 // If a day, month and year were passed then convert it to a timestamp. If these were passed
1029 // then we can assume the day, month and year are passed as Gregorian, as no where in core
1030 // should we be passing these values rather than the time. This is done for BC.
1031 if (!empty($day) || !empty($month) || !empty($year)) {
1032 $date = usergetdate(time());
1033 if (empty($day)) {
1034 $day = $date['mday'];
1036 if (empty($month)) {
1037 $month = $date['mon'];
1039 if (empty($year)) {
1040 $year = $date['year'];
1042 if (checkdate($month, $day, $year)) {
1043 $time = make_timestamp($year, $month, $day);
1044 } else {
1045 $time = time();
1049 $this->set_time($time);
1053 * Creates and set up a instance.
1055 * @param int $time the unixtimestamp representing the date we want to view.
1056 * @param int $courseid The ID of the course the user wishes to view.
1057 * @param int $categoryid The ID of the category the user wishes to view
1058 * If a courseid is specified, this value is ignored.
1059 * @return calendar_information
1061 public static function create($time, int $courseid, int $categoryid = null) : calendar_information {
1062 $calendar = new static(0, 0, 0, $time);
1063 if ($courseid != SITEID && !empty($courseid)) {
1064 // Course ID must be valid and existing.
1065 $course = get_course($courseid);
1066 $calendar->context = context_course::instance($course->id);
1068 if (!$course->visible) {
1069 require_capability('moodle/course:viewhiddencourses', $calendar->context);
1072 $courses = [$course->id => $course];
1073 $category = (\coursecat::get($course->category, MUST_EXIST, true))->get_db_record();
1074 } else if (!empty($categoryid)) {
1075 $course = get_site();
1076 $courses = calendar_get_default_courses();
1078 // Filter available courses to those within this category or it's children.
1079 $ids = [$categoryid];
1080 $category = \coursecat::get($categoryid);
1081 $ids = array_merge($ids, array_keys($category->get_children()));
1082 $courses = array_filter($courses, function($course) use ($ids) {
1083 return array_search($course->category, $ids) !== false;
1085 $category = $category->get_db_record();
1087 $calendar->context = context_coursecat::instance($categoryid);
1088 } else {
1089 $course = get_site();
1090 $courses = calendar_get_default_courses();
1091 $category = null;
1093 $calendar->context = context_system::instance();
1096 $calendar->set_sources($course, $courses, $category);
1098 return $calendar;
1102 * Set the time period of this instance.
1104 * @param int $time the unixtimestamp representing the date we want to view.
1105 * @return $this
1107 public function set_time($time = null) {
1108 if (empty($time)) {
1109 $this->time = time();
1110 } else {
1111 $this->time = $time;
1114 return $this;
1118 * Initialize calendar information
1120 * @deprecated 3.4
1121 * @param stdClass $course object
1122 * @param array $coursestoload An array of courses [$course->id => $course]
1123 * @param bool $ignorefilters options to use filter
1125 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
1126 debugging('The prepare_for_view() function has been deprecated. Please update your code to use set_sources()',
1127 DEBUG_DEVELOPER);
1128 $this->set_sources($course, $coursestoload);
1132 * Set the sources for events within the calendar.
1134 * If no category is provided, then the category path for the current
1135 * course will be used.
1137 * @param stdClass $course The current course being viewed.
1138 * @param int[] $courses The list of all courses currently accessible.
1139 * @param stdClass $category The current category to show.
1141 public function set_sources(stdClass $course, array $courses, stdClass $category = null) {
1142 global $USER;
1144 // A cousre must always be specified.
1145 $this->course = $course;
1146 $this->courseid = $course->id;
1148 list($courseids, $group, $user) = calendar_set_filters($courses);
1149 $this->courses = $courseids;
1150 $this->groups = $group;
1151 $this->users = $user;
1153 // Do not show category events by default.
1154 $this->categoryid = null;
1155 $this->categories = null;
1157 // Determine the correct category information to show.
1158 // When called with a course, the category of that course is usually included too.
1159 // When a category was specifically requested, it should be requested with the site id.
1160 if (SITEID !== $this->courseid) {
1161 // A specific course was requested.
1162 // Fetch the category that this course is in, along with all parents.
1163 // Do not include child categories of this category, as the user many not have enrolments in those siblings or children.
1164 $category = \coursecat::get($course->category, MUST_EXIST, true);
1165 $this->categoryid = $category->id;
1167 $this->categories = $category->get_parents();
1168 $this->categories[] = $category->id;
1169 } else if (null !== $category && $category->id > 0) {
1170 // A specific category was requested.
1171 // Fetch all parents of this category, along with all children too.
1172 $category = \coursecat::get($category->id);
1173 $this->categoryid = $category->id;
1175 // Build the category list.
1176 // This includes the current category.
1177 $this->categories = [$category->id];
1179 // All of its descendants.
1180 foreach (\coursecat::get_all() as $cat) {
1181 if (array_search($category->id, $cat->get_parents()) !== false) {
1182 $this->categories[] = $cat->id;
1186 // And all of its parents.
1187 $this->categories = array_merge($this->categories, $category->get_parents());
1188 } else if (SITEID === $this->courseid) {
1189 // The site was requested.
1190 // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
1192 // Grab the list of categories that this user has courses in.
1193 $coursecategories = array_flip(array_map(function($course) {
1194 return $course->category;
1195 }, $courses));
1197 $categories = [];
1198 foreach (\coursecat::get_all() as $category) {
1199 if (has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
1200 // If a user can manage a category, then they can see all child categories. as well as all parent categories.
1201 $categories[] = $category->id;
1202 foreach (\coursecat::get_all() as $cat) {
1203 if (array_search($category->id, $cat->get_parents()) !== false) {
1204 $categories[] = $cat->id;
1207 $categories = array_merge($categories, $category->get_parents());
1208 } else if (isset($coursecategories[$category->id])) {
1209 // The user has access to a course in this category.
1210 // Fetch all of the parents too.
1211 $categories = array_merge($categories, [$category->id], $category->get_parents());
1212 $categories[] = $category->id;
1216 $this->categories = array_unique($categories);
1221 * Ensures the date for the calendar is correct and either sets it to now
1222 * or throws a moodle_exception if not
1224 * @param bool $defaultonow use current time
1225 * @throws moodle_exception
1226 * @return bool validation of checkdate
1228 public function checkdate($defaultonow = true) {
1229 if (!checkdate($this->month, $this->day, $this->year)) {
1230 if ($defaultonow) {
1231 $now = usergetdate(time());
1232 $this->day = intval($now['mday']);
1233 $this->month = intval($now['mon']);
1234 $this->year = intval($now['year']);
1235 return true;
1236 } else {
1237 throw new moodle_exception('invaliddate');
1240 return true;
1244 * Gets todays timestamp for the calendar
1246 * @return int today timestamp
1248 public function timestamp_today() {
1249 return $this->time;
1252 * Gets tomorrows timestamp for the calendar
1254 * @return int tomorrow timestamp
1256 public function timestamp_tomorrow() {
1257 return strtotime('+1 day', $this->time);
1260 * Adds the pretend blocks for the calendar
1262 * @param core_calendar_renderer $renderer
1263 * @param bool $showfilters display filters, false is set as default
1264 * @param string|null $view preference view options (eg: day, month, upcoming)
1266 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
1267 if ($showfilters) {
1268 $filters = new block_contents();
1269 $filters->content = $renderer->event_filter();
1270 $filters->footer = '';
1271 $filters->title = get_string('eventskey', 'calendar');
1272 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
1274 $block = new block_contents;
1275 $block->content = $renderer->fake_block_threemonths($this);
1276 $block->footer = '';
1277 $block->title = get_string('monthlyview', 'calendar');
1278 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
1283 * Get calendar events.
1285 * @param int $tstart Start time of time range for events
1286 * @param int $tend End time of time range for events
1287 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
1288 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
1289 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
1290 * @param boolean $withduration whether only events starting within time range selected
1291 * or events in progress/already started selected as well
1292 * @param boolean $ignorehidden whether to select only visible events or all events
1293 * @param array|int|boolean $categories array of categories, category id or boolean for all/no course events
1294 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
1296 function calendar_get_events($tstart, $tend, $users, $groups, $courses,
1297 $withduration = true, $ignorehidden = true, $categories = []) {
1298 global $DB;
1300 $whereclause = '';
1301 $params = array();
1302 // Quick test.
1303 if (empty($users) && empty($groups) && empty($courses) && empty($categories)) {
1304 return array();
1307 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
1308 // Events from a number of users
1309 if(!empty($whereclause)) $whereclause .= ' OR';
1310 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED);
1311 $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)";
1312 $params = array_merge($params, $inparamsusers);
1313 } else if($users === true) {
1314 // Events from ALL users
1315 if(!empty($whereclause)) $whereclause .= ' OR';
1316 $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)';
1317 } else if($users === false) {
1318 // No user at all, do nothing
1321 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
1322 // Events from a number of groups
1323 if(!empty($whereclause)) $whereclause .= ' OR';
1324 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED);
1325 $whereclause .= " e.groupid $insqlgroups ";
1326 $params = array_merge($params, $inparamsgroups);
1327 } else if($groups === true) {
1328 // Events from ALL groups
1329 if(!empty($whereclause)) $whereclause .= ' OR ';
1330 $whereclause .= ' e.groupid != 0';
1332 // boolean false (no groups at all): we don't need to do anything
1334 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
1335 if(!empty($whereclause)) $whereclause .= ' OR';
1336 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED);
1337 $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
1338 $params = array_merge($params, $inparamscourses);
1339 } else if ($courses === true) {
1340 // Events from ALL courses
1341 if(!empty($whereclause)) $whereclause .= ' OR';
1342 $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
1345 if ((is_array($categories) && !empty($categories)) || is_numeric($categories)) {
1346 if (!empty($whereclause)) {
1347 $whereclause .= ' OR';
1349 list($insqlcategories, $inparamscategories) = $DB->get_in_or_equal($categories, SQL_PARAMS_NAMED);
1350 $whereclause .= " (e.groupid = 0 AND e.courseid = 0 AND e.categoryid $insqlcategories)";
1351 $params = array_merge($params, $inparamscategories);
1352 } else if ($categories === true) {
1353 // Events from ALL categories.
1354 if (!empty($whereclause)) {
1355 $whereclause .= ' OR';
1357 $whereclause .= ' (e.groupid = 0 AND e.courseid = 0 AND e.categoryid != 0)';
1360 // Security check: if, by now, we have NOTHING in $whereclause, then it means
1361 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
1362 // events no matter what. Allowing the code to proceed might return a completely
1363 // valid query with only time constraints, thus selecting ALL events in that time frame!
1364 if(empty($whereclause)) {
1365 return array();
1368 if($withduration) {
1369 $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1371 else {
1372 $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1374 if(!empty($whereclause)) {
1375 // We have additional constraints
1376 $whereclause = $timeclause.' AND ('.$whereclause.')';
1378 else {
1379 // Just basic time filtering
1380 $whereclause = $timeclause;
1383 if ($ignorehidden) {
1384 $whereclause .= ' AND e.visible = 1';
1387 $sql = "SELECT e.*
1388 FROM {event} e
1389 LEFT JOIN {modules} m ON e.modulename = m.name
1390 -- Non visible modules will have a value of 0.
1391 WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
1392 ORDER BY e.timestart";
1393 $events = $DB->get_records_sql($sql, $params);
1395 if ($events === false) {
1396 $events = array();
1398 return $events;
1402 * Return the days of the week.
1404 * @return array array of days
1406 function calendar_get_days() {
1407 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1408 return $calendartype->get_weekdays();
1412 * Get the subscription from a given id.
1414 * @since Moodle 2.5
1415 * @param int $id id of the subscription
1416 * @return stdClass Subscription record from DB
1417 * @throws moodle_exception for an invalid id
1419 function calendar_get_subscription($id) {
1420 global $DB;
1422 $cache = \cache::make('core', 'calendar_subscriptions');
1423 $subscription = $cache->get($id);
1424 if (empty($subscription)) {
1425 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
1426 $cache->set($id, $subscription);
1429 return $subscription;
1433 * Gets the first day of the week.
1435 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
1437 * @return int
1439 function calendar_get_starting_weekday() {
1440 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1441 return $calendartype->get_starting_weekday();
1445 * Get a HTML link to a course.
1447 * @param int|stdClass $course the course id or course object
1448 * @return string a link to the course (as HTML); empty if the course id is invalid
1450 function calendar_get_courselink($course) {
1451 if (!$course) {
1452 return '';
1455 if (!is_object($course)) {
1456 $course = calendar_get_course_cached($coursecache, $course);
1458 $context = \context_course::instance($course->id);
1459 $fullname = format_string($course->fullname, true, array('context' => $context));
1460 $url = new \moodle_url('/course/view.php', array('id' => $course->id));
1461 $link = \html_writer::link($url, $fullname);
1463 return $link;
1467 * Get current module cache.
1469 * Only use this method if you do not know courseid. Otherwise use:
1470 * get_fast_modinfo($courseid)->instances[$modulename][$instance]
1472 * @param array $modulecache in memory module cache
1473 * @param string $modulename name of the module
1474 * @param int $instance module instance number
1475 * @return stdClass|bool $module information
1477 function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
1478 if (!isset($modulecache[$modulename . '_' . $instance])) {
1479 $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
1482 return $modulecache[$modulename . '_' . $instance];
1486 * Get current course cache.
1488 * @param array $coursecache list of course cache
1489 * @param int $courseid id of the course
1490 * @return stdClass $coursecache[$courseid] return the specific course cache
1492 function calendar_get_course_cached(&$coursecache, $courseid) {
1493 if (!isset($coursecache[$courseid])) {
1494 $coursecache[$courseid] = get_course($courseid);
1496 return $coursecache[$courseid];
1500 * Get group from groupid for calendar display
1502 * @param int $groupid
1503 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1505 function calendar_get_group_cached($groupid) {
1506 static $groupscache = array();
1507 if (!isset($groupscache[$groupid])) {
1508 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1510 return $groupscache[$groupid];
1514 * Add calendar event metadata
1516 * @param stdClass $event event info
1517 * @return stdClass $event metadata
1519 function calendar_add_event_metadata($event) {
1520 global $CFG, $OUTPUT;
1522 // Support multilang in event->name.
1523 $event->name = format_string($event->name, true);
1525 if (!empty($event->modulename)) { // Activity event.
1526 // The module name is set. I will assume that it has to be displayed, and
1527 // also that it is an automatically-generated event. And of course that the
1528 // instace id and modulename are set correctly.
1529 $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
1530 if (!array_key_exists($event->instance, $instances)) {
1531 return;
1533 $module = $instances[$event->instance];
1535 $modulename = $module->get_module_type_name(false);
1536 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
1537 // Will be used as alt text if the event icon.
1538 $eventtype = get_string($event->eventtype, $event->modulename);
1539 } else {
1540 $eventtype = '';
1543 $event->icon = '<img src="' . s($module->get_icon_url()) . '" alt="' . s($eventtype) .
1544 '" title="' . s($modulename) . '" class="icon" />';
1545 $event->referer = html_writer::link($module->url, $event->name);
1546 $event->courselink = calendar_get_courselink($module->get_course());
1547 $event->cmid = $module->id;
1548 } else if ($event->courseid == SITEID) { // Site event.
1549 $event->icon = '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
1550 get_string('globalevent', 'calendar') . '" class="icon" />';
1551 $event->cssclass = 'calendar_event_global';
1552 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event.
1553 $event->icon = '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
1554 get_string('courseevent', 'calendar') . '" class="icon" />';
1555 $event->courselink = calendar_get_courselink($event->courseid);
1556 $event->cssclass = 'calendar_event_course';
1557 } else if ($event->groupid) { // Group event.
1558 if ($group = calendar_get_group_cached($event->groupid)) {
1559 $groupname = format_string($group->name, true, \context_course::instance($group->courseid));
1560 } else {
1561 $groupname = '';
1563 $event->icon = \html_writer::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
1564 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
1565 $event->courselink = calendar_get_courselink($event->courseid) . ', ' . $groupname;
1566 $event->cssclass = 'calendar_event_group';
1567 } else if ($event->userid) { // User event.
1568 $event->icon = '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
1569 get_string('userevent', 'calendar') . '" class="icon" />';
1570 $event->cssclass = 'calendar_event_user';
1573 return $event;
1577 * Get calendar events by id.
1579 * @since Moodle 2.5
1580 * @param array $eventids list of event ids
1581 * @return array Array of event entries, empty array if nothing found
1583 function calendar_get_events_by_id($eventids) {
1584 global $DB;
1586 if (!is_array($eventids) || empty($eventids)) {
1587 return array();
1590 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
1591 $wheresql = "id $wheresql";
1593 return $DB->get_records_select('event', $wheresql, $params);
1597 * Get control options for calendar.
1599 * @param string $type of calendar
1600 * @param array $data calendar information
1601 * @return string $content return available control for the calender in html
1603 function calendar_top_controls($type, $data) {
1604 global $PAGE, $OUTPUT;
1606 // Get the calendar type we are using.
1607 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1609 $content = '';
1611 // Ensure course id passed if relevant.
1612 $courseid = '';
1613 if (!empty($data['id'])) {
1614 $courseid = '&amp;course=' . $data['id'];
1617 // If we are passing a month and year then we need to convert this to a timestamp to
1618 // support multiple calendars. No where in core should these be passed, this logic
1619 // here is for third party plugins that may use this function.
1620 if (!empty($data['m']) && !empty($date['y'])) {
1621 if (!isset($data['d'])) {
1622 $data['d'] = 1;
1624 if (!checkdate($data['m'], $data['d'], $data['y'])) {
1625 $time = time();
1626 } else {
1627 $time = make_timestamp($data['y'], $data['m'], $data['d']);
1629 } else if (!empty($data['time'])) {
1630 $time = $data['time'];
1631 } else {
1632 $time = time();
1635 // Get the date for the calendar type.
1636 $date = $calendartype->timestamp_to_date_array($time);
1638 $urlbase = $PAGE->url;
1640 // We need to get the previous and next months in certain cases.
1641 if ($type == 'frontpage' || $type == 'course' || $type == 'month') {
1642 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1643 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
1644 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
1645 $prevmonthtime['hour'], $prevmonthtime['minute']);
1647 $nextmonth = calendar_add_month($date['mon'], $date['year']);
1648 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
1649 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
1650 $nextmonthtime['hour'], $nextmonthtime['minute']);
1653 switch ($type) {
1654 case 'frontpage':
1655 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1656 true, $prevmonthtime);
1657 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true,
1658 $nextmonthtime);
1659 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1660 false, false, false, $time);
1662 if (!empty($data['id'])) {
1663 $calendarlink->param('course', $data['id']);
1666 $right = $nextlink;
1668 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1669 $content .= $prevlink . '<span class="hide"> | </span>';
1670 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1671 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1672 ), array('class' => 'current'));
1673 $content .= '<span class="hide"> | </span>' . $right;
1674 $content .= "<span class=\"clearer\"><!-- --></span>\n";
1675 $content .= \html_writer::end_tag('div');
1677 break;
1678 case 'course':
1679 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1680 true, $prevmonthtime);
1681 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false,
1682 true, $nextmonthtime);
1683 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1684 false, false, false, $time);
1686 if (!empty($data['id'])) {
1687 $calendarlink->param('course', $data['id']);
1690 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1691 $content .= $prevlink . '<span class="hide"> | </span>';
1692 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1693 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1694 ), array('class' => 'current'));
1695 $content .= '<span class="hide"> | </span>' . $nextlink;
1696 $content .= "<span class=\"clearer\"><!-- --></span>";
1697 $content .= \html_writer::end_tag('div');
1698 break;
1699 case 'upcoming':
1700 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'upcoming')),
1701 false, false, false, $time);
1702 if (!empty($data['id'])) {
1703 $calendarlink->param('course', $data['id']);
1705 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1706 $content .= \html_writer::tag('div', $calendarlink, array('class' => 'centered'));
1707 break;
1708 case 'display':
1709 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1710 false, false, false, $time);
1711 if (!empty($data['id'])) {
1712 $calendarlink->param('course', $data['id']);
1714 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1715 $content .= \html_writer::tag('h3', $calendarlink);
1716 break;
1717 case 'month':
1718 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1719 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $prevmonthtime);
1720 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1721 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $nextmonthtime);
1723 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1724 $content .= $prevlink . '<span class="hide"> | </span>';
1725 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1726 $content .= '<span class="hide"> | </span>' . $nextlink;
1727 $content .= '<span class="clearer"><!-- --></span>';
1728 $content .= \html_writer::end_tag('div')."\n";
1729 break;
1730 case 'day':
1731 $days = calendar_get_days();
1733 $prevtimestamp = strtotime('-1 day', $time);
1734 $nexttimestamp = strtotime('+1 day', $time);
1736 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1737 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1739 $prevname = $days[$prevdate['wday']]['fullname'];
1740 $nextname = $days[$nextdate['wday']]['fullname'];
1741 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&amp;', false, false,
1742 false, false, $prevtimestamp);
1743 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&amp;', false, false, false,
1744 false, $nexttimestamp);
1746 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1747 $content .= $prevlink;
1748 $content .= '<span class="hide"> | </span><span class="current">' .userdate($time,
1749 get_string('strftimedaydate')) . '</span>';
1750 $content .= '<span class="hide"> | </span>' . $nextlink;
1751 $content .= "<span class=\"clearer\"><!-- --></span>";
1752 $content .= \html_writer::end_tag('div') . "\n";
1754 break;
1757 return $content;
1761 * Return the representation day.
1763 * @param int $tstamp Timestamp in GMT
1764 * @param int|bool $now current Unix timestamp
1765 * @param bool $usecommonwords
1766 * @return string the formatted date/time
1768 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1769 static $shortformat;
1771 if (empty($shortformat)) {
1772 $shortformat = get_string('strftimedayshort');
1775 if ($now === false) {
1776 $now = time();
1779 // To have it in one place, if a change is needed.
1780 $formal = userdate($tstamp, $shortformat);
1782 $datestamp = usergetdate($tstamp);
1783 $datenow = usergetdate($now);
1785 if ($usecommonwords == false) {
1786 // We don't want words, just a date.
1787 return $formal;
1788 } else if ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1789 return get_string('today', 'calendar');
1790 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1791 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12
1792 && $datenow['yday'] == 1)) {
1793 return get_string('yesterday', 'calendar');
1794 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1795 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12
1796 && $datestamp['yday'] == 1)) {
1797 return get_string('tomorrow', 'calendar');
1798 } else {
1799 return $formal;
1804 * return the formatted representation time.
1807 * @param int $time the timestamp in UTC, as obtained from the database
1808 * @return string the formatted date/time
1810 function calendar_time_representation($time) {
1811 static $langtimeformat = null;
1813 if ($langtimeformat === null) {
1814 $langtimeformat = get_string('strftimetime');
1817 $timeformat = get_user_preferences('calendar_timeformat');
1818 if (empty($timeformat)) {
1819 $timeformat = get_config(null, 'calendar_site_timeformat');
1822 // Allow language customization of selected time format.
1823 if ($timeformat === CALENDAR_TF_12) {
1824 $timeformat = get_string('strftimetime12', 'langconfig');
1825 } else if ($timeformat === CALENDAR_TF_24) {
1826 $timeformat = get_string('strftimetime24', 'langconfig');
1829 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
1833 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1835 * @param string|moodle_url $linkbase
1836 * @param int $d The number of the day.
1837 * @param int $m The number of the month.
1838 * @param int $y The number of the year.
1839 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1840 * $m and $y are kept for backwards compatibility.
1841 * @return moodle_url|null $linkbase
1843 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1844 if (empty($linkbase)) {
1845 return null;
1848 if (!($linkbase instanceof \moodle_url)) {
1849 $linkbase = new \moodle_url($linkbase);
1852 $linkbase->param('time', calendar_get_timestamp($d, $m, $y, $time));
1854 return $linkbase;
1858 * Build and return a previous month HTML link, with an arrow.
1860 * @param string $text The text label.
1861 * @param string|moodle_url $linkbase The URL stub.
1862 * @param int $d The number of the date.
1863 * @param int $m The number of the month.
1864 * @param int $y year The number of the year.
1865 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1866 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1867 * $m and $y are kept for backwards compatibility.
1868 * @return string HTML string.
1870 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1871 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1873 if (empty($href)) {
1874 return $text;
1877 $attrs = [
1878 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1879 'data-drop-zone' => 'nav-link',
1882 return link_arrow_left($text, $href->out(false), $accesshide, 'previous', $attrs);
1886 * Build and return a next month HTML link, with an arrow.
1888 * @param string $text The text label.
1889 * @param string|moodle_url $linkbase The URL stub.
1890 * @param int $d the number of the Day
1891 * @param int $m The number of the month.
1892 * @param int $y The number of the year.
1893 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1894 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1895 * $m and $y are kept for backwards compatibility.
1896 * @return string HTML string.
1898 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1899 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1901 if (empty($href)) {
1902 return $text;
1905 $attrs = [
1906 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1907 'data-drop-zone' => 'nav-link',
1910 return link_arrow_right($text, $href->out(false), $accesshide, 'next', $attrs);
1914 * Return the number of days in month.
1916 * @param int $month the number of the month.
1917 * @param int $year the number of the year
1918 * @return int
1920 function calendar_days_in_month($month, $year) {
1921 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1922 return $calendartype->get_num_days_in_month($year, $month);
1926 * Get the next following month.
1928 * @param int $month the number of the month.
1929 * @param int $year the number of the year.
1930 * @return array the following month
1932 function calendar_add_month($month, $year) {
1933 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1934 return $calendartype->get_next_month($year, $month);
1938 * Get the previous month.
1940 * @param int $month the number of the month.
1941 * @param int $year the number of the year.
1942 * @return array previous month
1944 function calendar_sub_month($month, $year) {
1945 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1946 return $calendartype->get_prev_month($year, $month);
1950 * Get per-day basis events
1952 * @param array $events list of events
1953 * @param int $month the number of the month
1954 * @param int $year the number of the year
1955 * @param array $eventsbyday event on specific day
1956 * @param array $durationbyday duration of the event in days
1957 * @param array $typesbyday event type (eg: global, course, user, or group)
1958 * @param array $courses list of courses
1959 * @return void
1961 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1962 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1964 $eventsbyday = array();
1965 $typesbyday = array();
1966 $durationbyday = array();
1968 if ($events === false) {
1969 return;
1972 foreach ($events as $event) {
1973 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
1974 if ($event->timeduration) {
1975 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
1976 } else {
1977 $enddate = $startdate;
1980 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair.
1981 if (!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) &&
1982 ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1983 continue;
1986 $eventdaystart = intval($startdate['mday']);
1988 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
1989 // Give the event to its day.
1990 $eventsbyday[$eventdaystart][] = $event->id;
1992 // Mark the day as having such an event.
1993 if ($event->courseid == SITEID && $event->groupid == 0) {
1994 $typesbyday[$eventdaystart]['startglobal'] = true;
1995 // Set event class for global event.
1996 $events[$event->id]->class = 'calendar_event_global';
1997 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1998 $typesbyday[$eventdaystart]['startcourse'] = true;
1999 // Set event class for course event.
2000 $events[$event->id]->class = 'calendar_event_course';
2001 } else if ($event->groupid) {
2002 $typesbyday[$eventdaystart]['startgroup'] = true;
2003 // Set event class for group event.
2004 $events[$event->id]->class = 'calendar_event_group';
2005 } else if ($event->userid) {
2006 $typesbyday[$eventdaystart]['startuser'] = true;
2007 // Set event class for user event.
2008 $events[$event->id]->class = 'calendar_event_user';
2012 if ($event->timeduration == 0) {
2013 // Proceed with the next.
2014 continue;
2017 // The event starts on $month $year or before.
2018 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2019 $lowerbound = intval($startdate['mday']);
2020 } else {
2021 $lowerbound = 0;
2024 // Also, it ends on $month $year or later.
2025 if ($enddate['mon'] == $month && $enddate['year'] == $year) {
2026 $upperbound = intval($enddate['mday']);
2027 } else {
2028 $upperbound = calendar_days_in_month($month, $year);
2031 // Mark all days between $lowerbound and $upperbound (inclusive) as duration.
2032 for ($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
2033 $durationbyday[$i][] = $event->id;
2034 if ($event->courseid == SITEID && $event->groupid == 0) {
2035 $typesbyday[$i]['durationglobal'] = true;
2036 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
2037 $typesbyday[$i]['durationcourse'] = true;
2038 } else if ($event->groupid) {
2039 $typesbyday[$i]['durationgroup'] = true;
2040 } else if ($event->userid) {
2041 $typesbyday[$i]['durationuser'] = true;
2046 return;
2050 * Returns the courses to load events for.
2052 * @param array $courseeventsfrom An array of courses to load calendar events for
2053 * @param bool $ignorefilters specify the use of filters, false is set as default
2054 * @return array An array of courses, groups, and user to load calendar events for based upon filters
2056 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
2057 global $USER, $CFG;
2059 // For backwards compatability we have to check whether the courses array contains
2060 // just id's in which case we need to load course objects.
2061 $coursestoload = array();
2062 foreach ($courseeventsfrom as $id => $something) {
2063 if (!is_object($something)) {
2064 $coursestoload[] = $id;
2065 unset($courseeventsfrom[$id]);
2069 $courses = array();
2070 $user = false;
2071 $group = false;
2073 // Get the capabilities that allow seeing group events from all groups.
2074 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
2076 $isloggedin = isloggedin();
2078 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
2079 $courses = array_keys($courseeventsfrom);
2081 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
2082 $courses[] = SITEID;
2084 $courses = array_unique($courses);
2085 sort($courses);
2087 if (!empty($courses) && in_array(SITEID, $courses)) {
2088 // Sort courses for consistent colour highlighting.
2089 // Effectively ignoring SITEID as setting as last course id.
2090 $key = array_search(SITEID, $courses);
2091 unset($courses[$key]);
2092 $courses[] = SITEID;
2095 if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
2096 $user = $USER->id;
2099 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
2101 if (count($courseeventsfrom) == 1) {
2102 $course = reset($courseeventsfrom);
2103 if (has_any_capability($allgroupscaps, \context_course::instance($course->id))) {
2104 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
2105 $group = array_keys($coursegroups);
2108 if ($group === false) {
2109 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, \context_system::instance())) {
2110 $group = true;
2111 } else if ($isloggedin) {
2112 $groupids = array();
2113 foreach ($courseeventsfrom as $courseid => $course) {
2114 // If the user is an editing teacher in there.
2115 if (!empty($USER->groupmember[$course->id])) {
2116 // We've already cached the users groups for this course so we can just use that.
2117 $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
2118 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2119 // If this course has groups, show events from all of those related to the current user.
2120 $coursegroups = groups_get_user_groups($course->id, $USER->id);
2121 $groupids = array_merge($groupids, $coursegroups['0']);
2124 if (!empty($groupids)) {
2125 $group = $groupids;
2130 if (empty($courses)) {
2131 $courses = false;
2134 return array($courses, $group, $user);
2138 * Return the capability for viewing a calendar event.
2140 * @param calendar_event $event event object
2141 * @return boolean
2143 function calendar_view_event_allowed(calendar_event $event) {
2144 global $USER;
2146 // Anyone can see site events.
2147 if ($event->courseid && $event->courseid == SITEID) {
2148 return true;
2151 // If a user can manage events at the site level they can see any event.
2152 $sitecontext = \context_system::instance();
2153 // If user has manageentries at site level, return true.
2154 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2155 return true;
2158 if (!empty($event->groupid)) {
2159 // If it is a group event we need to be able to manage events in the course, or be in the group.
2160 if (has_capability('moodle/calendar:manageentries', $event->context) ||
2161 has_capability('moodle/calendar:managegroupentries', $event->context)) {
2162 return true;
2165 $mycourses = enrol_get_my_courses('id');
2166 return isset($mycourses[$event->courseid]) && groups_is_member($event->groupid);
2167 } else if ($event->modulename) {
2168 // If this is a module event we need to be able to see the module.
2169 $coursemodules = [];
2170 $courseid = 0;
2171 // Override events do not have the courseid set.
2172 if ($event->courseid) {
2173 $courseid = $event->courseid;
2174 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2175 } else {
2176 $cmraw = get_coursemodule_from_instance($event->modulename, $event->instance, 0, false, MUST_EXIST);
2177 $courseid = $cmraw->course;
2178 $coursemodules = get_fast_modinfo($cmraw->course)->instances;
2180 $hasmodule = isset($coursemodules[$event->modulename]);
2181 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2183 // If modinfo doesn't know about the module, return false to be safe.
2184 if (!$hasmodule || !$hasinstance) {
2185 return false;
2188 // Must be able to see the course and the module - MDL-59304.
2189 $cm = $coursemodules[$event->modulename][$event->instance];
2190 if (!$cm->uservisible) {
2191 return false;
2193 $mycourses = enrol_get_my_courses('id');
2194 return isset($mycourses[$courseid]);
2195 } else if ($event->categoryid) {
2196 // If this is a category we need to be able to see the category.
2197 $cat = \coursecat::get($event->categoryid, IGNORE_MISSING);
2198 if (!$cat) {
2199 return false;
2201 return true;
2202 } else if (!empty($event->courseid)) {
2203 // If it is a course event we need to be able to manage events in the course, or be in the course.
2204 if (has_capability('moodle/calendar:manageentries', $event->context)) {
2205 return true;
2207 $mycourses = enrol_get_my_courses('id');
2208 return isset($mycourses[$event->courseid]);
2209 } else if ($event->userid) {
2210 if ($event->userid != $USER->id) {
2211 // No-one can ever see another users events.
2212 return false;
2214 return true;
2215 } else {
2216 throw new moodle_exception('unknown event type');
2219 return false;
2223 * Return the capability for editing calendar event.
2225 * @param calendar_event $event event object
2226 * @param bool $manualedit is the event being edited manually by the user
2227 * @return bool capability to edit event
2229 function calendar_edit_event_allowed($event, $manualedit = false) {
2230 global $USER, $DB;
2232 // Must be logged in.
2233 if (!isloggedin()) {
2234 return false;
2237 // Can not be using guest account.
2238 if (isguestuser()) {
2239 return false;
2242 if ($manualedit && !empty($event->modulename)) {
2243 $hascallback = component_callback_exists(
2244 'mod_' . $event->modulename,
2245 'core_calendar_event_timestart_updated'
2248 if (!$hascallback) {
2249 // If the activity hasn't implemented the correct callback
2250 // to handle changes to it's events then don't allow any
2251 // manual changes to them.
2252 return false;
2255 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2256 $hasmodule = isset($coursemodules[$event->modulename]);
2257 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2259 // If modinfo doesn't know about the module, return false to be safe.
2260 if (!$hasmodule || !$hasinstance) {
2261 return false;
2264 $coursemodule = $coursemodules[$event->modulename][$event->instance];
2265 $context = context_module::instance($coursemodule->id);
2266 // This is the capability that allows a user to modify the activity
2267 // settings. Since the activity generated this event we need to check
2268 // that the current user has the same capability before allowing them
2269 // to update the event because the changes to the event will be
2270 // reflected within the activity.
2271 return has_capability('moodle/course:manageactivities', $context);
2274 // You cannot edit URL based calendar subscription events presently.
2275 if (!empty($event->subscriptionid)) {
2276 if (!empty($event->subscription->url)) {
2277 // This event can be updated externally, so it cannot be edited.
2278 return false;
2282 $sitecontext = \context_system::instance();
2284 // If user has manageentries at site level, return true.
2285 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2286 return true;
2289 // If groupid is set, it's definitely a group event.
2290 if (!empty($event->groupid)) {
2291 // Allow users to add/edit group events if -
2292 // 1) They have manageentries for the course OR
2293 // 2) They have managegroupentries AND are in the group.
2294 $group = $DB->get_record('groups', array('id' => $event->groupid));
2295 return $group && (
2296 has_capability('moodle/calendar:manageentries', $event->context) ||
2297 (has_capability('moodle/calendar:managegroupentries', $event->context)
2298 && groups_is_member($event->groupid)));
2299 } else if (!empty($event->courseid)) {
2300 // If groupid is not set, but course is set, it's definitely a course event.
2301 return has_capability('moodle/calendar:manageentries', $event->context);
2302 } else if (!empty($event->categoryid)) {
2303 // If groupid is not set, but category is set, it's definitely a category event.
2304 return has_capability('moodle/calendar:manageentries', $event->context);
2305 } else if (!empty($event->userid) && $event->userid == $USER->id) {
2306 // If course is not set, but userid id set, it's a user event.
2307 return (has_capability('moodle/calendar:manageownentries', $event->context));
2308 } else if (!empty($event->userid)) {
2309 return (has_capability('moodle/calendar:manageentries', $event->context));
2312 return false;
2316 * Return the capability for deleting a calendar event.
2318 * @param calendar_event $event The event object
2319 * @return bool Whether the user has permission to delete the event or not.
2321 function calendar_delete_event_allowed($event) {
2322 // Only allow delete if you have capabilities and it is not an module event.
2323 return (calendar_edit_event_allowed($event) && empty($event->modulename));
2327 * Returns the default courses to display on the calendar when there isn't a specific
2328 * course to display.
2330 * @param int $courseid (optional) If passed, an additional course can be returned for admins (the current course).
2331 * @param string $fields Comma separated list of course fields to return.
2332 * @param bool $canmanage If true, this will return the list of courses the current user can create events in, rather
2333 * than the list of courses they see events from (an admin can always add events in a course
2334 * calendar, even if they are not enrolled in the course).
2335 * @return array $courses Array of courses to display
2337 function calendar_get_default_courses($courseid = null, $fields = '*', $canmanage=false) {
2338 global $CFG, $DB;
2340 if (!isloggedin()) {
2341 return array();
2344 if (has_capability('moodle/calendar:manageentries', context_system::instance()) &&
2345 (!empty($CFG->calendar_adminseesall) || $canmanage)) {
2347 // Add a c. prefix to every field as expected by get_courses function.
2348 $fieldlist = explode(',', $fields);
2350 $prefixedfields = array_map(function($value) {
2351 return 'c.' . trim($value);
2352 }, $fieldlist);
2353 $courses = get_courses('all', 'c.shortname', implode(',', $prefixedfields));
2354 } else {
2355 $courses = enrol_get_my_courses($fields);
2358 if ($courseid && $courseid != SITEID) {
2359 if (empty($courses[$courseid]) && has_capability('moodle/calendar:manageentries', context_system::instance())) {
2360 // Allow a site admin to see calendars from courses he is not enrolled in.
2361 // This will come from $COURSE.
2362 $courses[$courseid] = get_course($courseid);
2366 return $courses;
2370 * Get event format time.
2372 * @param calendar_event $event event object
2373 * @param int $now current time in gmt
2374 * @param array $linkparams list of params for event link
2375 * @param bool $usecommonwords the words as formatted date/time.
2376 * @param int $showtime determine the show time GMT timestamp
2377 * @return string $eventtime link/string for event time
2379 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
2380 $starttime = $event->timestart;
2381 $endtime = $event->timestart + $event->timeduration;
2383 if (empty($linkparams) || !is_array($linkparams)) {
2384 $linkparams = array();
2387 $linkparams['view'] = 'day';
2389 // OK, now to get a meaningful display.
2390 // Check if there is a duration for this event.
2391 if ($event->timeduration) {
2392 // Get the midnight of the day the event will start.
2393 $usermidnightstart = usergetmidnight($starttime);
2394 // Get the midnight of the day the event will end.
2395 $usermidnightend = usergetmidnight($endtime);
2396 // Check if we will still be on the same day.
2397 if ($usermidnightstart == $usermidnightend) {
2398 // Check if we are running all day.
2399 if ($event->timeduration == DAYSECS) {
2400 $time = get_string('allday', 'calendar');
2401 } else { // Specify the time we will be running this from.
2402 $datestart = calendar_time_representation($starttime);
2403 $dateend = calendar_time_representation($endtime);
2404 $time = $datestart . ' <strong>&raquo;</strong> ' . $dateend;
2407 // Set printable representation.
2408 if (!$showtime) {
2409 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2410 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2411 $eventtime = \html_writer::link($url, $day) . ', ' . $time;
2412 } else {
2413 $eventtime = $time;
2415 } else { // It must spans two or more days.
2416 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
2417 if ($showtime == $usermidnightstart) {
2418 $daystart = '';
2420 $timestart = calendar_time_representation($event->timestart);
2421 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
2422 if ($showtime == $usermidnightend) {
2423 $dayend = '';
2425 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
2427 // Set printable representation.
2428 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2429 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2430 $eventtime = $timestart . ' <strong>&raquo;</strong> ' . \html_writer::link($url, $dayend) . $timeend;
2431 } else {
2432 // The event is in the future, print start and end links.
2433 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2434 $eventtime = \html_writer::link($url, $daystart) . $timestart . ' <strong>&raquo;</strong> ';
2436 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2437 $eventtime .= \html_writer::link($url, $dayend) . $timeend;
2440 } else { // There is no time duration.
2441 $time = calendar_time_representation($event->timestart);
2442 // Set printable representation.
2443 if (!$showtime) {
2444 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2445 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2446 $eventtime = \html_writer::link($url, $day) . ', ' . trim($time);
2447 } else {
2448 $eventtime = $time;
2452 // Check if It has expired.
2453 if ($event->timestart + $event->timeduration < $now) {
2454 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2457 return $eventtime;
2461 * Checks to see if the requested type of event should be shown for the given user.
2463 * @param int $type The type to check the display for (default is to display all)
2464 * @param stdClass|int|null $user The user to check for - by default the current user
2465 * @return bool True if the tyep should be displayed false otherwise
2467 function calendar_show_event_type($type, $user = null) {
2468 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
2470 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2471 global $SESSION;
2472 if (!isset($SESSION->calendarshoweventtype)) {
2473 $SESSION->calendarshoweventtype = $default;
2475 return $SESSION->calendarshoweventtype & $type;
2476 } else {
2477 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2482 * Sets the display of the event type given $display.
2484 * If $display = true the event type will be shown.
2485 * If $display = false the event type will NOT be shown.
2486 * If $display = null the current value will be toggled and saved.
2488 * @param int $type object of CALENDAR_EVENT_XXX
2489 * @param bool $display option to display event type
2490 * @param stdClass|int $user moodle user object or id, null means current user
2492 function calendar_set_event_type_display($type, $display = null, $user = null) {
2493 $persist = get_user_preferences('calendar_persistflt', 0, $user);
2494 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP
2495 + CALENDAR_EVENT_USER + CALENDAR_EVENT_COURSECAT;
2496 if ($persist === 0) {
2497 global $SESSION;
2498 if (!isset($SESSION->calendarshoweventtype)) {
2499 $SESSION->calendarshoweventtype = $default;
2501 $preference = $SESSION->calendarshoweventtype;
2502 } else {
2503 $preference = get_user_preferences('calendar_savedflt', $default, $user);
2505 $current = $preference & $type;
2506 if ($display === null) {
2507 $display = !$current;
2509 if ($display && !$current) {
2510 $preference += $type;
2511 } else if (!$display && $current) {
2512 $preference -= $type;
2514 if ($persist === 0) {
2515 $SESSION->calendarshoweventtype = $preference;
2516 } else {
2517 if ($preference == $default) {
2518 unset_user_preference('calendar_savedflt', $user);
2519 } else {
2520 set_user_preference('calendar_savedflt', $preference, $user);
2526 * Get calendar's allowed types.
2528 * @param stdClass $allowed list of allowed edit for event type
2529 * @param stdClass|int $course object of a course or course id
2530 * @param array $groups array of groups for the given course
2531 * @param stdClass|int $category object of a category
2533 function calendar_get_allowed_types(&$allowed, $course = null, $groups = null, $category = null) {
2534 global $USER, $DB;
2536 $allowed = new \stdClass();
2537 $allowed->user = has_capability('moodle/calendar:manageownentries', \context_system::instance());
2538 $allowed->groups = false;
2539 $allowed->courses = false;
2540 $allowed->categories = false;
2541 $allowed->site = has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID));
2542 $getgroupsfunc = function($course, $context, $user) use ($groups) {
2543 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2544 if (has_capability('moodle/site:accessallgroups', $context)) {
2545 return is_null($groups) ? groups_get_all_groups($course->id) : $groups;
2546 } else {
2547 if (is_null($groups)) {
2548 return groups_get_all_groups($course->id, $user->id);
2549 } else {
2550 return array_filter($groups, function($group) use ($user) {
2551 return isset($group->members[$user->id]);
2557 return false;
2560 if (!empty($course)) {
2561 if (!is_object($course)) {
2562 $course = $DB->get_record('course', array('id' => $course), 'id, groupmode, groupmodeforce', MUST_EXIST);
2564 if ($course->id != SITEID) {
2565 $coursecontext = \context_course::instance($course->id);
2566 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
2568 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2569 $allowed->courses = array($course->id => 1);
2570 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2571 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
2572 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2577 if (!empty($category)) {
2578 $catcontext = \context_coursecat::instance($category->id);
2579 if (has_capability('moodle/category:manage', $catcontext)) {
2580 $allowed->categories = [$category->id => 1];
2586 * Get all of the allowed types for all of the courses and groups
2587 * the logged in user belongs to.
2589 * The returned array will optionally have 5 keys:
2590 * 'user' : true if the logged in user can create user events
2591 * 'site' : true if the logged in user can create site events
2592 * 'category' : array of course categories that the user can create events for
2593 * 'course' : array of courses that the user can create events for
2594 * 'group': array of groups that the user can create events for
2595 * 'groupcourses' : array of courses that the groups belong to (can
2596 * be different from the list in 'course'.
2598 * @return array The array of allowed types.
2600 function calendar_get_all_allowed_types() {
2601 global $CFG, $USER, $DB;
2603 require_once($CFG->libdir . '/enrollib.php');
2605 $types = [];
2607 $allowed = new stdClass();
2609 calendar_get_allowed_types($allowed);
2611 if ($allowed->user) {
2612 $types['user'] = true;
2615 if ($allowed->site) {
2616 $types['site'] = true;
2619 if (coursecat::has_manage_capability_on_any()) {
2620 $types['category'] = coursecat::make_categories_list('moodle/category:manage');
2623 // This function warms the context cache for the course so the calls
2624 // to load the course context in calendar_get_allowed_types don't result
2625 // in additional DB queries.
2626 $courses = calendar_get_default_courses(null, 'id, groupmode, groupmodeforce', true);
2628 // We want to pre-fetch all of the groups for each course in a single
2629 // query to avoid calendar_get_allowed_types from hitting the DB for
2630 // each separate course.
2631 $groups = groups_get_all_groups_for_courses($courses);
2633 foreach ($courses as $course) {
2634 $coursegroups = isset($groups[$course->id]) ? $groups[$course->id] : null;
2635 calendar_get_allowed_types($allowed, $course, $coursegroups);
2637 if (!empty($allowed->courses)) {
2638 $types['course'][$course->id] = $course;
2641 if (!empty($allowed->groups)) {
2642 $types['groupcourses'][$course->id] = $course;
2644 if (!isset($types['group'])) {
2645 $types['group'] = array_values($allowed->groups);
2646 } else {
2647 $types['group'] = array_merge($types['group'], array_values($allowed->groups));
2652 return $types;
2656 * See if user can add calendar entries at all used to print the "New Event" button.
2658 * @param stdClass $course object of a course or course id
2659 * @return bool has the capability to add at least one event type
2661 function calendar_user_can_add_event($course) {
2662 if (!isloggedin() || isguestuser()) {
2663 return false;
2666 calendar_get_allowed_types($allowed, $course);
2668 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->categories || $allowed->site);
2672 * Check wether the current user is permitted to add events.
2674 * @param stdClass $event object of event
2675 * @return bool has the capability to add event
2677 function calendar_add_event_allowed($event) {
2678 global $USER, $DB;
2680 // Can not be using guest account.
2681 if (!isloggedin() or isguestuser()) {
2682 return false;
2685 $sitecontext = \context_system::instance();
2687 // If user has manageentries at site level, always return true.
2688 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2689 return true;
2692 switch ($event->eventtype) {
2693 case 'category':
2694 return has_capability('moodle/category:manage', $event->context);
2695 case 'course':
2696 return has_capability('moodle/calendar:manageentries', $event->context);
2697 case 'group':
2698 // Allow users to add/edit group events if -
2699 // 1) They have manageentries (= entries for whole course).
2700 // 2) They have managegroupentries AND are in the group.
2701 $group = $DB->get_record('groups', array('id' => $event->groupid));
2702 return $group && (
2703 has_capability('moodle/calendar:manageentries', $event->context) ||
2704 (has_capability('moodle/calendar:managegroupentries', $event->context)
2705 && groups_is_member($event->groupid)));
2706 case 'user':
2707 if ($event->userid == $USER->id) {
2708 return (has_capability('moodle/calendar:manageownentries', $event->context));
2710 // There is intentionally no 'break'.
2711 case 'site':
2712 return has_capability('moodle/calendar:manageentries', $event->context);
2713 default:
2714 return has_capability('moodle/calendar:manageentries', $event->context);
2719 * Returns option list for the poll interval setting.
2721 * @return array An array of poll interval options. Interval => description.
2723 function calendar_get_pollinterval_choices() {
2724 return array(
2725 '0' => new \lang_string('never', 'calendar'),
2726 HOURSECS => new \lang_string('hourly', 'calendar'),
2727 DAYSECS => new \lang_string('daily', 'calendar'),
2728 WEEKSECS => new \lang_string('weekly', 'calendar'),
2729 '2628000' => new \lang_string('monthly', 'calendar'),
2730 YEARSECS => new \lang_string('annually', 'calendar')
2735 * Returns option list of available options for the calendar event type, given the current user and course.
2737 * @param int $courseid The id of the course
2738 * @return array An array containing the event types the user can create.
2740 function calendar_get_eventtype_choices($courseid) {
2741 $choices = array();
2742 $allowed = new \stdClass;
2743 calendar_get_allowed_types($allowed, $courseid);
2745 if ($allowed->user) {
2746 $choices['user'] = get_string('userevents', 'calendar');
2748 if ($allowed->site) {
2749 $choices['site'] = get_string('siteevents', 'calendar');
2751 if (!empty($allowed->courses)) {
2752 $choices['course'] = get_string('courseevents', 'calendar');
2754 if (!empty($allowed->categories)) {
2755 $choices['category'] = get_string('categoryevents', 'calendar');
2757 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2758 $choices['group'] = get_string('group');
2761 return array($choices, $allowed->groups);
2765 * Add an iCalendar subscription to the database.
2767 * @param stdClass $sub The subscription object (e.g. from the form)
2768 * @return int The insert ID, if any.
2770 function calendar_add_subscription($sub) {
2771 global $DB, $USER, $SITE;
2773 // Undo the form definition work around to allow us to have two different
2774 // course selectors present depending on which event type the user selects.
2775 if (!empty($sub->groupcourseid)) {
2776 $sub->courseid = $sub->groupcourseid;
2777 unset($sub->groupcourseid);
2780 // Pull the group id back out of the value. The form saves the value
2781 // as "<courseid>-<groupid>" to allow the javascript to work correctly.
2782 if (!empty($sub->groupid)) {
2783 list($courseid, $groupid) = explode('-', $sub->groupid);
2784 $sub->courseid = $courseid;
2785 $sub->groupid = $groupid;
2788 // Default course id if none is set.
2789 if (empty($sub->courseid)) {
2790 if ($sub->eventtype === 'site') {
2791 $sub->courseid = SITEID;
2792 } else {
2793 $sub->courseid = 0;
2797 if ($sub->eventtype === 'site') {
2798 $sub->courseid = $SITE->id;
2799 } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
2800 $sub->courseid = $sub->courseid;
2801 } else if ($sub->eventtype === 'category') {
2802 $sub->categoryid = $sub->categoryid;
2803 } else {
2804 // User events.
2805 $sub->courseid = 0;
2807 $sub->userid = $USER->id;
2809 // File subscriptions never update.
2810 if (empty($sub->url)) {
2811 $sub->pollinterval = 0;
2814 if (!empty($sub->name)) {
2815 if (empty($sub->id)) {
2816 $id = $DB->insert_record('event_subscriptions', $sub);
2817 // We cannot cache the data here because $sub is not complete.
2818 $sub->id = $id;
2819 // Trigger event, calendar subscription added.
2820 $eventparams = array('objectid' => $sub->id,
2821 'context' => calendar_get_calendar_context($sub),
2822 'other' => array(
2823 'eventtype' => $sub->eventtype,
2826 switch ($sub->eventtype) {
2827 case 'category':
2828 $eventparams['other']['categoryid'] = $sub->categoryid;
2829 break;
2830 case 'course':
2831 $eventparams['other']['courseid'] = $sub->courseid;
2832 break;
2833 case 'group':
2834 $eventparams['other']['courseid'] = $sub->courseid;
2835 $eventparams['other']['groupid'] = $sub->groupid;
2836 break;
2837 default:
2838 $eventparams['other']['courseid'] = $sub->courseid;
2841 $event = \core\event\calendar_subscription_created::create($eventparams);
2842 $event->trigger();
2843 return $id;
2844 } else {
2845 // Why are we doing an update here?
2846 calendar_update_subscription($sub);
2847 return $sub->id;
2849 } else {
2850 print_error('errorbadsubscription', 'importcalendar');
2855 * Add an iCalendar event to the Moodle calendar.
2857 * @param stdClass $event The RFC-2445 iCalendar event
2858 * @param int $unused Deprecated
2859 * @param int $subscriptionid The iCalendar subscription ID
2860 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2861 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2862 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2864 function calendar_add_icalendar_event($event, $unused = null, $subscriptionid, $timezone='UTC') {
2865 global $DB;
2867 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2868 if (empty($event->properties['SUMMARY'])) {
2869 return 0;
2872 $name = $event->properties['SUMMARY'][0]->value;
2873 $name = str_replace('\n', '<br />', $name);
2874 $name = str_replace('\\', '', $name);
2875 $name = preg_replace('/\s+/u', ' ', $name);
2877 $eventrecord = new \stdClass;
2878 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
2880 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2881 $description = '';
2882 } else {
2883 $description = $event->properties['DESCRIPTION'][0]->value;
2884 $description = clean_param($description, PARAM_NOTAGS);
2885 $description = str_replace('\n', '<br />', $description);
2886 $description = str_replace('\\', '', $description);
2887 $description = preg_replace('/\s+/u', ' ', $description);
2889 $eventrecord->description = $description;
2891 // Probably a repeating event with RRULE etc. TODO: skip for now.
2892 if (empty($event->properties['DTSTART'][0]->value)) {
2893 return 0;
2896 if (isset($event->properties['DTSTART'][0]->parameters['TZID'])) {
2897 $tz = $event->properties['DTSTART'][0]->parameters['TZID'];
2898 } else {
2899 $tz = $timezone;
2901 $tz = \core_date::normalise_timezone($tz);
2902 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value . ' ' . $tz);
2903 if (empty($event->properties['DTEND'])) {
2904 $eventrecord->timeduration = 0; // No duration if no end time specified.
2905 } else {
2906 if (isset($event->properties['DTEND'][0]->parameters['TZID'])) {
2907 $endtz = $event->properties['DTEND'][0]->parameters['TZID'];
2908 } else {
2909 $endtz = $timezone;
2911 $endtz = \core_date::normalise_timezone($endtz);
2912 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value . ' ' . $endtz) - $eventrecord->timestart;
2915 // Check to see if it should be treated as an all day event.
2916 if ($eventrecord->timeduration == DAYSECS) {
2917 // Check to see if the event started at Midnight on the imported calendar.
2918 date_default_timezone_set($timezone);
2919 if (date('H:i:s', $eventrecord->timestart) === "00:00:00") {
2920 // This event should be an all day event. This is not correct, we don't do anything differently for all day events.
2921 // See MDL-56227.
2922 $eventrecord->timeduration = 0;
2924 \core_date::set_default_server_timezone();
2927 $eventrecord->uuid = $event->properties['UID'][0]->value;
2928 $eventrecord->timemodified = time();
2930 // Add the iCal subscription details if required.
2931 // We should never do anything with an event without a subscription reference.
2932 $sub = calendar_get_subscription($subscriptionid);
2933 $eventrecord->subscriptionid = $subscriptionid;
2934 $eventrecord->userid = $sub->userid;
2935 $eventrecord->groupid = $sub->groupid;
2936 $eventrecord->courseid = $sub->courseid;
2937 $eventrecord->categoryid = $sub->categoryid;
2938 $eventrecord->eventtype = $sub->eventtype;
2940 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid,
2941 'subscriptionid' => $eventrecord->subscriptionid))) {
2942 $eventrecord->id = $updaterecord->id;
2943 $return = CALENDAR_IMPORT_EVENT_UPDATED; // Update.
2944 } else {
2945 $return = CALENDAR_IMPORT_EVENT_INSERTED; // Insert.
2947 if ($createdevent = \calendar_event::create($eventrecord, false)) {
2948 if (!empty($event->properties['RRULE'])) {
2949 // Repeating events.
2950 date_default_timezone_set($tz); // Change time zone to parse all events.
2951 $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
2952 $rrule->parse_rrule();
2953 $rrule->create_events($createdevent);
2954 \core_date::set_default_server_timezone(); // Change time zone back to what it was.
2956 return $return;
2957 } else {
2958 return 0;
2963 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2965 * @param int $subscriptionid The ID of the subscription we are acting upon.
2966 * @param int $pollinterval The poll interval to use.
2967 * @param int $action The action to be performed. One of update or remove.
2968 * @throws dml_exception if invalid subscriptionid is provided
2969 * @return string A log of the import progress, including errors
2971 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2972 // Fetch the subscription from the database making sure it exists.
2973 $sub = calendar_get_subscription($subscriptionid);
2975 // Update or remove the subscription, based on action.
2976 switch ($action) {
2977 case CALENDAR_SUBSCRIPTION_UPDATE:
2978 // Skip updating file subscriptions.
2979 if (empty($sub->url)) {
2980 break;
2982 $sub->pollinterval = $pollinterval;
2983 calendar_update_subscription($sub);
2985 // Update the events.
2986 return "<p>" . get_string('subscriptionupdated', 'calendar', $sub->name) . "</p>" .
2987 calendar_update_subscription_events($subscriptionid);
2988 case CALENDAR_SUBSCRIPTION_REMOVE:
2989 calendar_delete_subscription($subscriptionid);
2990 return get_string('subscriptionremoved', 'calendar', $sub->name);
2991 break;
2992 default:
2993 break;
2995 return '';
2999 * Delete subscription and all related events.
3001 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
3003 function calendar_delete_subscription($subscription) {
3004 global $DB;
3006 if (!is_object($subscription)) {
3007 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST);
3010 // Delete subscription and related events.
3011 $DB->delete_records('event', array('subscriptionid' => $subscription->id));
3012 $DB->delete_records('event_subscriptions', array('id' => $subscription->id));
3013 \cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id));
3015 // Trigger event, calendar subscription deleted.
3016 $eventparams = array('objectid' => $subscription->id,
3017 'context' => calendar_get_calendar_context($subscription),
3018 'other' => array(
3019 'eventtype' => $subscription->eventtype,
3022 switch ($subscription->eventtype) {
3023 case 'category':
3024 $eventparams['other']['categoryid'] = $subscription->categoryid;
3025 break;
3026 case 'course':
3027 $eventparams['other']['courseid'] = $subscription->courseid;
3028 break;
3029 case 'group':
3030 $eventparams['other']['courseid'] = $subscription->courseid;
3031 $eventparams['other']['groupid'] = $subscription->groupid;
3032 break;
3033 default:
3034 $eventparams['other']['courseid'] = $subscription->courseid;
3036 $event = \core\event\calendar_subscription_deleted::create($eventparams);
3037 $event->trigger();
3041 * From a URL, fetch the calendar and return an iCalendar object.
3043 * @param string $url The iCalendar URL
3044 * @return iCalendar The iCalendar object
3046 function calendar_get_icalendar($url) {
3047 global $CFG;
3049 require_once($CFG->libdir . '/filelib.php');
3051 $curl = new \curl();
3052 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
3053 $calendar = $curl->get($url);
3055 // Http code validation should actually be the job of curl class.
3056 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
3057 throw new \moodle_exception('errorinvalidicalurl', 'calendar');
3060 $ical = new \iCalendar();
3061 $ical->unserialize($calendar);
3063 return $ical;
3067 * Import events from an iCalendar object into a course calendar.
3069 * @param iCalendar $ical The iCalendar object.
3070 * @param int $courseid The course ID for the calendar.
3071 * @param int $subscriptionid The subscription ID.
3072 * @return string A log of the import progress, including errors.
3074 function calendar_import_icalendar_events($ical, $unused = null, $subscriptionid = null) {
3075 global $DB;
3077 $return = '';
3078 $eventcount = 0;
3079 $updatecount = 0;
3081 // Large calendars take a while...
3082 if (!CLI_SCRIPT) {
3083 \core_php_time_limit::raise(300);
3086 // Mark all events in a subscription with a zero timestamp.
3087 if (!empty($subscriptionid)) {
3088 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
3089 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3092 // Grab the timezone from the iCalendar file to be used later.
3093 if (isset($ical->properties['X-WR-TIMEZONE'][0]->value)) {
3094 $timezone = $ical->properties['X-WR-TIMEZONE'][0]->value;
3095 } else {
3096 $timezone = 'UTC';
3099 $return = '';
3100 foreach ($ical->components['VEVENT'] as $event) {
3101 $res = calendar_add_icalendar_event($event, null, $subscriptionid, $timezone);
3102 switch ($res) {
3103 case CALENDAR_IMPORT_EVENT_UPDATED:
3104 $updatecount++;
3105 break;
3106 case CALENDAR_IMPORT_EVENT_INSERTED:
3107 $eventcount++;
3108 break;
3109 case 0:
3110 $return .= '<p>' . get_string('erroraddingevent', 'calendar') . ': ';
3111 if (empty($event->properties['SUMMARY'])) {
3112 $return .= '(' . get_string('notitle', 'calendar') . ')';
3113 } else {
3114 $return .= $event->properties['SUMMARY'][0]->value;
3116 $return .= "</p>\n";
3117 break;
3121 $return .= "<p>" . get_string('eventsimported', 'calendar', $eventcount) . "</p> ";
3122 $return .= "<p>" . get_string('eventsupdated', 'calendar', $updatecount) . "</p>";
3124 // Delete remaining zero-marked events since they're not in remote calendar.
3125 if (!empty($subscriptionid)) {
3126 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3127 if (!empty($deletecount)) {
3128 $DB->delete_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3129 $return .= "<p> " . get_string('eventsdeleted', 'calendar') . ": {$deletecount} </p>\n";
3133 return $return;
3137 * Fetch a calendar subscription and update the events in the calendar.
3139 * @param int $subscriptionid The course ID for the calendar.
3140 * @return string A log of the import progress, including errors.
3142 function calendar_update_subscription_events($subscriptionid) {
3143 $sub = calendar_get_subscription($subscriptionid);
3145 // Don't update a file subscription.
3146 if (empty($sub->url)) {
3147 return 'File subscription not updated.';
3150 $ical = calendar_get_icalendar($sub->url);
3151 $return = calendar_import_icalendar_events($ical, null, $subscriptionid);
3152 $sub->lastupdated = time();
3154 calendar_update_subscription($sub);
3156 return $return;
3160 * Update a calendar subscription. Also updates the associated cache.
3162 * @param stdClass|array $subscription Subscription record.
3163 * @throws coding_exception If something goes wrong
3164 * @since Moodle 2.5
3166 function calendar_update_subscription($subscription) {
3167 global $DB;
3169 if (is_array($subscription)) {
3170 $subscription = (object)$subscription;
3172 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
3173 throw new \coding_exception('Cannot update a subscription without a valid id');
3176 $DB->update_record('event_subscriptions', $subscription);
3178 // Update cache.
3179 $cache = \cache::make('core', 'calendar_subscriptions');
3180 $cache->set($subscription->id, $subscription);
3182 // Trigger event, calendar subscription updated.
3183 $eventparams = array('userid' => $subscription->userid,
3184 'objectid' => $subscription->id,
3185 'context' => calendar_get_calendar_context($subscription),
3186 'other' => array(
3187 'eventtype' => $subscription->eventtype,
3190 switch ($subscription->eventtype) {
3191 case 'category':
3192 $eventparams['other']['categoryid'] = $subscription->categoryid;
3193 break;
3194 case 'course':
3195 $eventparams['other']['courseid'] = $subscription->courseid;
3196 break;
3197 case 'group':
3198 $eventparams['other']['courseid'] = $subscription->courseid;
3199 $eventparams['other']['groupid'] = $subscription->groupid;
3200 break;
3201 default:
3202 $eventparams['other']['courseid'] = $subscription->courseid;
3204 $event = \core\event\calendar_subscription_updated::create($eventparams);
3205 $event->trigger();
3209 * Checks to see if the user can edit a given subscription feed.
3211 * @param mixed $subscriptionorid Subscription object or id
3212 * @return bool true if current user can edit the subscription else false
3214 function calendar_can_edit_subscription($subscriptionorid) {
3215 if (is_array($subscriptionorid)) {
3216 $subscription = (object)$subscriptionorid;
3217 } else if (is_object($subscriptionorid)) {
3218 $subscription = $subscriptionorid;
3219 } else {
3220 $subscription = calendar_get_subscription($subscriptionorid);
3223 $allowed = new \stdClass;
3224 $courseid = $subscription->courseid;
3225 $categoryid = $subscription->categoryid;
3226 $groupid = $subscription->groupid;
3227 $category = null;
3229 if (!empty($categoryid)) {
3230 $category = \coursecat::get($categoryid);
3232 calendar_get_allowed_types($allowed, $courseid, null, $category);
3233 switch ($subscription->eventtype) {
3234 case 'user':
3235 return $allowed->user;
3236 case 'course':
3237 if (isset($allowed->courses[$courseid])) {
3238 return $allowed->courses[$courseid];
3239 } else {
3240 return false;
3242 case 'category':
3243 if (isset($allowed->categories[$categoryid])) {
3244 return $allowed->categories[$categoryid];
3245 } else {
3246 return false;
3248 case 'site':
3249 return $allowed->site;
3250 case 'group':
3251 if (isset($allowed->groups[$groupid])) {
3252 return $allowed->groups[$groupid];
3253 } else {
3254 return false;
3256 default:
3257 return false;
3262 * Helper function to determine the context of a calendar subscription.
3263 * Subscriptions can be created in two contexts COURSE, or USER.
3265 * @param stdClass $subscription
3266 * @return context instance
3268 function calendar_get_calendar_context($subscription) {
3269 // Determine context based on calendar type.
3270 if ($subscription->eventtype === 'site') {
3271 $context = \context_course::instance(SITEID);
3272 } else if ($subscription->eventtype === 'group' || $subscription->eventtype === 'course') {
3273 $context = \context_course::instance($subscription->courseid);
3274 } else {
3275 $context = \context_user::instance($subscription->userid);
3277 return $context;
3281 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
3283 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3285 * @return array
3287 function core_calendar_user_preferences() {
3288 $preferences = [];
3289 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED, 'default' => '0',
3290 'choices' => array('0', CALENDAR_TF_12, CALENDAR_TF_24)
3292 $preferences['calendar_startwday'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3293 'choices' => array(0, 1, 2, 3, 4, 5, 6));
3294 $preferences['calendar_maxevents'] = array('type' => PARAM_INT, 'choices' => range(1, 20));
3295 $preferences['calendar_lookahead'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 365,
3296 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3297 $preferences['calendar_persistflt'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3298 'choices' => array(0, 1));
3299 return $preferences;
3303 * Get legacy calendar events
3305 * @param int $tstart Start time of time range for events
3306 * @param int $tend End time of time range for events
3307 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3308 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3309 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3310 * @param boolean $withduration whether only events starting within time range selected
3311 * or events in progress/already started selected as well
3312 * @param boolean $ignorehidden whether to select only visible events or all events
3313 * @param array $categories array of category ids and/or objects.
3314 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3316 function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses,
3317 $withduration = true, $ignorehidden = true, $categories = []) {
3318 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3319 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3320 // parameters, but with the new API method, only null and arrays are accepted.
3321 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3322 // If parameter is true, return null.
3323 if ($param === true) {
3324 return null;
3327 // If parameter is false, return an empty array.
3328 if ($param === false) {
3329 return [];
3332 // If the parameter is a scalar value, enclose it in an array.
3333 if (!is_array($param)) {
3334 return [$param];
3337 // No normalisation required.
3338 return $param;
3339 }, [$users, $groups, $courses, $categories]);
3341 $mapper = \core_calendar\local\event\container::get_event_mapper();
3342 $events = \core_calendar\local\api::get_events(
3343 $tstart,
3344 $tend,
3345 null,
3346 null,
3347 null,
3348 null,
3350 null,
3351 $userparam,
3352 $groupparam,
3353 $courseparam,
3354 $categoryparam,
3355 $withduration,
3356 $ignorehidden
3359 return array_reduce($events, function($carry, $event) use ($mapper) {
3360 return $carry + [$event->get_id() => $mapper->from_event_to_stdclass($event)];
3361 }, []);
3366 * Get the calendar view output.
3368 * @param \calendar_information $calendar The calendar being represented
3369 * @param string $view The type of calendar to have displayed
3370 * @param bool $includenavigation Whether to include navigation
3371 * @param bool $skipevents Whether to load the events or not
3372 * @return array[array, string]
3374 function calendar_get_view(\calendar_information $calendar, $view, $includenavigation = true, bool $skipevents = false) {
3375 global $PAGE, $CFG;
3377 $renderer = $PAGE->get_renderer('core_calendar');
3378 $type = \core_calendar\type_factory::get_calendar_instance();
3380 // Calculate the bounds of the month.
3381 $calendardate = $type->timestamp_to_date_array($calendar->time);
3383 $date = new \DateTime('now', core_date::get_user_timezone_object(99));
3384 $eventlimit = 200;
3386 if ($view === 'day') {
3387 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday']);
3388 $date->setTimestamp($tstart);
3389 $date->modify('+1 day');
3390 } else if ($view === 'upcoming' || $view === 'upcoming_mini') {
3391 // Number of days in the future that will be used to fetch events.
3392 if (isset($CFG->calendar_lookahead)) {
3393 $defaultlookahead = intval($CFG->calendar_lookahead);
3394 } else {
3395 $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD;
3397 $lookahead = get_user_preferences('calendar_lookahead', $defaultlookahead);
3399 // Maximum number of events to be displayed on upcoming view.
3400 $defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS;
3401 if (isset($CFG->calendar_maxevents)) {
3402 $defaultmaxevents = intval($CFG->calendar_maxevents);
3404 $eventlimit = get_user_preferences('calendar_maxevents', $defaultmaxevents);
3406 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday'],
3407 $calendardate['hours']);
3408 $date->setTimestamp($tstart);
3409 $date->modify('+' . $lookahead . ' days');
3410 } else {
3411 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], 1);
3412 $monthdays = $type->get_num_days_in_month($calendardate['year'], $calendardate['mon']);
3413 $date->setTimestamp($tstart);
3414 $date->modify('+' . $monthdays . ' days');
3416 if ($view === 'mini' || $view === 'minithree') {
3417 $template = 'core_calendar/calendar_mini';
3418 } else {
3419 $template = 'core_calendar/calendar_month';
3423 // We need to extract 1 second to ensure that we don't get into the next day.
3424 $date->modify('-1 second');
3425 $tend = $date->getTimestamp();
3427 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3428 // If parameter is true, return null.
3429 if ($param === true) {
3430 return null;
3433 // If parameter is false, return an empty array.
3434 if ($param === false) {
3435 return [];
3438 // If the parameter is a scalar value, enclose it in an array.
3439 if (!is_array($param)) {
3440 return [$param];
3443 // No normalisation required.
3444 return $param;
3445 }, [$calendar->users, $calendar->groups, $calendar->courses, $calendar->categories]);
3447 if ($skipevents) {
3448 $events = [];
3449 } else {
3450 $events = \core_calendar\local\api::get_events(
3451 $tstart,
3452 $tend,
3453 null,
3454 null,
3455 null,
3456 null,
3457 $eventlimit,
3458 null,
3459 $userparam,
3460 $groupparam,
3461 $courseparam,
3462 $categoryparam,
3463 true,
3464 true,
3465 function ($event) {
3466 if ($proxy = $event->get_course_module()) {
3467 $cminfo = $proxy->get_proxied_instance();
3468 return $cminfo->uservisible;
3471 if ($proxy = $event->get_category()) {
3472 $category = $proxy->get_proxied_instance();
3474 return $category->is_uservisible();
3477 return true;
3482 $related = [
3483 'events' => $events,
3484 'cache' => new \core_calendar\external\events_related_objects_cache($events),
3485 'type' => $type,
3488 $data = [];
3489 if ($view == "month" || $view == "mini" || $view == "minithree") {
3490 $month = new \core_calendar\external\month_exporter($calendar, $type, $related);
3491 $month->set_includenavigation($includenavigation);
3492 $month->set_initialeventsloaded(!$skipevents);
3493 $data = $month->export($renderer);
3494 } else if ($view == "day") {
3495 $day = new \core_calendar\external\calendar_day_exporter($calendar, $related);
3496 $data = $day->export($renderer);
3497 $template = 'core_calendar/calendar_day';
3498 } else if ($view == "upcoming" || $view == "upcoming_mini") {
3499 $upcoming = new \core_calendar\external\calendar_upcoming_exporter($calendar, $related);
3500 $data = $upcoming->export($renderer);
3502 if ($view == "upcoming") {
3503 $template = 'core_calendar/calendar_upcoming';
3504 } else if ($view == "upcoming_mini") {
3505 $template = 'core_calendar/calendar_upcoming_mini';
3509 return [$data, $template];
3513 * Request and render event form fragment.
3515 * @param array $args The fragment arguments.
3516 * @return string The rendered mform fragment.
3518 function calendar_output_fragment_event_form($args) {
3519 global $CFG, $OUTPUT, $USER;
3521 $html = '';
3522 $data = [];
3523 $eventid = isset($args['eventid']) ? clean_param($args['eventid'], PARAM_INT) : null;
3524 $starttime = isset($args['starttime']) ? clean_param($args['starttime'], PARAM_INT) : null;
3525 $courseid = isset($args['courseid']) ? clean_param($args['courseid'], PARAM_INT) : null;
3526 $categoryid = isset($args['categoryid']) ? clean_param($args['categoryid'], PARAM_INT) : null;
3527 $event = null;
3528 $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
3529 $context = \context_user::instance($USER->id);
3530 $editoroptions = \core_calendar\local\event\forms\create::build_editor_options($context);
3531 $formoptions = ['editoroptions' => $editoroptions];
3532 $draftitemid = 0;
3534 if ($hasformdata) {
3535 parse_str(clean_param($args['formdata'], PARAM_TEXT), $data);
3536 if (isset($data['description']['itemid'])) {
3537 $draftitemid = $data['description']['itemid'];
3541 if ($starttime) {
3542 $formoptions['starttime'] = $starttime;
3545 if (is_null($eventid)) {
3546 $mform = new \core_calendar\local\event\forms\create(
3547 null,
3548 $formoptions,
3549 'post',
3551 null,
3552 true,
3553 $data
3556 // Let's check first which event types user can add.
3557 calendar_get_allowed_types($allowed, $courseid);
3559 // If the user is on course context and is allowed to add course events set the event type default to course.
3560 if ($courseid != SITEID && !empty($allowed->courses)) {
3561 $data['eventtype'] = 'course';
3562 $data['courseid'] = $courseid;
3563 $data['groupcourseid'] = $courseid;
3564 } else if (!empty($categoryid) && !empty($allowed->category)) {
3565 $data['eventtype'] = 'category';
3566 $data['categoryid'] = $categoryid;
3568 $mform->set_data($data);
3569 } else {
3570 $event = calendar_event::load($eventid);
3571 $mapper = new \core_calendar\local\event\mappers\create_update_form_mapper();
3572 $eventdata = $mapper->from_legacy_event_to_data($event);
3573 $data = array_merge((array) $eventdata, $data);
3574 $event->count_repeats();
3575 $formoptions['event'] = $event;
3576 $data['description']['text'] = file_prepare_draft_area(
3577 $draftitemid,
3578 $event->context->id,
3579 'calendar',
3580 'event_description',
3581 $event->id,
3582 null,
3583 $data['description']['text']
3585 $data['description']['itemid'] = $draftitemid;
3587 $mform = new \core_calendar\local\event\forms\update(
3588 null,
3589 $formoptions,
3590 'post',
3592 null,
3593 true,
3594 $data
3596 $mform->set_data($data);
3598 // Check to see if this event is part of a subscription or import.
3599 // If so display a warning on edit.
3600 if (isset($event->subscriptionid) && ($event->subscriptionid != null)) {
3601 $renderable = new \core\output\notification(
3602 get_string('eventsubscriptioneditwarning', 'calendar'),
3603 \core\output\notification::NOTIFY_INFO
3606 $html .= $OUTPUT->render($renderable);
3610 if ($hasformdata) {
3611 $mform->is_validated();
3614 $html .= $mform->render();
3615 return $html;
3619 * Calculate the timestamp from the supplied Gregorian Year, Month, and Day.
3621 * @param int $d The day
3622 * @param int $m The month
3623 * @param int $y The year
3624 * @param int $time The timestamp to use instead of a separate y/m/d.
3625 * @return int The timestamp
3627 function calendar_get_timestamp($d, $m, $y, $time = 0) {
3628 // If a day, month and year were passed then convert it to a timestamp. If these were passed
3629 // then we can assume the day, month and year are passed as Gregorian, as no where in core
3630 // should we be passing these values rather than the time.
3631 if (!empty($d) && !empty($m) && !empty($y)) {
3632 if (checkdate($m, $d, $y)) {
3633 $time = make_timestamp($y, $m, $d);
3634 } else {
3635 $time = time();
3637 } else if (empty($time)) {
3638 $time = time();
3641 return $time;
3645 * Get the calendar footer options.
3647 * @param calendar_information $calendar The calendar information object.
3648 * @return array The data for template and template name.
3650 function calendar_get_footer_options($calendar) {
3651 global $CFG, $USER, $DB, $PAGE;
3653 // Generate hash for iCal link.
3654 $rawhash = $USER->id . $DB->get_field('user', 'password', ['id' => $USER->id]) . $CFG->calendar_exportsalt;
3655 $authtoken = sha1($rawhash);
3657 $renderer = $PAGE->get_renderer('core_calendar');
3658 $footer = new \core_calendar\external\footer_options_exporter($calendar, $USER->id, $authtoken);
3659 $data = $footer->export($renderer);
3660 $template = 'core_calendar/footer_options';
3662 return [$data, $template];
3666 * Get the list of potential calendar filter types as a type => name
3667 * combination.
3669 * @return array
3671 function calendar_get_filter_types() {
3672 $types = [
3673 'site',
3674 'category',
3675 'course',
3676 'group',
3677 'user',
3680 return array_map(function($type) {
3681 return [
3682 'eventtype' => $type,
3683 'name' => get_string("eventtype{$type}", "calendar"),
3685 }, $types);
3689 * Check whether the specified event type is valid.
3691 * @param string $type
3692 * @return bool
3694 function calendar_is_valid_eventtype($type) {
3695 $validtypes = [
3696 'user',
3697 'group',
3698 'course',
3699 'category',
3700 'site',
3702 return in_array($type, $validtypes);