Merge branch 'MDL-60301-master' of git://github.com/ankitagarwal/moodle
[moodle.git] / calendar / lib.php
blobb54328c44fb78a71634d386e033b704ec51834b3
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Calendar extension
20 * @package core_calendar
21 * @copyright 2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
22 * Avgoustos Tsinakos
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 if (!defined('MOODLE_INTERNAL')) {
27 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
30 require_once($CFG->libdir . '/coursecatlib.php');
32 /**
33 * These are read by the administration component to provide default values
36 /**
37 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
39 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
41 /**
42 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
44 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
46 /**
47 * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
49 define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
51 // This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
52 // Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
54 /**
55 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
57 define('CALENDAR_DEFAULT_WEEKEND', 65);
59 /**
60 * CALENDAR_URL - path to calendar's folder
62 define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
64 /**
65 * CALENDAR_TF_24 - Calendar time in 24 hours format
67 define('CALENDAR_TF_24', '%H:%M');
69 /**
70 * CALENDAR_TF_12 - Calendar time in 12 hours format
72 define('CALENDAR_TF_12', '%I:%M %p');
74 /**
75 * CALENDAR_EVENT_GLOBAL - Global calendar event types
77 define('CALENDAR_EVENT_GLOBAL', 1);
79 /**
80 * CALENDAR_EVENT_COURSE - Course calendar event types
82 define('CALENDAR_EVENT_COURSE', 2);
84 /**
85 * CALENDAR_EVENT_GROUP - group calendar event types
87 define('CALENDAR_EVENT_GROUP', 4);
89 /**
90 * CALENDAR_EVENT_USER - user calendar event types
92 define('CALENDAR_EVENT_USER', 8);
94 /**
95 * CALENDAR_EVENT_COURSECAT - Course category calendar event types
97 define('CALENDAR_EVENT_COURSECAT', 16);
99 /**
100 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
102 define('CALENDAR_IMPORT_FROM_FILE', 0);
105 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
107 define('CALENDAR_IMPORT_FROM_URL', 1);
110 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
112 define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
115 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
117 define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
120 * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
122 define('CALENDAR_SUBSCRIPTION_UPDATE', 1);
125 * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
127 define('CALENDAR_SUBSCRIPTION_REMOVE', 2);
130 * CALENDAR_EVENT_USER_OVERRIDE_PRIORITY - Constant for the user override priority.
132 define('CALENDAR_EVENT_USER_OVERRIDE_PRIORITY', 0);
135 * CALENDAR_EVENT_TYPE_STANDARD - Standard events.
137 define('CALENDAR_EVENT_TYPE_STANDARD', 0);
140 * CALENDAR_EVENT_TYPE_ACTION - Action events.
142 define('CALENDAR_EVENT_TYPE_ACTION', 1);
145 * Manage calendar events.
147 * This class provides the required functionality in order to manage calendar events.
148 * It was introduced as part of Moodle 2.0 and was created in order to provide a
149 * better framework for dealing with calendar events in particular regard to file
150 * handling through the new file API.
152 * @package core_calendar
153 * @category calendar
154 * @copyright 2009 Sam Hemelryk
155 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
157 * @property int $id The id within the event table
158 * @property string $name The name of the event
159 * @property string $description The description of the event
160 * @property int $format The format of the description FORMAT_?
161 * @property int $courseid The course the event is associated with (0 if none)
162 * @property int $groupid The group the event is associated with (0 if none)
163 * @property int $userid The user the event is associated with (0 if none)
164 * @property int $repeatid If this is a repeated event this will be set to the
165 * id of the original
166 * @property string $modulename If added by a module this will be the module name
167 * @property int $instance If added by a module this will be the module instance
168 * @property string $eventtype The event type
169 * @property int $timestart The start time as a timestamp
170 * @property int $timeduration The duration of the event in seconds
171 * @property int $visible 1 if the event is visible
172 * @property int $uuid ?
173 * @property int $sequence ?
174 * @property int $timemodified The time last modified as a timestamp
176 class calendar_event {
178 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
179 protected $properties = null;
181 /** @var string The converted event discription with file paths resolved.
182 * This gets populated when someone requests description for the first time */
183 protected $_description = null;
185 /** @var array The options to use with this description editor */
186 protected $editoroptions = array(
187 'subdirs' => false,
188 'forcehttps' => false,
189 'maxfiles' => -1,
190 'maxbytes' => null,
191 'trusttext' => false);
193 /** @var object The context to use with the description editor */
194 protected $editorcontext = null;
197 * Instantiates a new event and optionally populates its properties with the data provided.
199 * @param \stdClass $data Optional. An object containing the properties to for
200 * an event
202 public function __construct($data = null) {
203 global $CFG, $USER;
205 // First convert to object if it is not already (should either be object or assoc array).
206 if (!is_object($data)) {
207 $data = (object) $data;
210 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
212 $data->eventrepeats = 0;
214 if (empty($data->id)) {
215 $data->id = null;
218 if (!empty($data->subscriptionid)) {
219 $data->subscription = calendar_get_subscription($data->subscriptionid);
222 // Default to a user event.
223 if (empty($data->eventtype)) {
224 $data->eventtype = 'user';
227 // Default to the current user.
228 if (empty($data->userid)) {
229 $data->userid = $USER->id;
232 if (!empty($data->timeduration) && is_array($data->timeduration)) {
233 $data->timeduration = make_timestamp(
234 $data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'],
235 $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
238 if (!empty($data->description) && is_array($data->description)) {
239 $data->format = $data->description['format'];
240 $data->description = $data->description['text'];
241 } else if (empty($data->description)) {
242 $data->description = '';
243 $data->format = editors_get_preferred_format();
246 // Ensure form is defaulted correctly.
247 if (empty($data->format)) {
248 $data->format = editors_get_preferred_format();
251 $this->properties = $data;
253 if (empty($data->context)) {
254 $this->properties->context = $this->calculate_context();
259 * Magic set method.
261 * Attempts to call a set_$key method if one exists otherwise falls back
262 * to simply set the property.
264 * @param string $key property name
265 * @param mixed $value value of the property
267 public function __set($key, $value) {
268 if (method_exists($this, 'set_'.$key)) {
269 $this->{'set_'.$key}($value);
271 $this->properties->{$key} = $value;
275 * Magic get method.
277 * Attempts to call a get_$key method to return the property and ralls over
278 * to return the raw property.
280 * @param string $key property name
281 * @return mixed property value
282 * @throws \coding_exception
284 public function __get($key) {
285 if (method_exists($this, 'get_'.$key)) {
286 return $this->{'get_'.$key}();
288 if (!property_exists($this->properties, $key)) {
289 throw new \coding_exception('Undefined property requested');
291 return $this->properties->{$key};
295 * Magic isset method.
297 * PHP needs an isset magic method if you use the get magic method and
298 * still want empty calls to work.
300 * @param string $key $key property name
301 * @return bool|mixed property value, false if property is not exist
303 public function __isset($key) {
304 return !empty($this->properties->{$key});
308 * Calculate the context value needed for an event.
310 * Event's type can be determine by the available value store in $data
311 * It is important to check for the existence of course/courseid to determine
312 * the course event.
313 * Default value is set to CONTEXT_USER
315 * @return \stdClass The context object.
317 protected function calculate_context() {
318 global $USER, $DB;
320 $context = null;
321 if (isset($this->properties->categoryid) && $this->properties->categoryid > 0) {
322 $context = \context_coursecat::instance($this->properties->categoryid);
323 } else if (isset($this->properties->courseid) && $this->properties->courseid > 0) {
324 $context = \context_course::instance($this->properties->courseid);
325 } else if (isset($this->properties->course) && $this->properties->course > 0) {
326 $context = \context_course::instance($this->properties->course);
327 } else if (isset($this->properties->groupid) && $this->properties->groupid > 0) {
328 $group = $DB->get_record('groups', array('id' => $this->properties->groupid));
329 $context = \context_course::instance($group->courseid);
330 } else if (isset($this->properties->userid) && $this->properties->userid > 0
331 && $this->properties->userid == $USER->id) {
332 $context = \context_user::instance($this->properties->userid);
333 } else if (isset($this->properties->userid) && $this->properties->userid > 0
334 && $this->properties->userid != $USER->id &&
335 isset($this->properties->instance) && $this->properties->instance > 0) {
336 $cm = get_coursemodule_from_instance($this->properties->modulename, $this->properties->instance, 0,
337 false, MUST_EXIST);
338 $context = \context_course::instance($cm->course);
339 } else {
340 $context = \context_user::instance($this->properties->userid);
343 return $context;
347 * Returns an array of editoroptions for this event.
349 * @return array event editor options
351 protected function get_editoroptions() {
352 return $this->editoroptions;
356 * Returns an event description: Called by __get
357 * Please use $blah = $event->description;
359 * @return string event description
361 protected function get_description() {
362 global $CFG;
364 require_once($CFG->libdir . '/filelib.php');
366 if ($this->_description === null) {
367 // Check if we have already resolved the context for this event.
368 if ($this->editorcontext === null) {
369 // Switch on the event type to decide upon the appropriate context to use for this event.
370 $this->editorcontext = $this->properties->context;
371 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
372 return clean_text($this->properties->description, $this->properties->format);
376 // Work out the item id for the editor, if this is a repeated event
377 // then the files will be associated with the original.
378 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
379 $itemid = $this->properties->repeatid;
380 } else {
381 $itemid = $this->properties->id;
384 // Convert file paths in the description so that things display correctly.
385 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php',
386 $this->editorcontext->id, 'calendar', 'event_description', $itemid);
387 // Clean the text so no nasties get through.
388 $this->_description = clean_text($this->_description, $this->properties->format);
391 // Finally return the description.
392 return $this->_description;
396 * Return the number of repeat events there are in this events series.
398 * @return int number of event repeated
400 public function count_repeats() {
401 global $DB;
402 if (!empty($this->properties->repeatid)) {
403 $this->properties->eventrepeats = $DB->count_records('event',
404 array('repeatid' => $this->properties->repeatid));
405 // We don't want to count ourselves.
406 $this->properties->eventrepeats--;
408 return $this->properties->eventrepeats;
412 * Update or create an event within the database
414 * Pass in a object containing the event properties and this function will
415 * insert it into the database and deal with any associated files
417 * @see self::create()
418 * @see self::update()
420 * @param \stdClass $data object of event
421 * @param bool $checkcapability if moodle should check calendar managing capability or not
422 * @return bool event updated
424 public function update($data, $checkcapability=true) {
425 global $DB, $USER;
427 foreach ($data as $key => $value) {
428 $this->properties->$key = $value;
431 $this->properties->timemodified = time();
432 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
434 // Prepare event data.
435 $eventargs = array(
436 'context' => $this->properties->context,
437 'objectid' => $this->properties->id,
438 'other' => array(
439 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
440 'timestart' => $this->properties->timestart,
441 'name' => $this->properties->name
445 if (empty($this->properties->id) || $this->properties->id < 1) {
447 if ($checkcapability) {
448 if (!calendar_add_event_allowed($this->properties)) {
449 print_error('nopermissiontoupdatecalendar');
453 if ($usingeditor) {
454 switch ($this->properties->eventtype) {
455 case 'user':
456 $this->properties->courseid = 0;
457 $this->properties->course = 0;
458 $this->properties->groupid = 0;
459 $this->properties->userid = $USER->id;
460 break;
461 case 'site':
462 $this->properties->courseid = SITEID;
463 $this->properties->course = SITEID;
464 $this->properties->groupid = 0;
465 $this->properties->userid = $USER->id;
466 break;
467 case 'course':
468 $this->properties->groupid = 0;
469 $this->properties->userid = $USER->id;
470 break;
471 case 'category':
472 $this->properties->groupid = 0;
473 $this->properties->category = 0;
474 $this->properties->userid = $USER->id;
475 break;
476 case 'group':
477 $this->properties->userid = $USER->id;
478 break;
479 default:
480 // We should NEVER get here, but just incase we do lets fail gracefully.
481 $usingeditor = false;
482 break;
485 // If we are actually using the editor, we recalculate the context because some default values
486 // were set when calculate_context() was called from the constructor.
487 if ($usingeditor) {
488 $this->properties->context = $this->calculate_context();
489 $this->editorcontext = $this->properties->context;
492 $editor = $this->properties->description;
493 $this->properties->format = $this->properties->description['format'];
494 $this->properties->description = $this->properties->description['text'];
497 // Insert the event into the database.
498 $this->properties->id = $DB->insert_record('event', $this->properties);
500 if ($usingeditor) {
501 $this->properties->description = file_save_draft_area_files(
502 $editor['itemid'],
503 $this->editorcontext->id,
504 'calendar',
505 'event_description',
506 $this->properties->id,
507 $this->editoroptions,
508 $editor['text'],
509 $this->editoroptions['forcehttps']);
510 $DB->set_field('event', 'description', $this->properties->description,
511 array('id' => $this->properties->id));
514 // Log the event entry.
515 $eventargs['objectid'] = $this->properties->id;
516 $eventargs['context'] = $this->properties->context;
517 $event = \core\event\calendar_event_created::create($eventargs);
518 $event->trigger();
520 $repeatedids = array();
522 if (!empty($this->properties->repeat)) {
523 $this->properties->repeatid = $this->properties->id;
524 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id' => $this->properties->id));
526 $eventcopy = clone($this->properties);
527 unset($eventcopy->id);
529 $timestart = new \DateTime('@' . $eventcopy->timestart);
530 $timestart->setTimezone(\core_date::get_user_timezone_object());
532 for ($i = 1; $i < $eventcopy->repeats; $i++) {
534 $timestart->add(new \DateInterval('P7D'));
535 $eventcopy->timestart = $timestart->getTimestamp();
537 // Get the event id for the log record.
538 $eventcopyid = $DB->insert_record('event', $eventcopy);
540 // If the context has been set delete all associated files.
541 if ($usingeditor) {
542 $fs = get_file_storage();
543 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description',
544 $this->properties->id);
545 foreach ($files as $file) {
546 $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
550 $repeatedids[] = $eventcopyid;
552 // Trigger an event.
553 $eventargs['objectid'] = $eventcopyid;
554 $eventargs['other']['timestart'] = $eventcopy->timestart;
555 $event = \core\event\calendar_event_created::create($eventargs);
556 $event->trigger();
560 return true;
561 } else {
563 if ($checkcapability) {
564 if (!calendar_edit_event_allowed($this->properties)) {
565 print_error('nopermissiontoupdatecalendar');
569 if ($usingeditor) {
570 if ($this->editorcontext !== null) {
571 $this->properties->description = file_save_draft_area_files(
572 $this->properties->description['itemid'],
573 $this->editorcontext->id,
574 'calendar',
575 'event_description',
576 $this->properties->id,
577 $this->editoroptions,
578 $this->properties->description['text'],
579 $this->editoroptions['forcehttps']);
580 } else {
581 $this->properties->format = $this->properties->description['format'];
582 $this->properties->description = $this->properties->description['text'];
586 $event = $DB->get_record('event', array('id' => $this->properties->id));
588 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
590 if ($updaterepeated) {
591 // Update all.
592 if ($this->properties->timestart != $event->timestart) {
593 $timestartoffset = $this->properties->timestart - $event->timestart;
594 $sql = "UPDATE {event}
595 SET name = ?,
596 description = ?,
597 timestart = timestart + ?,
598 timeduration = ?,
599 timemodified = ?
600 WHERE repeatid = ?";
601 $params = array($this->properties->name, $this->properties->description, $timestartoffset,
602 $this->properties->timeduration, time(), $event->repeatid);
603 } else {
604 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
605 $params = array($this->properties->name, $this->properties->description,
606 $this->properties->timeduration, time(), $event->repeatid);
608 $DB->execute($sql, $params);
610 // Trigger an update event for each of the calendar event.
611 $events = $DB->get_records('event', array('repeatid' => $event->repeatid), '', '*');
612 foreach ($events as $calendarevent) {
613 $eventargs['objectid'] = $calendarevent->id;
614 $eventargs['other']['timestart'] = $calendarevent->timestart;
615 $event = \core\event\calendar_event_updated::create($eventargs);
616 $event->add_record_snapshot('event', $calendarevent);
617 $event->trigger();
619 } else {
620 $DB->update_record('event', $this->properties);
621 $event = self::load($this->properties->id);
622 $this->properties = $event->properties();
624 // Trigger an update event.
625 $event = \core\event\calendar_event_updated::create($eventargs);
626 $event->add_record_snapshot('event', $this->properties);
627 $event->trigger();
630 return true;
635 * Deletes an event and if selected an repeated events in the same series
637 * This function deletes an event, any associated events if $deleterepeated=true,
638 * and cleans up any files associated with the events.
640 * @see self::delete()
642 * @param bool $deleterepeated delete event repeatedly
643 * @return bool succession of deleting event
645 public function delete($deleterepeated = false) {
646 global $DB;
648 // If $this->properties->id is not set then something is wrong.
649 if (empty($this->properties->id)) {
650 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
651 return false;
653 $calevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
654 // Delete the event.
655 $DB->delete_records('event', array('id' => $this->properties->id));
657 // Trigger an event for the delete action.
658 $eventargs = array(
659 'context' => $this->properties->context,
660 'objectid' => $this->properties->id,
661 'other' => array(
662 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
663 'timestart' => $this->properties->timestart,
664 'name' => $this->properties->name
666 $event = \core\event\calendar_event_deleted::create($eventargs);
667 $event->add_record_snapshot('event', $calevent);
668 $event->trigger();
670 // If we are deleting parent of a repeated event series, promote the next event in the series as parent.
671 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
672 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC",
673 array($this->properties->id), IGNORE_MULTIPLE);
674 if (!empty($newparent)) {
675 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?",
676 array($newparent, $this->properties->id));
677 // Get all records where the repeatid is the same as the event being removed.
678 $events = $DB->get_records('event', array('repeatid' => $newparent));
679 // For each of the returned events trigger an update event.
680 foreach ($events as $calendarevent) {
681 // Trigger an event for the update.
682 $eventargs['objectid'] = $calendarevent->id;
683 $eventargs['other']['timestart'] = $calendarevent->timestart;
684 $event = \core\event\calendar_event_updated::create($eventargs);
685 $event->add_record_snapshot('event', $calendarevent);
686 $event->trigger();
691 // If the editor context hasn't already been set then set it now.
692 if ($this->editorcontext === null) {
693 $this->editorcontext = $this->properties->context;
696 // If the context has been set delete all associated files.
697 if ($this->editorcontext !== null) {
698 $fs = get_file_storage();
699 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
700 foreach ($files as $file) {
701 $file->delete();
705 // If we need to delete repeated events then we will fetch them all and delete one by one.
706 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
707 // Get all records where the repeatid is the same as the event being removed.
708 $events = $DB->get_records('event', array('repeatid' => $this->properties->repeatid));
709 // For each of the returned events populate an event object and call delete.
710 // make sure the arg passed is false as we are already deleting all repeats.
711 foreach ($events as $event) {
712 $event = new calendar_event($event);
713 $event->delete(false);
717 return true;
721 * Fetch all event properties.
723 * This function returns all of the events properties as an object and optionally
724 * can prepare an editor for the description field at the same time. This is
725 * designed to work when the properties are going to be used to set the default
726 * values of a moodle forms form.
728 * @param bool $prepareeditor If set to true a editor is prepared for use with
729 * the mforms editor element. (for description)
730 * @return \stdClass Object containing event properties
732 public function properties($prepareeditor = false) {
733 global $DB;
735 // First take a copy of the properties. We don't want to actually change the
736 // properties or we'd forever be converting back and forwards between an
737 // editor formatted description and not.
738 $properties = clone($this->properties);
739 // Clean the description here.
740 $properties->description = clean_text($properties->description, $properties->format);
742 // If set to true we need to prepare the properties for use with an editor
743 // and prepare the file area.
744 if ($prepareeditor) {
746 // We may or may not have a property id. If we do then we need to work
747 // out the context so we can copy the existing files to the draft area.
748 if (!empty($properties->id)) {
750 if ($properties->eventtype === 'site') {
751 // Site context.
752 $this->editorcontext = $this->properties->context;
753 } else if ($properties->eventtype === 'user') {
754 // User context.
755 $this->editorcontext = $this->properties->context;
756 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
757 // First check the course is valid.
758 $course = $DB->get_record('course', array('id' => $properties->courseid));
759 if (!$course) {
760 print_error('invalidcourse');
762 // Course context.
763 $this->editorcontext = $this->properties->context;
764 // We have a course and are within the course context so we had
765 // better use the courses max bytes value.
766 $this->editoroptions['maxbytes'] = $course->maxbytes;
767 } else if ($properties->eventtype === 'category') {
768 // First check the course is valid.
769 \coursecat::get($properties->categoryid, MUST_EXIST, true);
770 // Course context.
771 $this->editorcontext = $this->properties->context;
772 // We have a course and are within the course context so we had
773 // better use the courses max bytes value.
774 $this->editoroptions['maxbytes'] = $course->maxbytes;
775 } else {
776 // If we get here we have a custom event type as used by some
777 // modules. In this case the event will have been added by
778 // code and we won't need the editor.
779 $this->editoroptions['maxbytes'] = 0;
780 $this->editoroptions['maxfiles'] = 0;
783 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
784 $contextid = false;
785 } else {
786 // Get the context id that is what we really want.
787 $contextid = $this->editorcontext->id;
789 } else {
791 // If we get here then this is a new event in which case we don't need a
792 // context as there is no existing files to copy to the draft area.
793 $contextid = null;
796 // If the contextid === false we don't support files so no preparing
797 // a draft area.
798 if ($contextid !== false) {
799 // Just encase it has already been submitted.
800 $draftiddescription = file_get_submitted_draft_itemid('description');
801 // Prepare the draft area, this copies existing files to the draft area as well.
802 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar',
803 'event_description', $properties->id, $this->editoroptions, $properties->description);
804 } else {
805 $draftiddescription = 0;
808 // Structure the description field as the editor requires.
809 $properties->description = array('text' => $properties->description, 'format' => $properties->format,
810 'itemid' => $draftiddescription);
813 // Finally return the properties.
814 return $properties;
818 * Toggles the visibility of an event
820 * @param null|bool $force If it is left null the events visibility is flipped,
821 * If it is false the event is made hidden, if it is true it
822 * is made visible.
823 * @return bool if event is successfully updated, toggle will be visible
825 public function toggle_visibility($force = null) {
826 global $DB;
828 // Set visible to the default if it is not already set.
829 if (empty($this->properties->visible)) {
830 $this->properties->visible = 1;
833 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
834 // Make this event visible.
835 $this->properties->visible = 1;
836 } else {
837 // Make this event hidden.
838 $this->properties->visible = 0;
841 // Update the database to reflect this change.
842 $success = $DB->set_field('event', 'visible', $this->properties->visible, array('id' => $this->properties->id));
843 $calendarevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
845 // Prepare event data.
846 $eventargs = array(
847 'context' => $this->properties->context,
848 'objectid' => $this->properties->id,
849 'other' => array(
850 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
851 'timestart' => $this->properties->timestart,
852 'name' => $this->properties->name
855 $event = \core\event\calendar_event_updated::create($eventargs);
856 $event->add_record_snapshot('event', $calendarevent);
857 $event->trigger();
859 return $success;
863 * Returns an event object when provided with an event id.
865 * This function makes use of MUST_EXIST, if the event id passed in is invalid
866 * it will result in an exception being thrown.
868 * @param int|object $param event object or event id
869 * @return calendar_event
871 public static function load($param) {
872 global $DB;
873 if (is_object($param)) {
874 $event = new calendar_event($param);
875 } else {
876 $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST);
877 $event = new calendar_event($event);
879 return $event;
883 * Creates a new event and returns an event object
885 * @param \stdClass|array $properties An object containing event properties
886 * @param bool $checkcapability Check caps or not
887 * @throws \coding_exception
889 * @return calendar_event|bool The event object or false if it failed
891 public static function create($properties, $checkcapability = true) {
892 if (is_array($properties)) {
893 $properties = (object)$properties;
895 if (!is_object($properties)) {
896 throw new \coding_exception('When creating an event properties should be either an object or an assoc array');
898 $event = new calendar_event($properties);
899 if ($event->update($properties, $checkcapability)) {
900 return $event;
901 } else {
902 return false;
907 * Format the text using the external API.
909 * This function should we used when text formatting is required in external functions.
911 * @return array an array containing the text formatted and the text format
913 public function format_external_text() {
915 if ($this->editorcontext === null) {
916 // Switch on the event type to decide upon the appropriate context to use for this event.
917 $this->editorcontext = $this->properties->context;
919 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
920 // We don't have a context here, do a normal format_text.
921 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id);
925 // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
926 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
927 $itemid = $this->properties->repeatid;
928 } else {
929 $itemid = $this->properties->id;
932 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id,
933 'calendar', 'event_description', $itemid);
938 * Calendar information class
940 * This class is used simply to organise the information pertaining to a calendar
941 * and is used primarily to make information easily available.
943 * @package core_calendar
944 * @category calendar
945 * @copyright 2010 Sam Hemelryk
946 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
948 class calendar_information {
951 * @var int The timestamp
953 * Rather than setting the day, month and year we will set a timestamp which will be able
954 * to be used by multiple calendars.
956 public $time;
958 /** @var int A course id */
959 public $courseid = null;
961 /** @var array An array of categories */
962 public $categories = array();
964 /** @var int The current category */
965 public $categoryid = null;
967 /** @var array An array of courses */
968 public $courses = array();
970 /** @var array An array of groups */
971 public $groups = array();
973 /** @var array An array of users */
974 public $users = array();
977 * Creates a new instance
979 * @param int $day the number of the day
980 * @param int $month the number of the month
981 * @param int $year the number of the year
982 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
983 * and $calyear to support multiple calendars
985 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
986 // If a day, month and year were passed then convert it to a timestamp. If these were passed
987 // then we can assume the day, month and year are passed as Gregorian, as no where in core
988 // should we be passing these values rather than the time. This is done for BC.
989 if (!empty($day) || !empty($month) || !empty($year)) {
990 $date = usergetdate(time());
991 if (empty($day)) {
992 $day = $date['mday'];
994 if (empty($month)) {
995 $month = $date['mon'];
997 if (empty($year)) {
998 $year = $date['year'];
1000 if (checkdate($month, $day, $year)) {
1001 $time = make_timestamp($year, $month, $day);
1002 } else {
1003 $time = time();
1007 $this->set_time($time);
1011 * Set the time period of this instance.
1013 * @param int $time the unixtimestamp representing the date we want to view.
1014 * @return $this
1016 public function set_time($time = null) {
1017 if (empty($time)) {
1018 $this->time = time();
1019 } else {
1020 $this->time = $time;
1023 return $this;
1027 * Initialize calendar information
1029 * @deprecated 3.4
1030 * @param stdClass $course object
1031 * @param array $coursestoload An array of courses [$course->id => $course]
1032 * @param bool $ignorefilters options to use filter
1034 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
1035 debugging('The prepare_for_view() function has been deprecated. Please update your code to use set_sources()',
1036 DEBUG_DEVELOPER);
1037 $this->set_sources($course, $coursestoload);
1041 * Set the sources for events within the calendar.
1043 * If no category is provided, then the category path for the current
1044 * course will be used.
1046 * @param stdClass $course The current course being viewed.
1047 * @param int[] $courses The list of all courses currently accessible.
1048 * @param stdClass $category The current category to show.
1050 public function set_sources(stdClass $course, array $courses, stdClass $category = null) {
1051 // A cousre must always be specified.
1052 $this->course = $course;
1053 $this->courseid = $course->id;
1055 list($courseids, $group, $user) = calendar_set_filters($courses);
1056 $this->courses = $courseids;
1057 $this->groups = $group;
1058 $this->users = $user;
1060 // Do not show category events by default.
1061 $this->categoryid = null;
1062 $this->categories = null;
1064 if (null !== $category && $category->id > 0) {
1065 // A specific category was requested - set the current category, and include all parents of that category.
1066 $category = \coursecat::get($category->id);
1067 $this->categoryid = $category->id;
1069 $this->categories = $category->get_parents();
1070 $this->categories[] = $category->id;
1071 } else if (SITEID === $this->courseid) {
1072 // This is the site.
1073 // Show categories for all courses the user has access to.
1074 $this->categories = true;
1075 $categories = [];
1076 foreach ($courses as $course) {
1077 if ($category = \coursecat::get($course->category, IGNORE_MISSING)) {
1078 $categories = array_merge($categories, $category->get_parents());
1079 $categories[] = $category->id;
1083 // And all categories that the user can manage.
1084 foreach (\coursecat::get_all() as $category) {
1085 if (!$category->has_manage_capability()) {
1086 continue;
1089 $categories = array_merge($categories, $category->get_parents());
1090 $categories[] = $category->id;
1093 $this->categories = array_unique($categories);
1098 * Ensures the date for the calendar is correct and either sets it to now
1099 * or throws a moodle_exception if not
1101 * @param bool $defaultonow use current time
1102 * @throws moodle_exception
1103 * @return bool validation of checkdate
1105 public function checkdate($defaultonow = true) {
1106 if (!checkdate($this->month, $this->day, $this->year)) {
1107 if ($defaultonow) {
1108 $now = usergetdate(time());
1109 $this->day = intval($now['mday']);
1110 $this->month = intval($now['mon']);
1111 $this->year = intval($now['year']);
1112 return true;
1113 } else {
1114 throw new moodle_exception('invaliddate');
1117 return true;
1121 * Gets todays timestamp for the calendar
1123 * @return int today timestamp
1125 public function timestamp_today() {
1126 return $this->time;
1129 * Gets tomorrows timestamp for the calendar
1131 * @return int tomorrow timestamp
1133 public function timestamp_tomorrow() {
1134 return strtotime('+1 day', $this->time);
1137 * Adds the pretend blocks for the calendar
1139 * @param core_calendar_renderer $renderer
1140 * @param bool $showfilters display filters, false is set as default
1141 * @param string|null $view preference view options (eg: day, month, upcoming)
1143 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
1144 if ($showfilters) {
1145 $filters = new block_contents();
1146 $filters->content = $renderer->event_filter();
1147 $filters->footer = '';
1148 $filters->title = get_string('eventskey', 'calendar');
1149 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
1151 $block = new block_contents;
1152 $block->content = $renderer->fake_block_threemonths($this);
1153 $block->footer = '';
1154 $block->title = get_string('monthlyview', 'calendar');
1155 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
1160 * Get calendar events.
1162 * @param int $tstart Start time of time range for events
1163 * @param int $tend End time of time range for events
1164 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
1165 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
1166 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
1167 * @param boolean $withduration whether only events starting within time range selected
1168 * or events in progress/already started selected as well
1169 * @param boolean $ignorehidden whether to select only visible events or all events
1170 * @param array|int|boolean $categories array of categories, category id or boolean for all/no course events
1171 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
1173 function calendar_get_events($tstart, $tend, $users, $groups, $courses,
1174 $withduration = true, $ignorehidden = true, $categories = []) {
1175 global $DB;
1177 $whereclause = '';
1178 $params = array();
1179 // Quick test.
1180 if (empty($users) && empty($groups) && empty($courses) && empty($categories)) {
1181 return array();
1184 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
1185 // Events from a number of users
1186 if(!empty($whereclause)) $whereclause .= ' OR';
1187 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED);
1188 $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)";
1189 $params = array_merge($params, $inparamsusers);
1190 } else if($users === true) {
1191 // Events from ALL users
1192 if(!empty($whereclause)) $whereclause .= ' OR';
1193 $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)';
1194 } else if($users === false) {
1195 // No user at all, do nothing
1198 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
1199 // Events from a number of groups
1200 if(!empty($whereclause)) $whereclause .= ' OR';
1201 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED);
1202 $whereclause .= " e.groupid $insqlgroups ";
1203 $params = array_merge($params, $inparamsgroups);
1204 } else if($groups === true) {
1205 // Events from ALL groups
1206 if(!empty($whereclause)) $whereclause .= ' OR ';
1207 $whereclause .= ' e.groupid != 0';
1209 // boolean false (no groups at all): we don't need to do anything
1211 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
1212 if(!empty($whereclause)) $whereclause .= ' OR';
1213 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED);
1214 $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
1215 $params = array_merge($params, $inparamscourses);
1216 } else if ($courses === true) {
1217 // Events from ALL courses
1218 if(!empty($whereclause)) $whereclause .= ' OR';
1219 $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
1222 if ((is_array($categories) && !empty($categories)) || is_numeric($categories)) {
1223 if (!empty($whereclause)) {
1224 $whereclause .= ' OR';
1226 list($insqlcategories, $inparamscategories) = $DB->get_in_or_equal($categories, SQL_PARAMS_NAMED);
1227 $whereclause .= " (e.groupid = 0 AND e.courseid = 0 AND e.categoryid $insqlcategories)";
1228 $params = array_merge($params, $inparamscategories);
1229 } else if ($categories === true) {
1230 // Events from ALL categories.
1231 if (!empty($whereclause)) {
1232 $whereclause .= ' OR';
1234 $whereclause .= ' (e.groupid = 0 AND e.courseid = 0 AND e.categoryid != 0)';
1237 // Security check: if, by now, we have NOTHING in $whereclause, then it means
1238 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
1239 // events no matter what. Allowing the code to proceed might return a completely
1240 // valid query with only time constraints, thus selecting ALL events in that time frame!
1241 if(empty($whereclause)) {
1242 return array();
1245 if($withduration) {
1246 $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1248 else {
1249 $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1251 if(!empty($whereclause)) {
1252 // We have additional constraints
1253 $whereclause = $timeclause.' AND ('.$whereclause.')';
1255 else {
1256 // Just basic time filtering
1257 $whereclause = $timeclause;
1260 if ($ignorehidden) {
1261 $whereclause .= ' AND e.visible = 1';
1264 $sql = "SELECT e.*
1265 FROM {event} e
1266 LEFT JOIN {modules} m ON e.modulename = m.name
1267 -- Non visible modules will have a value of 0.
1268 WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
1269 ORDER BY e.timestart";
1270 $events = $DB->get_records_sql($sql, $params);
1272 if ($events === false) {
1273 $events = array();
1275 return $events;
1279 * Return the days of the week.
1281 * @return array array of days
1283 function calendar_get_days() {
1284 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1285 return $calendartype->get_weekdays();
1289 * Get the subscription from a given id.
1291 * @since Moodle 2.5
1292 * @param int $id id of the subscription
1293 * @return stdClass Subscription record from DB
1294 * @throws moodle_exception for an invalid id
1296 function calendar_get_subscription($id) {
1297 global $DB;
1299 $cache = \cache::make('core', 'calendar_subscriptions');
1300 $subscription = $cache->get($id);
1301 if (empty($subscription)) {
1302 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
1303 $cache->set($id, $subscription);
1306 return $subscription;
1310 * Gets the first day of the week.
1312 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
1314 * @return int
1316 function calendar_get_starting_weekday() {
1317 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1318 return $calendartype->get_starting_weekday();
1322 * Get a HTML link to a course.
1324 * @param int|stdClass $course the course id or course object
1325 * @return string a link to the course (as HTML); empty if the course id is invalid
1327 function calendar_get_courselink($course) {
1328 if (!$course) {
1329 return '';
1332 if (!is_object($course)) {
1333 $course = calendar_get_course_cached($coursecache, $course);
1335 $context = \context_course::instance($course->id);
1336 $fullname = format_string($course->fullname, true, array('context' => $context));
1337 $url = new \moodle_url('/course/view.php', array('id' => $course->id));
1338 $link = \html_writer::link($url, $fullname);
1340 return $link;
1344 * Get current module cache.
1346 * Only use this method if you do not know courseid. Otherwise use:
1347 * get_fast_modinfo($courseid)->instances[$modulename][$instance]
1349 * @param array $modulecache in memory module cache
1350 * @param string $modulename name of the module
1351 * @param int $instance module instance number
1352 * @return stdClass|bool $module information
1354 function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
1355 if (!isset($modulecache[$modulename . '_' . $instance])) {
1356 $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
1359 return $modulecache[$modulename . '_' . $instance];
1363 * Get current course cache.
1365 * @param array $coursecache list of course cache
1366 * @param int $courseid id of the course
1367 * @return stdClass $coursecache[$courseid] return the specific course cache
1369 function calendar_get_course_cached(&$coursecache, $courseid) {
1370 if (!isset($coursecache[$courseid])) {
1371 $coursecache[$courseid] = get_course($courseid);
1373 return $coursecache[$courseid];
1377 * Get group from groupid for calendar display
1379 * @param int $groupid
1380 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1382 function calendar_get_group_cached($groupid) {
1383 static $groupscache = array();
1384 if (!isset($groupscache[$groupid])) {
1385 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1387 return $groupscache[$groupid];
1391 * Add calendar event metadata
1393 * @param stdClass $event event info
1394 * @return stdClass $event metadata
1396 function calendar_add_event_metadata($event) {
1397 global $CFG, $OUTPUT;
1399 // Support multilang in event->name.
1400 $event->name = format_string($event->name, true);
1402 if (!empty($event->modulename)) { // Activity event.
1403 // The module name is set. I will assume that it has to be displayed, and
1404 // also that it is an automatically-generated event. And of course that the
1405 // instace id and modulename are set correctly.
1406 $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
1407 if (!array_key_exists($event->instance, $instances)) {
1408 return;
1410 $module = $instances[$event->instance];
1412 $modulename = $module->get_module_type_name(false);
1413 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
1414 // Will be used as alt text if the event icon.
1415 $eventtype = get_string($event->eventtype, $event->modulename);
1416 } else {
1417 $eventtype = '';
1420 $event->icon = '<img src="' . s($module->get_icon_url()) . '" alt="' . s($eventtype) .
1421 '" title="' . s($modulename) . '" class="icon" />';
1422 $event->referer = html_writer::link($module->url, $event->name);
1423 $event->courselink = calendar_get_courselink($module->get_course());
1424 $event->cmid = $module->id;
1425 } else if ($event->courseid == SITEID) { // Site event.
1426 $event->icon = '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
1427 get_string('globalevent', 'calendar') . '" class="icon" />';
1428 $event->cssclass = 'calendar_event_global';
1429 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event.
1430 $event->icon = '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
1431 get_string('courseevent', 'calendar') . '" class="icon" />';
1432 $event->courselink = calendar_get_courselink($event->courseid);
1433 $event->cssclass = 'calendar_event_course';
1434 } else if ($event->groupid) { // Group event.
1435 if ($group = calendar_get_group_cached($event->groupid)) {
1436 $groupname = format_string($group->name, true, \context_course::instance($group->courseid));
1437 } else {
1438 $groupname = '';
1440 $event->icon = \html_writer::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
1441 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
1442 $event->courselink = calendar_get_courselink($event->courseid) . ', ' . $groupname;
1443 $event->cssclass = 'calendar_event_group';
1444 } else if ($event->userid) { // User event.
1445 $event->icon = '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
1446 get_string('userevent', 'calendar') . '" class="icon" />';
1447 $event->cssclass = 'calendar_event_user';
1450 return $event;
1454 * Get calendar events by id.
1456 * @since Moodle 2.5
1457 * @param array $eventids list of event ids
1458 * @return array Array of event entries, empty array if nothing found
1460 function calendar_get_events_by_id($eventids) {
1461 global $DB;
1463 if (!is_array($eventids) || empty($eventids)) {
1464 return array();
1467 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
1468 $wheresql = "id $wheresql";
1470 return $DB->get_records_select('event', $wheresql, $params);
1474 * Get control options for calendar.
1476 * @param string $type of calendar
1477 * @param array $data calendar information
1478 * @return string $content return available control for the calender in html
1480 function calendar_top_controls($type, $data) {
1481 global $PAGE, $OUTPUT;
1483 // Get the calendar type we are using.
1484 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1486 $content = '';
1488 // Ensure course id passed if relevant.
1489 $courseid = '';
1490 if (!empty($data['id'])) {
1491 $courseid = '&amp;course=' . $data['id'];
1494 // If we are passing a month and year then we need to convert this to a timestamp to
1495 // support multiple calendars. No where in core should these be passed, this logic
1496 // here is for third party plugins that may use this function.
1497 if (!empty($data['m']) && !empty($date['y'])) {
1498 if (!isset($data['d'])) {
1499 $data['d'] = 1;
1501 if (!checkdate($data['m'], $data['d'], $data['y'])) {
1502 $time = time();
1503 } else {
1504 $time = make_timestamp($data['y'], $data['m'], $data['d']);
1506 } else if (!empty($data['time'])) {
1507 $time = $data['time'];
1508 } else {
1509 $time = time();
1512 // Get the date for the calendar type.
1513 $date = $calendartype->timestamp_to_date_array($time);
1515 $urlbase = $PAGE->url;
1517 // We need to get the previous and next months in certain cases.
1518 if ($type == 'frontpage' || $type == 'course' || $type == 'month') {
1519 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1520 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
1521 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
1522 $prevmonthtime['hour'], $prevmonthtime['minute']);
1524 $nextmonth = calendar_add_month($date['mon'], $date['year']);
1525 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
1526 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
1527 $nextmonthtime['hour'], $nextmonthtime['minute']);
1530 switch ($type) {
1531 case 'frontpage':
1532 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1533 true, $prevmonthtime);
1534 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true,
1535 $nextmonthtime);
1536 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1537 false, false, false, $time);
1539 if (!empty($data['id'])) {
1540 $calendarlink->param('course', $data['id']);
1543 $right = $nextlink;
1545 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1546 $content .= $prevlink . '<span class="hide"> | </span>';
1547 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1548 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1549 ), array('class' => 'current'));
1550 $content .= '<span class="hide"> | </span>' . $right;
1551 $content .= "<span class=\"clearer\"><!-- --></span>\n";
1552 $content .= \html_writer::end_tag('div');
1554 break;
1555 case 'course':
1556 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1557 true, $prevmonthtime);
1558 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false,
1559 true, $nextmonthtime);
1560 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1561 false, false, false, $time);
1563 if (!empty($data['id'])) {
1564 $calendarlink->param('course', $data['id']);
1567 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1568 $content .= $prevlink . '<span class="hide"> | </span>';
1569 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1570 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1571 ), array('class' => 'current'));
1572 $content .= '<span class="hide"> | </span>' . $nextlink;
1573 $content .= "<span class=\"clearer\"><!-- --></span>";
1574 $content .= \html_writer::end_tag('div');
1575 break;
1576 case 'upcoming':
1577 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'upcoming')),
1578 false, false, false, $time);
1579 if (!empty($data['id'])) {
1580 $calendarlink->param('course', $data['id']);
1582 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1583 $content .= \html_writer::tag('div', $calendarlink, array('class' => 'centered'));
1584 break;
1585 case 'display':
1586 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1587 false, false, false, $time);
1588 if (!empty($data['id'])) {
1589 $calendarlink->param('course', $data['id']);
1591 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1592 $content .= \html_writer::tag('h3', $calendarlink);
1593 break;
1594 case 'month':
1595 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1596 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $prevmonthtime);
1597 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1598 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $nextmonthtime);
1600 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1601 $content .= $prevlink . '<span class="hide"> | </span>';
1602 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1603 $content .= '<span class="hide"> | </span>' . $nextlink;
1604 $content .= '<span class="clearer"><!-- --></span>';
1605 $content .= \html_writer::end_tag('div')."\n";
1606 break;
1607 case 'day':
1608 $days = calendar_get_days();
1610 $prevtimestamp = strtotime('-1 day', $time);
1611 $nexttimestamp = strtotime('+1 day', $time);
1613 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1614 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1616 $prevname = $days[$prevdate['wday']]['fullname'];
1617 $nextname = $days[$nextdate['wday']]['fullname'];
1618 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&amp;', false, false,
1619 false, false, $prevtimestamp);
1620 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&amp;', false, false, false,
1621 false, $nexttimestamp);
1623 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1624 $content .= $prevlink;
1625 $content .= '<span class="hide"> | </span><span class="current">' .userdate($time,
1626 get_string('strftimedaydate')) . '</span>';
1627 $content .= '<span class="hide"> | </span>' . $nextlink;
1628 $content .= "<span class=\"clearer\"><!-- --></span>";
1629 $content .= \html_writer::end_tag('div') . "\n";
1631 break;
1634 return $content;
1638 * Return the representation day.
1640 * @param int $tstamp Timestamp in GMT
1641 * @param int|bool $now current Unix timestamp
1642 * @param bool $usecommonwords
1643 * @return string the formatted date/time
1645 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1646 static $shortformat;
1648 if (empty($shortformat)) {
1649 $shortformat = get_string('strftimedayshort');
1652 if ($now === false) {
1653 $now = time();
1656 // To have it in one place, if a change is needed.
1657 $formal = userdate($tstamp, $shortformat);
1659 $datestamp = usergetdate($tstamp);
1660 $datenow = usergetdate($now);
1662 if ($usecommonwords == false) {
1663 // We don't want words, just a date.
1664 return $formal;
1665 } else if ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1666 return get_string('today', 'calendar');
1667 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1668 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12
1669 && $datenow['yday'] == 1)) {
1670 return get_string('yesterday', 'calendar');
1671 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1672 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12
1673 && $datestamp['yday'] == 1)) {
1674 return get_string('tomorrow', 'calendar');
1675 } else {
1676 return $formal;
1681 * return the formatted representation time.
1684 * @param int $time the timestamp in UTC, as obtained from the database
1685 * @return string the formatted date/time
1687 function calendar_time_representation($time) {
1688 static $langtimeformat = null;
1690 if ($langtimeformat === null) {
1691 $langtimeformat = get_string('strftimetime');
1694 $timeformat = get_user_preferences('calendar_timeformat');
1695 if (empty($timeformat)) {
1696 $timeformat = get_config(null, 'calendar_site_timeformat');
1699 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
1703 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1705 * @param string|moodle_url $linkbase
1706 * @param int $d The number of the day.
1707 * @param int $m The number of the month.
1708 * @param int $y The number of the year.
1709 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1710 * $m and $y are kept for backwards compatibility.
1711 * @return moodle_url|null $linkbase
1713 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1714 if (empty($linkbase)) {
1715 return null;
1718 if (!($linkbase instanceof \moodle_url)) {
1719 $linkbase = new \moodle_url($linkbase);
1722 $linkbase->param('time', calendar_get_timestamp($d, $m, $y, $time));
1724 return $linkbase;
1728 * Build and return a previous month HTML link, with an arrow.
1730 * @param string $text The text label.
1731 * @param string|moodle_url $linkbase The URL stub.
1732 * @param int $d The number of the date.
1733 * @param int $m The number of the month.
1734 * @param int $y year The number of the year.
1735 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1736 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1737 * $m and $y are kept for backwards compatibility.
1738 * @return string HTML string.
1740 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1741 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1743 if (empty($href)) {
1744 return $text;
1747 $attrs = [
1748 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1749 'data-drop-zone' => 'nav-link',
1752 return link_arrow_left($text, $href->out(false), $accesshide, 'previous', $attrs);
1756 * Build and return a next month HTML link, with an arrow.
1758 * @param string $text The text label.
1759 * @param string|moodle_url $linkbase The URL stub.
1760 * @param int $d the number of the Day
1761 * @param int $m The number of the month.
1762 * @param int $y The number of the year.
1763 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1764 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1765 * $m and $y are kept for backwards compatibility.
1766 * @return string HTML string.
1768 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1769 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1771 if (empty($href)) {
1772 return $text;
1775 $attrs = [
1776 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1777 'data-drop-zone' => 'nav-link',
1780 return link_arrow_right($text, $href->out(false), $accesshide, 'next', $attrs);
1784 * Return the number of days in month.
1786 * @param int $month the number of the month.
1787 * @param int $year the number of the year
1788 * @return int
1790 function calendar_days_in_month($month, $year) {
1791 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1792 return $calendartype->get_num_days_in_month($year, $month);
1796 * Get the next following month.
1798 * @param int $month the number of the month.
1799 * @param int $year the number of the year.
1800 * @return array the following month
1802 function calendar_add_month($month, $year) {
1803 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1804 return $calendartype->get_next_month($year, $month);
1808 * Get the previous month.
1810 * @param int $month the number of the month.
1811 * @param int $year the number of the year.
1812 * @return array previous month
1814 function calendar_sub_month($month, $year) {
1815 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1816 return $calendartype->get_prev_month($year, $month);
1820 * Get per-day basis events
1822 * @param array $events list of events
1823 * @param int $month the number of the month
1824 * @param int $year the number of the year
1825 * @param array $eventsbyday event on specific day
1826 * @param array $durationbyday duration of the event in days
1827 * @param array $typesbyday event type (eg: global, course, user, or group)
1828 * @param array $courses list of courses
1829 * @return void
1831 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1832 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1834 $eventsbyday = array();
1835 $typesbyday = array();
1836 $durationbyday = array();
1838 if ($events === false) {
1839 return;
1842 foreach ($events as $event) {
1843 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
1844 if ($event->timeduration) {
1845 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
1846 } else {
1847 $enddate = $startdate;
1850 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair.
1851 if (!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) &&
1852 ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1853 continue;
1856 $eventdaystart = intval($startdate['mday']);
1858 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
1859 // Give the event to its day.
1860 $eventsbyday[$eventdaystart][] = $event->id;
1862 // Mark the day as having such an event.
1863 if ($event->courseid == SITEID && $event->groupid == 0) {
1864 $typesbyday[$eventdaystart]['startglobal'] = true;
1865 // Set event class for global event.
1866 $events[$event->id]->class = 'calendar_event_global';
1867 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1868 $typesbyday[$eventdaystart]['startcourse'] = true;
1869 // Set event class for course event.
1870 $events[$event->id]->class = 'calendar_event_course';
1871 } else if ($event->groupid) {
1872 $typesbyday[$eventdaystart]['startgroup'] = true;
1873 // Set event class for group event.
1874 $events[$event->id]->class = 'calendar_event_group';
1875 } else if ($event->userid) {
1876 $typesbyday[$eventdaystart]['startuser'] = true;
1877 // Set event class for user event.
1878 $events[$event->id]->class = 'calendar_event_user';
1882 if ($event->timeduration == 0) {
1883 // Proceed with the next.
1884 continue;
1887 // The event starts on $month $year or before.
1888 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
1889 $lowerbound = intval($startdate['mday']);
1890 } else {
1891 $lowerbound = 0;
1894 // Also, it ends on $month $year or later.
1895 if ($enddate['mon'] == $month && $enddate['year'] == $year) {
1896 $upperbound = intval($enddate['mday']);
1897 } else {
1898 $upperbound = calendar_days_in_month($month, $year);
1901 // Mark all days between $lowerbound and $upperbound (inclusive) as duration.
1902 for ($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
1903 $durationbyday[$i][] = $event->id;
1904 if ($event->courseid == SITEID && $event->groupid == 0) {
1905 $typesbyday[$i]['durationglobal'] = true;
1906 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1907 $typesbyday[$i]['durationcourse'] = true;
1908 } else if ($event->groupid) {
1909 $typesbyday[$i]['durationgroup'] = true;
1910 } else if ($event->userid) {
1911 $typesbyday[$i]['durationuser'] = true;
1916 return;
1920 * Returns the courses to load events for.
1922 * @param array $courseeventsfrom An array of courses to load calendar events for
1923 * @param bool $ignorefilters specify the use of filters, false is set as default
1924 * @return array An array of courses, groups, and user to load calendar events for based upon filters
1926 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
1927 global $USER, $CFG;
1929 // For backwards compatability we have to check whether the courses array contains
1930 // just id's in which case we need to load course objects.
1931 $coursestoload = array();
1932 foreach ($courseeventsfrom as $id => $something) {
1933 if (!is_object($something)) {
1934 $coursestoload[] = $id;
1935 unset($courseeventsfrom[$id]);
1939 $courses = array();
1940 $user = false;
1941 $group = false;
1943 // Get the capabilities that allow seeing group events from all groups.
1944 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
1946 $isloggedin = isloggedin();
1948 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
1949 $courses = array_keys($courseeventsfrom);
1951 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
1952 $courses[] = SITEID;
1954 $courses = array_unique($courses);
1955 sort($courses);
1957 if (!empty($courses) && in_array(SITEID, $courses)) {
1958 // Sort courses for consistent colour highlighting.
1959 // Effectively ignoring SITEID as setting as last course id.
1960 $key = array_search(SITEID, $courses);
1961 unset($courses[$key]);
1962 $courses[] = SITEID;
1965 if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
1966 $user = $USER->id;
1969 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
1971 if (count($courseeventsfrom) == 1) {
1972 $course = reset($courseeventsfrom);
1973 if (has_any_capability($allgroupscaps, \context_course::instance($course->id))) {
1974 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
1975 $group = array_keys($coursegroups);
1978 if ($group === false) {
1979 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, \context_system::instance())) {
1980 $group = true;
1981 } else if ($isloggedin) {
1982 $groupids = array();
1983 foreach ($courseeventsfrom as $courseid => $course) {
1984 // If the user is an editing teacher in there.
1985 if (!empty($USER->groupmember[$course->id])) {
1986 // We've already cached the users groups for this course so we can just use that.
1987 $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
1988 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1989 // If this course has groups, show events from all of those related to the current user.
1990 $coursegroups = groups_get_user_groups($course->id, $USER->id);
1991 $groupids = array_merge($groupids, $coursegroups['0']);
1994 if (!empty($groupids)) {
1995 $group = $groupids;
2000 if (empty($courses)) {
2001 $courses = false;
2004 return array($courses, $group, $user);
2008 * Return the capability for editing calendar event.
2010 * @param calendar_event $event event object
2011 * @param bool $manualedit is the event being edited manually by the user
2012 * @return bool capability to edit event
2014 function calendar_edit_event_allowed($event, $manualedit = false) {
2015 global $USER, $DB;
2017 // Must be logged in.
2018 if (!isloggedin()) {
2019 return false;
2022 // Can not be using guest account.
2023 if (isguestuser()) {
2024 return false;
2027 if ($manualedit && !empty($event->modulename)) {
2028 $hascallback = component_callback_exists(
2029 'mod_' . $event->modulename,
2030 'core_calendar_event_timestart_updated'
2033 if (!$hascallback) {
2034 // If the activity hasn't implemented the correct callback
2035 // to handle changes to it's events then don't allow any
2036 // manual changes to them.
2037 return false;
2040 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2041 $hasmodule = isset($coursemodules[$event->modulename]);
2042 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2044 // If modinfo doesn't know about the module, return false to be safe.
2045 if (!$hasmodule || !$hasinstance) {
2046 return false;
2049 $coursemodule = $coursemodules[$event->modulename][$event->instance];
2050 $context = context_module::instance($coursemodule->id);
2051 // This is the capability that allows a user to modify the activity
2052 // settings. Since the activity generated this event we need to check
2053 // that the current user has the same capability before allowing them
2054 // to update the event because the changes to the event will be
2055 // reflected within the activity.
2056 return has_capability('moodle/course:manageactivities', $context);
2059 // You cannot edit URL based calendar subscription events presently.
2060 if (!empty($event->subscriptionid)) {
2061 if (!empty($event->subscription->url)) {
2062 // This event can be updated externally, so it cannot be edited.
2063 return false;
2067 $sitecontext = \context_system::instance();
2069 // If user has manageentries at site level, return true.
2070 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2071 return true;
2074 // If groupid is set, it's definitely a group event.
2075 if (!empty($event->groupid)) {
2076 // Allow users to add/edit group events if -
2077 // 1) They have manageentries for the course OR
2078 // 2) They have managegroupentries AND are in the group.
2079 $group = $DB->get_record('groups', array('id' => $event->groupid));
2080 return $group && (
2081 has_capability('moodle/calendar:manageentries', $event->context) ||
2082 (has_capability('moodle/calendar:managegroupentries', $event->context)
2083 && groups_is_member($event->groupid)));
2084 } else if (!empty($event->courseid)) {
2085 // If groupid is not set, but course is set, it's definitely a course event.
2086 return has_capability('moodle/calendar:manageentries', $event->context);
2087 } else if (!empty($event->categoryid)) {
2088 // If groupid is not set, but category is set, it's definitely a category event.
2089 return has_capability('moodle/calendar:manageentries', $event->context);
2090 } else if (!empty($event->userid) && $event->userid == $USER->id) {
2091 // If course is not set, but userid id set, it's a user event.
2092 return (has_capability('moodle/calendar:manageownentries', $event->context));
2093 } else if (!empty($event->userid)) {
2094 return (has_capability('moodle/calendar:manageentries', $event->context));
2097 return false;
2101 * Return the capability for deleting a calendar event.
2103 * @param calendar_event $event The event object
2104 * @return bool Whether the user has permission to delete the event or not.
2106 function calendar_delete_event_allowed($event) {
2107 // Only allow delete if you have capabilities and it is not an module event.
2108 return (calendar_edit_event_allowed($event) && empty($event->modulename));
2112 * Returns the default courses to display on the calendar when there isn't a specific
2113 * course to display.
2115 * @return array $courses Array of courses to display
2117 function calendar_get_default_courses() {
2118 global $CFG, $DB;
2120 if (!isloggedin()) {
2121 return array();
2124 if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', \context_system::instance())) {
2125 $select = ', ' . \context_helper::get_preload_record_columns_sql('ctx');
2126 $join = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
2127 $sql = "SELECT c.* $select
2128 FROM {course} c
2129 $join
2130 WHERE EXISTS (SELECT 1 FROM {event} e WHERE e.courseid = c.id)
2132 $courses = $DB->get_records_sql($sql, array('contextlevel' => CONTEXT_COURSE), 0, 20);
2133 foreach ($courses as $course) {
2134 \context_helper::preload_from_record($course);
2136 return $courses;
2139 $courses = enrol_get_my_courses();
2141 return $courses;
2145 * Get event format time.
2147 * @param calendar_event $event event object
2148 * @param int $now current time in gmt
2149 * @param array $linkparams list of params for event link
2150 * @param bool $usecommonwords the words as formatted date/time.
2151 * @param int $showtime determine the show time GMT timestamp
2152 * @return string $eventtime link/string for event time
2154 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
2155 $starttime = $event->timestart;
2156 $endtime = $event->timestart + $event->timeduration;
2158 if (empty($linkparams) || !is_array($linkparams)) {
2159 $linkparams = array();
2162 $linkparams['view'] = 'day';
2164 // OK, now to get a meaningful display.
2165 // Check if there is a duration for this event.
2166 if ($event->timeduration) {
2167 // Get the midnight of the day the event will start.
2168 $usermidnightstart = usergetmidnight($starttime);
2169 // Get the midnight of the day the event will end.
2170 $usermidnightend = usergetmidnight($endtime);
2171 // Check if we will still be on the same day.
2172 if ($usermidnightstart == $usermidnightend) {
2173 // Check if we are running all day.
2174 if ($event->timeduration == DAYSECS) {
2175 $time = get_string('allday', 'calendar');
2176 } else { // Specify the time we will be running this from.
2177 $datestart = calendar_time_representation($starttime);
2178 $dateend = calendar_time_representation($endtime);
2179 $time = $datestart . ' <strong>&raquo;</strong> ' . $dateend;
2182 // Set printable representation.
2183 if (!$showtime) {
2184 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2185 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2186 $eventtime = \html_writer::link($url, $day) . ', ' . $time;
2187 } else {
2188 $eventtime = $time;
2190 } else { // It must spans two or more days.
2191 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
2192 if ($showtime == $usermidnightstart) {
2193 $daystart = '';
2195 $timestart = calendar_time_representation($event->timestart);
2196 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
2197 if ($showtime == $usermidnightend) {
2198 $dayend = '';
2200 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
2202 // Set printable representation.
2203 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2204 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2205 $eventtime = $timestart . ' <strong>&raquo;</strong> ' . \html_writer::link($url, $dayend) . $timeend;
2206 } else {
2207 // The event is in the future, print start and end links.
2208 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2209 $eventtime = \html_writer::link($url, $daystart) . $timestart . ' <strong>&raquo;</strong> ';
2211 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2212 $eventtime .= \html_writer::link($url, $dayend) . $timeend;
2215 } else { // There is no time duration.
2216 $time = calendar_time_representation($event->timestart);
2217 // Set printable representation.
2218 if (!$showtime) {
2219 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2220 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2221 $eventtime = \html_writer::link($url, $day) . ', ' . trim($time);
2222 } else {
2223 $eventtime = $time;
2227 // Check if It has expired.
2228 if ($event->timestart + $event->timeduration < $now) {
2229 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2232 return $eventtime;
2236 * Checks to see if the requested type of event should be shown for the given user.
2238 * @param int $type The type to check the display for (default is to display all)
2239 * @param stdClass|int|null $user The user to check for - by default the current user
2240 * @return bool True if the tyep should be displayed false otherwise
2242 function calendar_show_event_type($type, $user = null) {
2243 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
2245 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2246 global $SESSION;
2247 if (!isset($SESSION->calendarshoweventtype)) {
2248 $SESSION->calendarshoweventtype = $default;
2250 return $SESSION->calendarshoweventtype & $type;
2251 } else {
2252 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2257 * Sets the display of the event type given $display.
2259 * If $display = true the event type will be shown.
2260 * If $display = false the event type will NOT be shown.
2261 * If $display = null the current value will be toggled and saved.
2263 * @param int $type object of CALENDAR_EVENT_XXX
2264 * @param bool $display option to display event type
2265 * @param stdClass|int $user moodle user object or id, null means current user
2267 function calendar_set_event_type_display($type, $display = null, $user = null) {
2268 $persist = get_user_preferences('calendar_persistflt', 0, $user);
2269 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP
2270 + CALENDAR_EVENT_USER + CALENDAR_EVENT_COURSECAT;
2271 if ($persist === 0) {
2272 global $SESSION;
2273 if (!isset($SESSION->calendarshoweventtype)) {
2274 $SESSION->calendarshoweventtype = $default;
2276 $preference = $SESSION->calendarshoweventtype;
2277 } else {
2278 $preference = get_user_preferences('calendar_savedflt', $default, $user);
2280 $current = $preference & $type;
2281 if ($display === null) {
2282 $display = !$current;
2284 if ($display && !$current) {
2285 $preference += $type;
2286 } else if (!$display && $current) {
2287 $preference -= $type;
2289 if ($persist === 0) {
2290 $SESSION->calendarshoweventtype = $preference;
2291 } else {
2292 if ($preference == $default) {
2293 unset_user_preference('calendar_savedflt', $user);
2294 } else {
2295 set_user_preference('calendar_savedflt', $preference, $user);
2301 * Get calendar's allowed types.
2303 * @param stdClass $allowed list of allowed edit for event type
2304 * @param stdClass|int $course object of a course or course id
2305 * @param array $groups array of groups for the given course
2306 * @param stdClass|int $category object of a category
2308 function calendar_get_allowed_types(&$allowed, $course = null, $groups = null, $category = null) {
2309 global $USER, $DB;
2311 $allowed = new \stdClass();
2312 $allowed->user = has_capability('moodle/calendar:manageownentries', \context_system::instance());
2313 $allowed->groups = false;
2314 $allowed->courses = false;
2315 $allowed->categories = false;
2316 $allowed->site = has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID));
2317 $getgroupsfunc = function($course, $context, $user) use ($groups) {
2318 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2319 if (has_capability('moodle/site:accessallgroups', $context)) {
2320 return is_null($groups) ? groups_get_all_groups($course->id) : $groups;
2321 } else {
2322 if (is_null($groups)) {
2323 return groups_get_all_groups($course->id, $user->id);
2324 } else {
2325 return array_filter($groups, function($group) use ($user) {
2326 return isset($group->members[$user->id]);
2332 return false;
2335 if (!empty($course)) {
2336 if (!is_object($course)) {
2337 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST);
2339 if ($course->id != SITEID) {
2340 $coursecontext = \context_course::instance($course->id);
2341 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
2343 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2344 $allowed->courses = array($course->id => 1);
2345 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2346 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
2347 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2352 if (!empty($category)) {
2353 $catcontext = \context_coursecat::instance($category->id);
2354 if (has_capability('moodle/category:manage', $catcontext)) {
2355 $allowed->categories = [$category->id => 1];
2361 * Get all of the allowed types for all of the courses and groups
2362 * the logged in user belongs to.
2364 * The returned array will optionally have 5 keys:
2365 * 'user' : true if the logged in user can create user events
2366 * 'site' : true if the logged in user can create site events
2367 * 'category' : array of course categories that the user can create events for
2368 * 'course' : array of courses that the user can create events for
2369 * 'group': array of groups that the user can create events for
2370 * 'groupcourses' : array of courses that the groups belong to (can
2371 * be different from the list in 'course'.
2373 * @return array The array of allowed types.
2375 function calendar_get_all_allowed_types() {
2376 global $CFG, $USER, $DB;
2378 require_once($CFG->libdir . '/enrollib.php');
2380 $types = [];
2382 calendar_get_allowed_types($allowed);
2384 if ($allowed->user) {
2385 $types['user'] = true;
2388 if ($allowed->site) {
2389 $types['site'] = true;
2392 if (coursecat::has_manage_capability_on_any()) {
2393 $types['category'] = coursecat::make_categories_list('moodle/category:manage');
2396 // This function warms the context cache for the course so the calls
2397 // to load the course context in calendar_get_allowed_types don't result
2398 // in additional DB queries.
2399 $courses = enrol_get_users_courses($USER->id, true);
2400 // We want to pre-fetch all of the groups for each course in a single
2401 // query to avoid calendar_get_allowed_types from hitting the DB for
2402 // each separate course.
2403 $groups = groups_get_all_groups_for_courses($courses);
2405 foreach ($courses as $course) {
2406 $coursegroups = isset($groups[$course->id]) ? $groups[$course->id] : null;
2407 calendar_get_allowed_types($allowed, $course, $coursegroups);
2409 if (!empty($allowed->courses)) {
2410 if (!isset($types['course'])) {
2411 $types['course'] = [$course];
2412 } else {
2413 $types['course'][$course->id] = $course;
2417 if (!empty($allowed->groups)) {
2418 if (!isset($types['groupcourses'])) {
2419 $types['groupcourses'] = [$course];
2420 } else {
2421 $types['groupcourses'][$course->id] = $course;
2424 if (!isset($types['group'])) {
2425 $types['group'] = array_values($allowed->groups);
2426 } else {
2427 $types['group'] = array_merge($types['group'], array_values($allowed->groups));
2432 return $types;
2436 * See if user can add calendar entries at all used to print the "New Event" button.
2438 * @param stdClass $course object of a course or course id
2439 * @return bool has the capability to add at least one event type
2441 function calendar_user_can_add_event($course) {
2442 if (!isloggedin() || isguestuser()) {
2443 return false;
2446 calendar_get_allowed_types($allowed, $course);
2448 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->category || $allowed->site);
2452 * Check wether the current user is permitted to add events.
2454 * @param stdClass $event object of event
2455 * @return bool has the capability to add event
2457 function calendar_add_event_allowed($event) {
2458 global $USER, $DB;
2460 // Can not be using guest account.
2461 if (!isloggedin() or isguestuser()) {
2462 return false;
2465 $sitecontext = \context_system::instance();
2467 // If user has manageentries at site level, always return true.
2468 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2469 return true;
2472 switch ($event->eventtype) {
2473 case 'category':
2474 return has_capability('moodle/category:manage', $event->context);
2475 case 'course':
2476 return has_capability('moodle/calendar:manageentries', $event->context);
2477 case 'group':
2478 // Allow users to add/edit group events if -
2479 // 1) They have manageentries (= entries for whole course).
2480 // 2) They have managegroupentries AND are in the group.
2481 $group = $DB->get_record('groups', array('id' => $event->groupid));
2482 return $group && (
2483 has_capability('moodle/calendar:manageentries', $event->context) ||
2484 (has_capability('moodle/calendar:managegroupentries', $event->context)
2485 && groups_is_member($event->groupid)));
2486 case 'user':
2487 if ($event->userid == $USER->id) {
2488 return (has_capability('moodle/calendar:manageownentries', $event->context));
2490 // There is intentionally no 'break'.
2491 case 'site':
2492 return has_capability('moodle/calendar:manageentries', $event->context);
2493 default:
2494 return has_capability('moodle/calendar:manageentries', $event->context);
2499 * Returns option list for the poll interval setting.
2501 * @return array An array of poll interval options. Interval => description.
2503 function calendar_get_pollinterval_choices() {
2504 return array(
2505 '0' => new \lang_string('never', 'calendar'),
2506 HOURSECS => new \lang_string('hourly', 'calendar'),
2507 DAYSECS => new \lang_string('daily', 'calendar'),
2508 WEEKSECS => new \lang_string('weekly', 'calendar'),
2509 '2628000' => new \lang_string('monthly', 'calendar'),
2510 YEARSECS => new \lang_string('annually', 'calendar')
2515 * Returns option list of available options for the calendar event type, given the current user and course.
2517 * @param int $courseid The id of the course
2518 * @return array An array containing the event types the user can create.
2520 function calendar_get_eventtype_choices($courseid) {
2521 $choices = array();
2522 $allowed = new \stdClass;
2523 calendar_get_allowed_types($allowed, $courseid);
2525 if ($allowed->user) {
2526 $choices['user'] = get_string('userevents', 'calendar');
2528 if ($allowed->site) {
2529 $choices['site'] = get_string('siteevents', 'calendar');
2531 if (!empty($allowed->courses)) {
2532 $choices['course'] = get_string('courseevents', 'calendar');
2534 if (!empty($allowed->categories)) {
2535 $choices['category'] = get_string('categoryevents', 'calendar');
2537 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2538 $choices['group'] = get_string('group');
2541 return array($choices, $allowed->groups);
2545 * Add an iCalendar subscription to the database.
2547 * @param stdClass $sub The subscription object (e.g. from the form)
2548 * @return int The insert ID, if any.
2550 function calendar_add_subscription($sub) {
2551 global $DB, $USER, $SITE;
2553 if ($sub->eventtype === 'site') {
2554 $sub->courseid = $SITE->id;
2555 } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
2556 $sub->courseid = $sub->course;
2557 } else if ($sub->eventtype === 'category') {
2558 $sub->categoryid = $sub->category;
2559 } else {
2560 // User events.
2561 $sub->courseid = 0;
2563 $sub->userid = $USER->id;
2565 // File subscriptions never update.
2566 if (empty($sub->url)) {
2567 $sub->pollinterval = 0;
2570 if (!empty($sub->name)) {
2571 if (empty($sub->id)) {
2572 $id = $DB->insert_record('event_subscriptions', $sub);
2573 // We cannot cache the data here because $sub is not complete.
2574 $sub->id = $id;
2575 // Trigger event, calendar subscription added.
2576 $eventparams = array('objectid' => $sub->id,
2577 'context' => calendar_get_calendar_context($sub),
2578 'other' => array('eventtype' => $sub->eventtype, 'courseid' => $sub->courseid)
2580 $event = \core\event\calendar_subscription_created::create($eventparams);
2581 $event->trigger();
2582 return $id;
2583 } else {
2584 // Why are we doing an update here?
2585 calendar_update_subscription($sub);
2586 return $sub->id;
2588 } else {
2589 print_error('errorbadsubscription', 'importcalendar');
2594 * Add an iCalendar event to the Moodle calendar.
2596 * @param stdClass $event The RFC-2445 iCalendar event
2597 * @param int $courseid The course ID
2598 * @param int $subscriptionid The iCalendar subscription ID
2599 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2600 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2601 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2603 function calendar_add_icalendar_event($event, $courseid, $subscriptionid, $timezone='UTC') {
2604 global $DB;
2606 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2607 if (empty($event->properties['SUMMARY'])) {
2608 return 0;
2611 $name = $event->properties['SUMMARY'][0]->value;
2612 $name = str_replace('\n', '<br />', $name);
2613 $name = str_replace('\\', '', $name);
2614 $name = preg_replace('/\s+/u', ' ', $name);
2616 $eventrecord = new \stdClass;
2617 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
2619 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2620 $description = '';
2621 } else {
2622 $description = $event->properties['DESCRIPTION'][0]->value;
2623 $description = clean_param($description, PARAM_NOTAGS);
2624 $description = str_replace('\n', '<br />', $description);
2625 $description = str_replace('\\', '', $description);
2626 $description = preg_replace('/\s+/u', ' ', $description);
2628 $eventrecord->description = $description;
2630 // Probably a repeating event with RRULE etc. TODO: skip for now.
2631 if (empty($event->properties['DTSTART'][0]->value)) {
2632 return 0;
2635 if (isset($event->properties['DTSTART'][0]->parameters['TZID'])) {
2636 $tz = $event->properties['DTSTART'][0]->parameters['TZID'];
2637 } else {
2638 $tz = $timezone;
2640 $tz = \core_date::normalise_timezone($tz);
2641 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value . ' ' . $tz);
2642 if (empty($event->properties['DTEND'])) {
2643 $eventrecord->timeduration = 0; // No duration if no end time specified.
2644 } else {
2645 if (isset($event->properties['DTEND'][0]->parameters['TZID'])) {
2646 $endtz = $event->properties['DTEND'][0]->parameters['TZID'];
2647 } else {
2648 $endtz = $timezone;
2650 $endtz = \core_date::normalise_timezone($endtz);
2651 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value . ' ' . $endtz) - $eventrecord->timestart;
2654 // Check to see if it should be treated as an all day event.
2655 if ($eventrecord->timeduration == DAYSECS) {
2656 // Check to see if the event started at Midnight on the imported calendar.
2657 date_default_timezone_set($timezone);
2658 if (date('H:i:s', $eventrecord->timestart) === "00:00:00") {
2659 // This event should be an all day event. This is not correct, we don't do anything differently for all day events.
2660 // See MDL-56227.
2661 $eventrecord->timeduration = 0;
2663 \core_date::set_default_server_timezone();
2666 $eventrecord->uuid = $event->properties['UID'][0]->value;
2667 $eventrecord->timemodified = time();
2669 // Add the iCal subscription details if required.
2670 // We should never do anything with an event without a subscription reference.
2671 $sub = calendar_get_subscription($subscriptionid);
2672 $eventrecord->subscriptionid = $subscriptionid;
2673 $eventrecord->userid = $sub->userid;
2674 $eventrecord->groupid = $sub->groupid;
2675 $eventrecord->courseid = $sub->courseid;
2676 $eventrecord->eventtype = $sub->eventtype;
2678 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid,
2679 'subscriptionid' => $eventrecord->subscriptionid))) {
2680 $eventrecord->id = $updaterecord->id;
2681 $return = CALENDAR_IMPORT_EVENT_UPDATED; // Update.
2682 } else {
2683 $return = CALENDAR_IMPORT_EVENT_INSERTED; // Insert.
2685 if ($createdevent = \calendar_event::create($eventrecord, false)) {
2686 if (!empty($event->properties['RRULE'])) {
2687 // Repeating events.
2688 date_default_timezone_set($tz); // Change time zone to parse all events.
2689 $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
2690 $rrule->parse_rrule();
2691 $rrule->create_events($createdevent);
2692 \core_date::set_default_server_timezone(); // Change time zone back to what it was.
2694 return $return;
2695 } else {
2696 return 0;
2701 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2703 * @param int $subscriptionid The ID of the subscription we are acting upon.
2704 * @param int $pollinterval The poll interval to use.
2705 * @param int $action The action to be performed. One of update or remove.
2706 * @throws dml_exception if invalid subscriptionid is provided
2707 * @return string A log of the import progress, including errors
2709 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2710 // Fetch the subscription from the database making sure it exists.
2711 $sub = calendar_get_subscription($subscriptionid);
2713 // Update or remove the subscription, based on action.
2714 switch ($action) {
2715 case CALENDAR_SUBSCRIPTION_UPDATE:
2716 // Skip updating file subscriptions.
2717 if (empty($sub->url)) {
2718 break;
2720 $sub->pollinterval = $pollinterval;
2721 calendar_update_subscription($sub);
2723 // Update the events.
2724 return "<p>" . get_string('subscriptionupdated', 'calendar', $sub->name) . "</p>" .
2725 calendar_update_subscription_events($subscriptionid);
2726 case CALENDAR_SUBSCRIPTION_REMOVE:
2727 calendar_delete_subscription($subscriptionid);
2728 return get_string('subscriptionremoved', 'calendar', $sub->name);
2729 break;
2730 default:
2731 break;
2733 return '';
2737 * Delete subscription and all related events.
2739 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
2741 function calendar_delete_subscription($subscription) {
2742 global $DB;
2744 if (!is_object($subscription)) {
2745 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST);
2748 // Delete subscription and related events.
2749 $DB->delete_records('event', array('subscriptionid' => $subscription->id));
2750 $DB->delete_records('event_subscriptions', array('id' => $subscription->id));
2751 \cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id));
2753 // Trigger event, calendar subscription deleted.
2754 $eventparams = array('objectid' => $subscription->id,
2755 'context' => calendar_get_calendar_context($subscription),
2756 'other' => array('courseid' => $subscription->courseid)
2758 $event = \core\event\calendar_subscription_deleted::create($eventparams);
2759 $event->trigger();
2763 * From a URL, fetch the calendar and return an iCalendar object.
2765 * @param string $url The iCalendar URL
2766 * @return iCalendar The iCalendar object
2768 function calendar_get_icalendar($url) {
2769 global $CFG;
2771 require_once($CFG->libdir . '/filelib.php');
2773 $curl = new \curl();
2774 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
2775 $calendar = $curl->get($url);
2777 // Http code validation should actually be the job of curl class.
2778 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
2779 throw new \moodle_exception('errorinvalidicalurl', 'calendar');
2782 $ical = new \iCalendar();
2783 $ical->unserialize($calendar);
2785 return $ical;
2789 * Import events from an iCalendar object into a course calendar.
2791 * @param iCalendar $ical The iCalendar object.
2792 * @param int $courseid The course ID for the calendar.
2793 * @param int $subscriptionid The subscription ID.
2794 * @return string A log of the import progress, including errors.
2796 function calendar_import_icalendar_events($ical, $courseid, $subscriptionid = null) {
2797 global $DB;
2799 $return = '';
2800 $eventcount = 0;
2801 $updatecount = 0;
2803 // Large calendars take a while...
2804 if (!CLI_SCRIPT) {
2805 \core_php_time_limit::raise(300);
2808 // Mark all events in a subscription with a zero timestamp.
2809 if (!empty($subscriptionid)) {
2810 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
2811 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
2814 // Grab the timezone from the iCalendar file to be used later.
2815 if (isset($ical->properties['X-WR-TIMEZONE'][0]->value)) {
2816 $timezone = $ical->properties['X-WR-TIMEZONE'][0]->value;
2817 } else {
2818 $timezone = 'UTC';
2821 $return = '';
2822 foreach ($ical->components['VEVENT'] as $event) {
2823 $res = calendar_add_icalendar_event($event, $courseid, $subscriptionid, $timezone);
2824 switch ($res) {
2825 case CALENDAR_IMPORT_EVENT_UPDATED:
2826 $updatecount++;
2827 break;
2828 case CALENDAR_IMPORT_EVENT_INSERTED:
2829 $eventcount++;
2830 break;
2831 case 0:
2832 $return .= '<p>' . get_string('erroraddingevent', 'calendar') . ': ';
2833 if (empty($event->properties['SUMMARY'])) {
2834 $return .= '(' . get_string('notitle', 'calendar') . ')';
2835 } else {
2836 $return .= $event->properties['SUMMARY'][0]->value;
2838 $return .= "</p>\n";
2839 break;
2843 $return .= "<p>" . get_string('eventsimported', 'calendar', $eventcount) . "</p> ";
2844 $return .= "<p>" . get_string('eventsupdated', 'calendar', $updatecount) . "</p>";
2846 // Delete remaining zero-marked events since they're not in remote calendar.
2847 if (!empty($subscriptionid)) {
2848 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
2849 if (!empty($deletecount)) {
2850 $DB->delete_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
2851 $return .= "<p> " . get_string('eventsdeleted', 'calendar') . ": {$deletecount} </p>\n";
2855 return $return;
2859 * Fetch a calendar subscription and update the events in the calendar.
2861 * @param int $subscriptionid The course ID for the calendar.
2862 * @return string A log of the import progress, including errors.
2864 function calendar_update_subscription_events($subscriptionid) {
2865 $sub = calendar_get_subscription($subscriptionid);
2867 // Don't update a file subscription.
2868 if (empty($sub->url)) {
2869 return 'File subscription not updated.';
2872 $ical = calendar_get_icalendar($sub->url);
2873 $return = calendar_import_icalendar_events($ical, $sub->courseid, $subscriptionid);
2874 $sub->lastupdated = time();
2876 calendar_update_subscription($sub);
2878 return $return;
2882 * Update a calendar subscription. Also updates the associated cache.
2884 * @param stdClass|array $subscription Subscription record.
2885 * @throws coding_exception If something goes wrong
2886 * @since Moodle 2.5
2888 function calendar_update_subscription($subscription) {
2889 global $DB;
2891 if (is_array($subscription)) {
2892 $subscription = (object)$subscription;
2894 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
2895 throw new \coding_exception('Cannot update a subscription without a valid id');
2898 $DB->update_record('event_subscriptions', $subscription);
2900 // Update cache.
2901 $cache = \cache::make('core', 'calendar_subscriptions');
2902 $cache->set($subscription->id, $subscription);
2904 // Trigger event, calendar subscription updated.
2905 $eventparams = array('userid' => $subscription->userid,
2906 'objectid' => $subscription->id,
2907 'context' => calendar_get_calendar_context($subscription),
2908 'other' => array('eventtype' => $subscription->eventtype, 'courseid' => $subscription->courseid)
2910 $event = \core\event\calendar_subscription_updated::create($eventparams);
2911 $event->trigger();
2915 * Checks to see if the user can edit a given subscription feed.
2917 * @param mixed $subscriptionorid Subscription object or id
2918 * @return bool true if current user can edit the subscription else false
2920 function calendar_can_edit_subscription($subscriptionorid) {
2921 if (is_array($subscriptionorid)) {
2922 $subscription = (object)$subscriptionorid;
2923 } else if (is_object($subscriptionorid)) {
2924 $subscription = $subscriptionorid;
2925 } else {
2926 $subscription = calendar_get_subscription($subscriptionorid);
2929 $allowed = new \stdClass;
2930 $courseid = $subscription->courseid;
2931 $groupid = $subscription->groupid;
2933 calendar_get_allowed_types($allowed, $courseid);
2934 switch ($subscription->eventtype) {
2935 case 'user':
2936 return $allowed->user;
2937 case 'course':
2938 if (isset($allowed->courses[$courseid])) {
2939 return $allowed->courses[$courseid];
2940 } else {
2941 return false;
2943 case 'site':
2944 return $allowed->site;
2945 case 'group':
2946 if (isset($allowed->groups[$groupid])) {
2947 return $allowed->groups[$groupid];
2948 } else {
2949 return false;
2951 default:
2952 return false;
2957 * Helper function to determine the context of a calendar subscription.
2958 * Subscriptions can be created in two contexts COURSE, or USER.
2960 * @param stdClass $subscription
2961 * @return context instance
2963 function calendar_get_calendar_context($subscription) {
2964 // Determine context based on calendar type.
2965 if ($subscription->eventtype === 'site') {
2966 $context = \context_course::instance(SITEID);
2967 } else if ($subscription->eventtype === 'group' || $subscription->eventtype === 'course') {
2968 $context = \context_course::instance($subscription->courseid);
2969 } else {
2970 $context = \context_user::instance($subscription->userid);
2972 return $context;
2976 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
2978 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
2980 * @return array
2982 function core_calendar_user_preferences() {
2983 $preferences = [];
2984 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED, 'default' => '0',
2985 'choices' => array('0', CALENDAR_TF_12, CALENDAR_TF_24)
2987 $preferences['calendar_startwday'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
2988 'choices' => array(0, 1, 2, 3, 4, 5, 6));
2989 $preferences['calendar_maxevents'] = array('type' => PARAM_INT, 'choices' => range(1, 20));
2990 $preferences['calendar_lookahead'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 365,
2991 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
2992 $preferences['calendar_persistflt'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
2993 'choices' => array(0, 1));
2994 return $preferences;
2998 * Get legacy calendar events
3000 * @param int $tstart Start time of time range for events
3001 * @param int $tend End time of time range for events
3002 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3003 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3004 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3005 * @param boolean $withduration whether only events starting within time range selected
3006 * or events in progress/already started selected as well
3007 * @param boolean $ignorehidden whether to select only visible events or all events
3008 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3010 function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses,
3011 $withduration = true, $ignorehidden = true, $categories = []) {
3012 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3013 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3014 // parameters, but with the new API method, only null and arrays are accepted.
3015 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3016 // If parameter is true, return null.
3017 if ($param === true) {
3018 return null;
3021 // If parameter is false, return an empty array.
3022 if ($param === false) {
3023 return [];
3026 // If the parameter is a scalar value, enclose it in an array.
3027 if (!is_array($param)) {
3028 return [$param];
3031 // No normalisation required.
3032 return $param;
3033 }, [$users, $groups, $courses, $categories]);
3035 $mapper = \core_calendar\local\event\container::get_event_mapper();
3036 $events = \core_calendar\local\api::get_events(
3037 $tstart,
3038 $tend,
3039 null,
3040 null,
3041 null,
3042 null,
3044 null,
3045 $userparam,
3046 $groupparam,
3047 $courseparam,
3048 $categoryparam,
3049 $withduration,
3050 $ignorehidden
3053 return array_reduce($events, function($carry, $event) use ($mapper) {
3054 return $carry + [$event->get_id() => $mapper->from_event_to_stdclass($event)];
3055 }, []);
3060 * Get the calendar view output.
3062 * @param \calendar_information $calendar The calendar being represented
3063 * @param string $view The type of calendar to have displayed
3064 * @param bool $includenavigation Whether to include navigation
3065 * @return array[array, string]
3067 function calendar_get_view(\calendar_information $calendar, $view, $includenavigation = true) {
3068 global $PAGE, $CFG;
3070 $renderer = $PAGE->get_renderer('core_calendar');
3071 $type = \core_calendar\type_factory::get_calendar_instance();
3073 // Calculate the bounds of the month.
3074 $date = $type->timestamp_to_date_array($calendar->time);
3076 if ($view === 'day') {
3077 $tstart = $type->convert_to_timestamp($date['year'], $date['mon'], $date['mday']);
3078 $tend = $tstart + DAYSECS - 1;
3079 } else if ($view === 'upcoming' || $view === 'upcoming_mini') {
3080 if (isset($CFG->calendar_lookahead)) {
3081 $defaultlookahead = intval($CFG->calendar_lookahead);
3082 } else {
3083 $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD;
3085 $lookahead = get_user_preferences('calendar_lookahead', $defaultlookahead);
3086 $defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS;
3087 if (isset($CFG->calendar_maxevents)) {
3088 $defaultmaxevents = intval($CFG->calendar_maxevents);
3090 $maxevents = get_user_preferences('calendar_maxevents', $defaultmaxevents);
3091 $tstart = $type->convert_to_timestamp($date['year'], $date['mon'], $date['mday'], $date['hours']);
3092 $tend = usergetmidnight($tstart + DAYSECS * $lookahead + 3 * HOURSECS) - 1;
3093 } else {
3094 $tstart = $type->convert_to_timestamp($date['year'], $date['mon'], 1);
3095 $monthdays = $type->get_num_days_in_month($date['year'], $date['mon']);
3096 $tend = $tstart + ($monthdays * DAYSECS) - 1;
3097 $selectortitle = get_string('detailedmonthviewfor', 'calendar');
3098 if ($view === 'mini' || $view === 'minithree') {
3099 $template = 'core_calendar/calendar_mini';
3100 } else {
3101 $template = 'core_calendar/calendar_month';
3105 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3106 // If parameter is true, return null.
3107 if ($param === true) {
3108 return null;
3111 // If parameter is false, return an empty array.
3112 if ($param === false) {
3113 return [];
3116 // If the parameter is a scalar value, enclose it in an array.
3117 if (!is_array($param)) {
3118 return [$param];
3121 // No normalisation required.
3122 return $param;
3123 }, [$calendar->users, $calendar->groups, $calendar->courses, $calendar->categories]);
3125 // We need to make sure user calendar preferences are respected.
3126 // If max upcoming events is not set then use default value of 40 events.
3127 if (isset($maxevents)) {
3128 $limit = $maxevents;
3129 } else {
3130 $limit = 40;
3133 $events = \core_calendar\local\api::get_events(
3134 $tstart,
3135 $tend,
3136 null,
3137 null,
3138 null,
3139 null,
3140 $limit,
3141 null,
3142 $userparam,
3143 $groupparam,
3144 $courseparam,
3145 $categoryparam,
3146 true,
3147 true,
3148 function ($event) {
3149 if ($proxy = $event->get_course_module()) {
3150 $cminfo = $proxy->get_proxied_instance();
3151 return $cminfo->uservisible;
3154 if ($proxy = $event->get_category()) {
3155 $category = $proxy->get_proxied_instance();
3157 return $category->is_uservisible();
3160 return true;
3164 $related = [
3165 'events' => $events,
3166 'cache' => new \core_calendar\external\events_related_objects_cache($events),
3167 'type' => $type,
3170 $data = [];
3171 if ($view == "month" || $view == "mini" || $view == "minithree") {
3172 $month = new \core_calendar\external\month_exporter($calendar, $type, $related);
3173 $month->set_includenavigation($includenavigation);
3174 $data = $month->export($renderer);
3175 } else if ($view == "day") {
3176 $day = new \core_calendar\external\calendar_day_exporter($calendar, $related);
3177 $data = $day->export($renderer);
3178 $template = 'core_calendar/calendar_day';
3179 } else if ($view == "upcoming" || $view == "upcoming_mini") {
3180 $upcoming = new \core_calendar\external\calendar_upcoming_exporter($calendar, $related);
3181 $data = $upcoming->export($renderer);
3183 if ($view == "upcoming") {
3184 $template = 'core_calendar/calendar_upcoming';
3185 } else if ($view == "upcoming_mini") {
3186 $template = 'core_calendar/upcoming_mini';
3190 return [$data, $template];
3194 * Request and render event form fragment.
3196 * @param array $args The fragment arguments.
3197 * @return string The rendered mform fragment.
3199 function calendar_output_fragment_event_form($args) {
3200 global $CFG, $OUTPUT, $USER;
3202 $html = '';
3203 $data = [];
3204 $eventid = isset($args['eventid']) ? clean_param($args['eventid'], PARAM_INT) : null;
3205 $starttime = isset($args['starttime']) ? clean_param($args['starttime'], PARAM_INT) : null;
3206 $courseid = isset($args['courseid']) ? clean_param($args['courseid'], PARAM_INT) : null;
3207 $categoryid = isset($args['categoryid']) ? clean_param($args['categoryid'], PARAM_INT) : null;
3208 $event = null;
3209 $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
3210 $context = \context_user::instance($USER->id);
3211 $editoroptions = \core_calendar\local\event\forms\create::build_editor_options($context);
3212 $formoptions = ['editoroptions' => $editoroptions];
3213 $draftitemid = 0;
3215 if ($hasformdata) {
3216 parse_str(clean_param($args['formdata'], PARAM_TEXT), $data);
3217 if (isset($data['description']['itemid'])) {
3218 $draftitemid = $data['description']['itemid'];
3222 if ($starttime) {
3223 $formoptions['starttime'] = $starttime;
3226 if (is_null($eventid)) {
3227 $mform = new \core_calendar\local\event\forms\create(
3228 null,
3229 $formoptions,
3230 'post',
3232 null,
3233 true,
3234 $data
3236 if ($courseid != SITEID) {
3237 $data['eventtype'] = 'course';
3238 $data['courseid'] = $courseid;
3239 $data['groupcourseid'] = $courseid;
3240 } else if (!empty($categoryid)) {
3241 $data['eventtype'] = 'category';
3242 $data['categoryid'] = $categoryid;
3244 $mform->set_data($data);
3245 } else {
3246 $event = calendar_event::load($eventid);
3247 $mapper = new \core_calendar\local\event\mappers\create_update_form_mapper();
3248 $eventdata = $mapper->from_legacy_event_to_data($event);
3249 $data = array_merge((array) $eventdata, $data);
3250 $event->count_repeats();
3251 $formoptions['event'] = $event;
3252 $data['description']['text'] = file_prepare_draft_area(
3253 $draftitemid,
3254 $event->context->id,
3255 'calendar',
3256 'event_description',
3257 $event->id,
3258 null,
3259 $data['description']['text']
3261 $data['description']['itemid'] = $draftitemid;
3263 $mform = new \core_calendar\local\event\forms\update(
3264 null,
3265 $formoptions,
3266 'post',
3268 null,
3269 true,
3270 $data
3272 $mform->set_data($data);
3274 // Check to see if this event is part of a subscription or import.
3275 // If so display a warning on edit.
3276 if (isset($event->subscriptionid) && ($event->subscriptionid != null)) {
3277 $renderable = new \core\output\notification(
3278 get_string('eventsubscriptioneditwarning', 'calendar'),
3279 \core\output\notification::NOTIFY_INFO
3282 $html .= $OUTPUT->render($renderable);
3286 if ($hasformdata) {
3287 $mform->is_validated();
3290 $html .= $mform->render();
3291 return $html;
3295 * Calculate the timestamp from the supplied Gregorian Year, Month, and Day.
3297 * @param int $d The day
3298 * @param int $m The month
3299 * @param int $y The year
3300 * @param int $time The timestamp to use instead of a separate y/m/d.
3301 * @return int The timestamp
3303 function calendar_get_timestamp($d, $m, $y, $time = 0) {
3304 // If a day, month and year were passed then convert it to a timestamp. If these were passed
3305 // then we can assume the day, month and year are passed as Gregorian, as no where in core
3306 // should we be passing these values rather than the time.
3307 if (!empty($d) && !empty($m) && !empty($y)) {
3308 if (checkdate($m, $d, $y)) {
3309 $time = make_timestamp($y, $m, $d);
3310 } else {
3311 $time = time();
3313 } else if (empty($time)) {
3314 $time = time();
3317 return $time;
3321 * Get the calendar footer options.
3323 * @param calendar_information $calendar The calendar information object.
3324 * @return array The data for template and template name.
3326 function calendar_get_footer_options($calendar) {
3327 global $CFG, $USER, $DB, $PAGE;
3329 // Generate hash for iCal link.
3330 $rawhash = $USER->id . $DB->get_field('user', 'password', ['id' => $USER->id]) . $CFG->calendar_exportsalt;
3331 $authtoken = sha1($rawhash);
3333 $renderer = $PAGE->get_renderer('core_calendar');
3334 $footer = new \core_calendar\external\footer_options_exporter($calendar, $USER->id, $authtoken);
3335 $data = $footer->export($renderer);
3336 $template = 'core_calendar/footer_options';
3338 return [$data, $template];
3342 * Get the list of potential calendar filter types as a type => name
3343 * combination.
3345 * @return array
3347 function calendar_get_filter_types() {
3348 $types = [
3349 'site',
3350 'category',
3351 'course',
3352 'group',
3353 'user',
3356 return array_map(function($type) {
3357 return [
3358 'eventtype' => $type,
3359 'name' => get_string("eventtype{$type}", "calendar"),
3361 }, $types);
3365 * Check whether the specified event type is valid.
3367 * @param string $type
3368 * @return bool
3370 function calendar_is_valid_eventtype($type) {
3371 $validtypes = [
3372 'user',
3373 'group',
3374 'course',
3375 'category',
3376 'site',
3378 return in_array($type, $validtypes);