2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
20 * @package core_calendar
21 * @copyright 2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
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');
33 * These are read by the administration component to provide default values
37 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
39 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
42 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
44 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
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
55 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
57 define('CALENDAR_DEFAULT_WEEKEND', 65);
60 * CALENDAR_URL - path to calendar's folder
62 define('CALENDAR_URL', $CFG->wwwroot
.'/calendar/');
65 * CALENDAR_TF_24 - Calendar time in 24 hours format
67 define('CALENDAR_TF_24', '%H:%M');
70 * CALENDAR_TF_12 - Calendar time in 12 hours format
72 define('CALENDAR_TF_12', '%I:%M %p');
75 * CALENDAR_EVENT_GLOBAL - Global calendar event types
77 define('CALENDAR_EVENT_GLOBAL', 1);
80 * CALENDAR_EVENT_COURSE - Course calendar event types
82 define('CALENDAR_EVENT_COURSE', 2);
85 * CALENDAR_EVENT_GROUP - group calendar event types
87 define('CALENDAR_EVENT_GROUP', 4);
90 * CALENDAR_EVENT_USER - user calendar event types
92 define('CALENDAR_EVENT_USER', 8);
95 * CALENDAR_EVENT_COURSECAT - Course category calendar event types
97 define('CALENDAR_EVENT_COURSECAT', 16);
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
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
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(
188 'forcehttps' => false,
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
202 public function __construct($data = null) {
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
)) {
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;
257 * Attempts to call a set_$key method if one exists otherwise falls back
258 * to simply set the property.
260 * @param string $key property name
261 * @param mixed $value value of the property
263 public function __set($key, $value) {
264 if (method_exists($this, 'set_'.$key)) {
265 $this->{'set_'.$key}($value);
267 $this->properties
->{$key} = $value;
273 * Attempts to call a get_$key method to return the property and ralls over
274 * to return the raw property.
276 * @param string $key property name
277 * @return mixed property value
278 * @throws \coding_exception
280 public function __get($key) {
281 if (method_exists($this, 'get_'.$key)) {
282 return $this->{'get_'.$key}();
284 if (!property_exists($this->properties
, $key)) {
285 throw new \
coding_exception('Undefined property requested');
287 return $this->properties
->{$key};
291 * Magic isset method.
293 * PHP needs an isset magic method if you use the get magic method and
294 * still want empty calls to work.
296 * @param string $key $key property name
297 * @return bool|mixed property value, false if property is not exist
299 public function __isset($key) {
300 return !empty($this->properties
->{$key});
304 * Calculate the context value needed for an event.
306 * Event's type can be determine by the available value store in $data
307 * It is important to check for the existence of course/courseid to determine
309 * Default value is set to CONTEXT_USER
311 * @return \stdClass The context object.
313 protected function calculate_context() {
317 if (isset($this->properties
->categoryid
) && $this->properties
->categoryid
> 0) {
318 $context = \context_coursecat
::instance($this->properties
->categoryid
);
319 } else if (isset($this->properties
->courseid
) && $this->properties
->courseid
> 0) {
320 $context = \context_course
::instance($this->properties
->courseid
);
321 } else if (isset($this->properties
->course
) && $this->properties
->course
> 0) {
322 $context = \context_course
::instance($this->properties
->course
);
323 } else if (isset($this->properties
->groupid
) && $this->properties
->groupid
> 0) {
324 $group = $DB->get_record('groups', array('id' => $this->properties
->groupid
));
325 $context = \context_course
::instance($group->courseid
);
326 } else if (isset($this->properties
->userid
) && $this->properties
->userid
> 0
327 && $this->properties
->userid
== $USER->id
) {
328 $context = \context_user
::instance($this->properties
->userid
);
329 } else if (isset($this->properties
->userid
) && $this->properties
->userid
> 0
330 && $this->properties
->userid
!= $USER->id
&&
331 isset($this->properties
->instance
) && $this->properties
->instance
> 0) {
332 $cm = get_coursemodule_from_instance($this->properties
->modulename
, $this->properties
->instance
, 0,
334 $context = \context_course
::instance($cm->course
);
336 $context = \context_user
::instance($this->properties
->userid
);
343 * Returns the context for this event. The context is calculated
344 * the first time is is requested and then stored in a member
345 * variable to be returned each subsequent time.
347 * This is a magical getter function that will be called when
348 * ever the context property is accessed, e.g. $event->context.
352 protected function get_context() {
353 if (!isset($this->properties
->context
)) {
354 $this->properties
->context
= $this->calculate_context();
357 return $this->properties
->context
;
361 * Returns an array of editoroptions for this event.
363 * @return array event editor options
365 protected function get_editoroptions() {
366 return $this->editoroptions
;
370 * Returns an event description: Called by __get
371 * Please use $blah = $event->description;
373 * @return string event description
375 protected function get_description() {
378 require_once($CFG->libdir
. '/filelib.php');
380 if ($this->_description
=== null) {
381 // Check if we have already resolved the context for this event.
382 if ($this->editorcontext
=== null) {
383 // Switch on the event type to decide upon the appropriate context to use for this event.
384 $this->editorcontext
= $this->get_context();
385 if (!calendar_is_valid_eventtype($this->properties
->eventtype
)) {
386 return clean_text($this->properties
->description
, $this->properties
->format
);
390 // Work out the item id for the editor, if this is a repeated event
391 // then the files will be associated with the original.
392 if (!empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
393 $itemid = $this->properties
->repeatid
;
395 $itemid = $this->properties
->id
;
398 // Convert file paths in the description so that things display correctly.
399 $this->_description
= file_rewrite_pluginfile_urls($this->properties
->description
, 'pluginfile.php',
400 $this->editorcontext
->id
, 'calendar', 'event_description', $itemid);
401 // Clean the text so no nasties get through.
402 $this->_description
= clean_text($this->_description
, $this->properties
->format
);
405 // Finally return the description.
406 return $this->_description
;
410 * Return the number of repeat events there are in this events series.
412 * @return int number of event repeated
414 public function count_repeats() {
416 if (!empty($this->properties
->repeatid
)) {
417 $this->properties
->eventrepeats
= $DB->count_records('event',
418 array('repeatid' => $this->properties
->repeatid
));
419 // We don't want to count ourselves.
420 $this->properties
->eventrepeats
--;
422 return $this->properties
->eventrepeats
;
426 * Update or create an event within the database
428 * Pass in a object containing the event properties and this function will
429 * insert it into the database and deal with any associated files
431 * @see self::create()
432 * @see self::update()
434 * @param \stdClass $data object of event
435 * @param bool $checkcapability if moodle should check calendar managing capability or not
436 * @return bool event updated
438 public function update($data, $checkcapability=true) {
441 foreach ($data as $key => $value) {
442 $this->properties
->$key = $value;
445 $this->properties
->timemodified
= time();
446 $usingeditor = (!empty($this->properties
->description
) && is_array($this->properties
->description
));
448 // Prepare event data.
450 'context' => $this->get_context(),
451 'objectid' => $this->properties
->id
,
453 'repeatid' => empty($this->properties
->repeatid
) ?
0 : $this->properties
->repeatid
,
454 'timestart' => $this->properties
->timestart
,
455 'name' => $this->properties
->name
459 if (empty($this->properties
->id
) ||
$this->properties
->id
< 1) {
460 if ($checkcapability) {
461 if (!calendar_add_event_allowed($this->properties
)) {
462 print_error('nopermissiontoupdatecalendar');
467 switch ($this->properties
->eventtype
) {
469 $this->properties
->courseid
= 0;
470 $this->properties
->course
= 0;
471 $this->properties
->groupid
= 0;
472 $this->properties
->userid
= $USER->id
;
475 $this->properties
->courseid
= SITEID
;
476 $this->properties
->course
= SITEID
;
477 $this->properties
->groupid
= 0;
478 $this->properties
->userid
= $USER->id
;
481 $this->properties
->groupid
= 0;
482 $this->properties
->userid
= $USER->id
;
485 $this->properties
->groupid
= 0;
486 $this->properties
->category
= 0;
487 $this->properties
->userid
= $USER->id
;
490 $this->properties
->userid
= $USER->id
;
493 // We should NEVER get here, but just incase we do lets fail gracefully.
494 $usingeditor = false;
498 // If we are actually using the editor, we recalculate the context because some default values
499 // were set when calculate_context() was called from the constructor.
501 $this->properties
->context
= $this->calculate_context();
502 $this->editorcontext
= $this->get_context();
505 $editor = $this->properties
->description
;
506 $this->properties
->format
= $this->properties
->description
['format'];
507 $this->properties
->description
= $this->properties
->description
['text'];
510 // Insert the event into the database.
511 $this->properties
->id
= $DB->insert_record('event', $this->properties
);
514 $this->properties
->description
= file_save_draft_area_files(
516 $this->editorcontext
->id
,
519 $this->properties
->id
,
520 $this->editoroptions
,
522 $this->editoroptions
['forcehttps']);
523 $DB->set_field('event', 'description', $this->properties
->description
,
524 array('id' => $this->properties
->id
));
527 // Log the event entry.
528 $eventargs['objectid'] = $this->properties
->id
;
529 $eventargs['context'] = $this->get_context();
530 $event = \core\event\calendar_event_created
::create($eventargs);
533 $repeatedids = array();
535 if (!empty($this->properties
->repeat
)) {
536 $this->properties
->repeatid
= $this->properties
->id
;
537 $DB->set_field('event', 'repeatid', $this->properties
->repeatid
, array('id' => $this->properties
->id
));
539 $eventcopy = clone($this->properties
);
540 unset($eventcopy->id
);
542 $timestart = new \
DateTime('@' . $eventcopy->timestart
);
543 $timestart->setTimezone(\core_date
::get_user_timezone_object());
545 for ($i = 1; $i < $eventcopy->repeats
; $i++
) {
547 $timestart->add(new \
DateInterval('P7D'));
548 $eventcopy->timestart
= $timestart->getTimestamp();
550 // Get the event id for the log record.
551 $eventcopyid = $DB->insert_record('event', $eventcopy);
553 // If the context has been set delete all associated files.
555 $fs = get_file_storage();
556 $files = $fs->get_area_files($this->editorcontext
->id
, 'calendar', 'event_description',
557 $this->properties
->id
);
558 foreach ($files as $file) {
559 $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
563 $repeatedids[] = $eventcopyid;
566 $eventargs['objectid'] = $eventcopyid;
567 $eventargs['other']['timestart'] = $eventcopy->timestart
;
568 $event = \core\event\calendar_event_created
::create($eventargs);
576 if ($checkcapability) {
577 if (!calendar_edit_event_allowed($this->properties
)) {
578 print_error('nopermissiontoupdatecalendar');
583 if ($this->editorcontext
!== null) {
584 $this->properties
->description
= file_save_draft_area_files(
585 $this->properties
->description
['itemid'],
586 $this->editorcontext
->id
,
589 $this->properties
->id
,
590 $this->editoroptions
,
591 $this->properties
->description
['text'],
592 $this->editoroptions
['forcehttps']);
594 $this->properties
->format
= $this->properties
->description
['format'];
595 $this->properties
->description
= $this->properties
->description
['text'];
599 $event = $DB->get_record('event', array('id' => $this->properties
->id
));
601 $updaterepeated = (!empty($this->properties
->repeatid
) && !empty($this->properties
->repeateditall
));
603 if ($updaterepeated) {
605 if ($this->properties
->timestart
!= $event->timestart
) {
606 $timestartoffset = $this->properties
->timestart
- $event->timestart
;
607 $sql = "UPDATE {event}
610 timestart = timestart + ?,
616 // Note: Group and course id may not be set. If not, keep their current values.
618 $this->properties
->name
,
619 $this->properties
->description
,
621 $this->properties
->timeduration
,
623 isset($this->properties
->groupid
) ?
$this->properties
->groupid
: $event->groupid
,
624 isset($this->properties
->courseid
) ?
$this->properties
->courseid
: $event->courseid
,
628 $sql = "UPDATE {event}
636 // Note: Group and course id may not be set. If not, keep their current values.
638 $this->properties
->name
,
639 $this->properties
->description
,
640 $this->properties
->timeduration
,
642 isset($this->properties
->groupid
) ?
$this->properties
->groupid
: $event->groupid
,
643 isset($this->properties
->courseid
) ?
$this->properties
->courseid
: $event->courseid
,
647 $DB->execute($sql, $params);
649 // Trigger an update event for each of the calendar event.
650 $events = $DB->get_records('event', array('repeatid' => $event->repeatid
), '', '*');
651 foreach ($events as $calendarevent) {
652 $eventargs['objectid'] = $calendarevent->id
;
653 $eventargs['other']['timestart'] = $calendarevent->timestart
;
654 $event = \core\event\calendar_event_updated
::create($eventargs);
655 $event->add_record_snapshot('event', $calendarevent);
659 $DB->update_record('event', $this->properties
);
660 $event = self
::load($this->properties
->id
);
661 $this->properties
= $event->properties();
663 // Trigger an update event.
664 $event = \core\event\calendar_event_updated
::create($eventargs);
665 $event->add_record_snapshot('event', $this->properties
);
674 * Deletes an event and if selected an repeated events in the same series
676 * This function deletes an event, any associated events if $deleterepeated=true,
677 * and cleans up any files associated with the events.
679 * @see self::delete()
681 * @param bool $deleterepeated delete event repeatedly
682 * @return bool succession of deleting event
684 public function delete($deleterepeated = false) {
687 // If $this->properties->id is not set then something is wrong.
688 if (empty($this->properties
->id
)) {
689 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER
);
692 $calevent = $DB->get_record('event', array('id' => $this->properties
->id
), '*', MUST_EXIST
);
694 $DB->delete_records('event', array('id' => $this->properties
->id
));
696 // Trigger an event for the delete action.
698 'context' => $this->get_context(),
699 'objectid' => $this->properties
->id
,
701 'repeatid' => empty($this->properties
->repeatid
) ?
0 : $this->properties
->repeatid
,
702 'timestart' => $this->properties
->timestart
,
703 'name' => $this->properties
->name
705 $event = \core\event\calendar_event_deleted
::create($eventargs);
706 $event->add_record_snapshot('event', $calevent);
709 // If we are deleting parent of a repeated event series, promote the next event in the series as parent.
710 if (($this->properties
->id
== $this->properties
->repeatid
) && !$deleterepeated) {
711 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC",
712 array($this->properties
->id
), IGNORE_MULTIPLE
);
713 if (!empty($newparent)) {
714 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?",
715 array($newparent, $this->properties
->id
));
716 // Get all records where the repeatid is the same as the event being removed.
717 $events = $DB->get_records('event', array('repeatid' => $newparent));
718 // For each of the returned events trigger an update event.
719 foreach ($events as $calendarevent) {
720 // Trigger an event for the update.
721 $eventargs['objectid'] = $calendarevent->id
;
722 $eventargs['other']['timestart'] = $calendarevent->timestart
;
723 $event = \core\event\calendar_event_updated
::create($eventargs);
724 $event->add_record_snapshot('event', $calendarevent);
730 // If the editor context hasn't already been set then set it now.
731 if ($this->editorcontext
=== null) {
732 $this->editorcontext
= $this->get_context();
735 // If the context has been set delete all associated files.
736 if ($this->editorcontext
!== null) {
737 $fs = get_file_storage();
738 $files = $fs->get_area_files($this->editorcontext
->id
, 'calendar', 'event_description', $this->properties
->id
);
739 foreach ($files as $file) {
744 // If we need to delete repeated events then we will fetch them all and delete one by one.
745 if ($deleterepeated && !empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
746 // Get all records where the repeatid is the same as the event being removed.
747 $events = $DB->get_records('event', array('repeatid' => $this->properties
->repeatid
));
748 // For each of the returned events populate an event object and call delete.
749 // make sure the arg passed is false as we are already deleting all repeats.
750 foreach ($events as $event) {
751 $event = new calendar_event($event);
752 $event->delete(false);
760 * Fetch all event properties.
762 * This function returns all of the events properties as an object and optionally
763 * can prepare an editor for the description field at the same time. This is
764 * designed to work when the properties are going to be used to set the default
765 * values of a moodle forms form.
767 * @param bool $prepareeditor If set to true a editor is prepared for use with
768 * the mforms editor element. (for description)
769 * @return \stdClass Object containing event properties
771 public function properties($prepareeditor = false) {
774 // First take a copy of the properties. We don't want to actually change the
775 // properties or we'd forever be converting back and forwards between an
776 // editor formatted description and not.
777 $properties = clone($this->properties
);
778 // Clean the description here.
779 $properties->description
= clean_text($properties->description
, $properties->format
);
781 // If set to true we need to prepare the properties for use with an editor
782 // and prepare the file area.
783 if ($prepareeditor) {
785 // We may or may not have a property id. If we do then we need to work
786 // out the context so we can copy the existing files to the draft area.
787 if (!empty($properties->id
)) {
789 if ($properties->eventtype
=== 'site') {
791 $this->editorcontext
= $this->get_context();
792 } else if ($properties->eventtype
=== 'user') {
794 $this->editorcontext
= $this->get_context();
795 } else if ($properties->eventtype
=== 'group' ||
$properties->eventtype
=== 'course') {
796 // First check the course is valid.
797 $course = $DB->get_record('course', array('id' => $properties->courseid
));
799 print_error('invalidcourse');
802 $this->editorcontext
= $this->get_context();
803 // We have a course and are within the course context so we had
804 // better use the courses max bytes value.
805 $this->editoroptions
['maxbytes'] = $course->maxbytes
;
806 } else if ($properties->eventtype
=== 'category') {
807 // First check the course is valid.
808 \coursecat
::get($properties->categoryid
, MUST_EXIST
, true);
810 $this->editorcontext
= $this->get_context();
812 // If we get here we have a custom event type as used by some
813 // modules. In this case the event will have been added by
814 // code and we won't need the editor.
815 $this->editoroptions
['maxbytes'] = 0;
816 $this->editoroptions
['maxfiles'] = 0;
819 if (empty($this->editorcontext
) ||
empty($this->editorcontext
->id
)) {
822 // Get the context id that is what we really want.
823 $contextid = $this->editorcontext
->id
;
827 // If we get here then this is a new event in which case we don't need a
828 // context as there is no existing files to copy to the draft area.
832 // If the contextid === false we don't support files so no preparing
834 if ($contextid !== false) {
835 // Just encase it has already been submitted.
836 $draftiddescription = file_get_submitted_draft_itemid('description');
837 // Prepare the draft area, this copies existing files to the draft area as well.
838 $properties->description
= file_prepare_draft_area($draftiddescription, $contextid, 'calendar',
839 'event_description', $properties->id
, $this->editoroptions
, $properties->description
);
841 $draftiddescription = 0;
844 // Structure the description field as the editor requires.
845 $properties->description
= array('text' => $properties->description
, 'format' => $properties->format
,
846 'itemid' => $draftiddescription);
849 // Finally return the properties.
854 * Toggles the visibility of an event
856 * @param null|bool $force If it is left null the events visibility is flipped,
857 * If it is false the event is made hidden, if it is true it
859 * @return bool if event is successfully updated, toggle will be visible
861 public function toggle_visibility($force = null) {
864 // Set visible to the default if it is not already set.
865 if (empty($this->properties
->visible
)) {
866 $this->properties
->visible
= 1;
869 if ($force === true ||
($force !== false && $this->properties
->visible
== 0)) {
870 // Make this event visible.
871 $this->properties
->visible
= 1;
873 // Make this event hidden.
874 $this->properties
->visible
= 0;
877 // Update the database to reflect this change.
878 $success = $DB->set_field('event', 'visible', $this->properties
->visible
, array('id' => $this->properties
->id
));
879 $calendarevent = $DB->get_record('event', array('id' => $this->properties
->id
), '*', MUST_EXIST
);
881 // Prepare event data.
883 'context' => $this->get_context(),
884 'objectid' => $this->properties
->id
,
886 'repeatid' => empty($this->properties
->repeatid
) ?
0 : $this->properties
->repeatid
,
887 'timestart' => $this->properties
->timestart
,
888 'name' => $this->properties
->name
891 $event = \core\event\calendar_event_updated
::create($eventargs);
892 $event->add_record_snapshot('event', $calendarevent);
899 * Returns an event object when provided with an event id.
901 * This function makes use of MUST_EXIST, if the event id passed in is invalid
902 * it will result in an exception being thrown.
904 * @param int|object $param event object or event id
905 * @return calendar_event
907 public static function load($param) {
909 if (is_object($param)) {
910 $event = new calendar_event($param);
912 $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST
);
913 $event = new calendar_event($event);
919 * Creates a new event and returns an event object
921 * @param \stdClass|array $properties An object containing event properties
922 * @param bool $checkcapability Check caps or not
923 * @throws \coding_exception
925 * @return calendar_event|bool The event object or false if it failed
927 public static function create($properties, $checkcapability = true) {
928 if (is_array($properties)) {
929 $properties = (object)$properties;
931 if (!is_object($properties)) {
932 throw new \
coding_exception('When creating an event properties should be either an object or an assoc array');
934 $event = new calendar_event($properties);
935 if ($event->update($properties, $checkcapability)) {
943 * Format the text using the external API.
945 * This function should we used when text formatting is required in external functions.
947 * @return array an array containing the text formatted and the text format
949 public function format_external_text() {
951 if ($this->editorcontext
=== null) {
952 // Switch on the event type to decide upon the appropriate context to use for this event.
953 $this->editorcontext
= $this->get_context();
955 if (!calendar_is_valid_eventtype($this->properties
->eventtype
)) {
956 // We don't have a context here, do a normal format_text.
957 return external_format_text($this->properties
->description
, $this->properties
->format
, $this->editorcontext
->id
);
961 // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
962 if (!empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
963 $itemid = $this->properties
->repeatid
;
965 $itemid = $this->properties
->id
;
968 return external_format_text($this->properties
->description
, $this->properties
->format
, $this->editorcontext
->id
,
969 'calendar', 'event_description', $itemid);
974 * Calendar information class
976 * This class is used simply to organise the information pertaining to a calendar
977 * and is used primarily to make information easily available.
979 * @package core_calendar
981 * @copyright 2010 Sam Hemelryk
982 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
984 class calendar_information
{
987 * @var int The timestamp
989 * Rather than setting the day, month and year we will set a timestamp which will be able
990 * to be used by multiple calendars.
994 /** @var int A course id */
995 public $courseid = null;
997 /** @var array An array of categories */
998 public $categories = array();
1000 /** @var int The current category */
1001 public $categoryid = null;
1003 /** @var array An array of courses */
1004 public $courses = array();
1006 /** @var array An array of groups */
1007 public $groups = array();
1009 /** @var array An array of users */
1010 public $users = array();
1012 /** @var context The anticipated context that the calendar is viewed in */
1013 public $context = null;
1016 * Creates a new instance
1018 * @param int $day the number of the day
1019 * @param int $month the number of the month
1020 * @param int $year the number of the year
1021 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
1022 * and $calyear to support multiple calendars
1024 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
1025 // If a day, month and year were passed then convert it to a timestamp. If these were passed
1026 // then we can assume the day, month and year are passed as Gregorian, as no where in core
1027 // should we be passing these values rather than the time. This is done for BC.
1028 if (!empty($day) ||
!empty($month) ||
!empty($year)) {
1029 $date = usergetdate(time());
1031 $day = $date['mday'];
1033 if (empty($month)) {
1034 $month = $date['mon'];
1037 $year = $date['year'];
1039 if (checkdate($month, $day, $year)) {
1040 $time = make_timestamp($year, $month, $day);
1046 $this->set_time($time);
1050 * Creates and set up a instance.
1052 * @param int $time the unixtimestamp representing the date we want to view.
1053 * @param int $courseid The ID of the course the user wishes to view.
1054 * @param int $categoryid The ID of the category the user wishes to view
1055 * If a courseid is specified, this value is ignored.
1056 * @return calendar_information
1058 public static function create($time, int $courseid, int $categoryid = null) : calendar_information
{
1059 $calendar = new static(0, 0, 0, $time);
1060 if ($courseid != SITEID
&& !empty($courseid)) {
1061 // Course ID must be valid and existing.
1062 $course = get_course($courseid);
1063 $calendar->context
= context_course
::instance($course->id
);
1065 if (!$course->visible
&& !is_role_switched($course->id
)) {
1066 require_capability('moodle/course:viewhiddencourses', $calendar->context
);
1069 $courses = [$course->id
=> $course];
1070 $category = (\coursecat
::get($course->category
, MUST_EXIST
, true))->get_db_record();
1071 } else if (!empty($categoryid)) {
1072 $course = get_site();
1073 $courses = calendar_get_default_courses();
1075 // Filter available courses to those within this category or it's children.
1076 $ids = [$categoryid];
1077 $category = \coursecat
::get($categoryid);
1078 $ids = array_merge($ids, array_keys($category->get_children()));
1079 $courses = array_filter($courses, function($course) use ($ids) {
1080 return array_search($course->category
, $ids) !== false;
1082 $category = $category->get_db_record();
1084 $calendar->context
= context_coursecat
::instance($categoryid);
1086 $course = get_site();
1087 $courses = calendar_get_default_courses();
1090 $calendar->context
= context_system
::instance();
1093 $calendar->set_sources($course, $courses, $category);
1099 * Set the time period of this instance.
1101 * @param int $time the unixtimestamp representing the date we want to view.
1104 public function set_time($time = null) {
1106 $this->time
= time();
1108 $this->time
= $time;
1115 * Initialize calendar information
1118 * @param stdClass $course object
1119 * @param array $coursestoload An array of courses [$course->id => $course]
1120 * @param bool $ignorefilters options to use filter
1122 public function prepare_for_view(stdClass
$course, array $coursestoload, $ignorefilters = false) {
1123 debugging('The prepare_for_view() function has been deprecated. Please update your code to use set_sources()',
1125 $this->set_sources($course, $coursestoload);
1129 * Set the sources for events within the calendar.
1131 * If no category is provided, then the category path for the current
1132 * course will be used.
1134 * @param stdClass $course The current course being viewed.
1135 * @param stdClass[] $courses The list of all courses currently accessible.
1136 * @param stdClass $category The current category to show.
1138 public function set_sources(stdClass
$course, array $courses, stdClass
$category = null) {
1141 // A cousre must always be specified.
1142 $this->course
= $course;
1143 $this->courseid
= $course->id
;
1145 list($courseids, $group, $user) = calendar_set_filters($courses);
1146 $this->courses
= $courseids;
1147 $this->groups
= $group;
1148 $this->users
= $user;
1150 // Do not show category events by default.
1151 $this->categoryid
= null;
1152 $this->categories
= null;
1154 // Determine the correct category information to show.
1155 // When called with a course, the category of that course is usually included too.
1156 // When a category was specifically requested, it should be requested with the site id.
1157 if (SITEID
!== $this->courseid
) {
1158 // A specific course was requested.
1159 // Fetch the category that this course is in, along with all parents.
1160 // Do not include child categories of this category, as the user many not have enrolments in those siblings or children.
1161 $category = \coursecat
::get($course->category
, MUST_EXIST
, true);
1162 $this->categoryid
= $category->id
;
1164 $this->categories
= $category->get_parents();
1165 $this->categories
[] = $category->id
;
1166 } else if (null !== $category && $category->id
> 0) {
1167 // A specific category was requested.
1168 // Fetch all parents of this category, along with all children too.
1169 $category = \coursecat
::get($category->id
);
1170 $this->categoryid
= $category->id
;
1172 // Build the category list.
1173 // This includes the current category.
1174 $this->categories
= $category->get_parents();
1175 $this->categories
[] = $category->id
;
1176 $this->categories
= array_merge($this->categories
, $category->get_all_children_ids());
1177 } else if (SITEID
=== $this->courseid
) {
1178 // The site was requested.
1179 // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
1181 // Grab the list of categories that this user has courses in.
1182 $coursecategories = array_flip(array_map(function($course) {
1183 return $course->category
;
1186 $calcatcache = cache
::make('core', 'calendar_categories');
1187 $this->categories
= $calcatcache->get('site');
1188 if ($this->categories
=== false) {
1189 // Use the category id as the key in the following array. That way we do not have to remove duplicates.
1191 foreach (\coursecat
::get_all() as $category) {
1192 if (isset($coursecategories[$category->id
]) ||
1193 has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
1194 // If the user has access to a course in this category or can manage the category,
1195 // then they can see all parent categories too.
1196 $categories[$category->id
] = true;
1197 foreach ($category->get_parents() as $catid) {
1198 $categories[$catid] = true;
1202 $this->categories
= array_keys($categories);
1203 $calcatcache->set('site', $this->categories
);
1209 * Ensures the date for the calendar is correct and either sets it to now
1210 * or throws a moodle_exception if not
1212 * @param bool $defaultonow use current time
1213 * @throws moodle_exception
1214 * @return bool validation of checkdate
1216 public function checkdate($defaultonow = true) {
1217 if (!checkdate($this->month
, $this->day
, $this->year
)) {
1219 $now = usergetdate(time());
1220 $this->day
= intval($now['mday']);
1221 $this->month
= intval($now['mon']);
1222 $this->year
= intval($now['year']);
1225 throw new moodle_exception('invaliddate');
1232 * Gets todays timestamp for the calendar
1234 * @return int today timestamp
1236 public function timestamp_today() {
1240 * Gets tomorrows timestamp for the calendar
1242 * @return int tomorrow timestamp
1244 public function timestamp_tomorrow() {
1245 return strtotime('+1 day', $this->time
);
1248 * Adds the pretend blocks for the calendar
1250 * @param core_calendar_renderer $renderer
1251 * @param bool $showfilters display filters, false is set as default
1252 * @param string|null $view preference view options (eg: day, month, upcoming)
1254 public function add_sidecalendar_blocks(core_calendar_renderer
$renderer, $showfilters=false, $view=null) {
1256 $filters = new block_contents();
1257 $filters->content
= $renderer->event_filter();
1258 $filters->footer
= '';
1259 $filters->title
= get_string('eventskey', 'calendar');
1260 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT
);
1262 $block = new block_contents
;
1263 $block->content
= $renderer->fake_block_threemonths($this);
1264 $block->footer
= '';
1265 $block->title
= get_string('monthlyview', 'calendar');
1266 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT
);
1271 * Get calendar events.
1273 * @param int $tstart Start time of time range for events
1274 * @param int $tend End time of time range for events
1275 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
1276 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
1277 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
1278 * @param boolean $withduration whether only events starting within time range selected
1279 * or events in progress/already started selected as well
1280 * @param boolean $ignorehidden whether to select only visible events or all events
1281 * @param array|int|boolean $categories array of categories, category id or boolean for all/no course events
1282 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
1284 function calendar_get_events($tstart, $tend, $users, $groups, $courses,
1285 $withduration = true, $ignorehidden = true, $categories = []) {
1291 if (empty($users) && empty($groups) && empty($courses) && empty($categories)) {
1295 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
1296 // Events from a number of users
1297 if(!empty($whereclause)) $whereclause .= ' OR';
1298 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED
);
1299 $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)";
1300 $params = array_merge($params, $inparamsusers);
1301 } else if($users === true) {
1302 // Events from ALL users
1303 if(!empty($whereclause)) $whereclause .= ' OR';
1304 $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)';
1305 } else if($users === false) {
1306 // No user at all, do nothing
1309 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
1310 // Events from a number of groups
1311 if(!empty($whereclause)) $whereclause .= ' OR';
1312 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED
);
1313 $whereclause .= " e.groupid $insqlgroups ";
1314 $params = array_merge($params, $inparamsgroups);
1315 } else if($groups === true) {
1316 // Events from ALL groups
1317 if(!empty($whereclause)) $whereclause .= ' OR ';
1318 $whereclause .= ' e.groupid != 0';
1320 // boolean false (no groups at all): we don't need to do anything
1322 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
1323 if(!empty($whereclause)) $whereclause .= ' OR';
1324 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED
);
1325 $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
1326 $params = array_merge($params, $inparamscourses);
1327 } else if ($courses === true) {
1328 // Events from ALL courses
1329 if(!empty($whereclause)) $whereclause .= ' OR';
1330 $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
1333 if ((is_array($categories) && !empty($categories)) ||
is_numeric($categories)) {
1334 if (!empty($whereclause)) {
1335 $whereclause .= ' OR';
1337 list($insqlcategories, $inparamscategories) = $DB->get_in_or_equal($categories, SQL_PARAMS_NAMED
);
1338 $whereclause .= " (e.groupid = 0 AND e.courseid = 0 AND e.categoryid $insqlcategories)";
1339 $params = array_merge($params, $inparamscategories);
1340 } else if ($categories === true) {
1341 // Events from ALL categories.
1342 if (!empty($whereclause)) {
1343 $whereclause .= ' OR';
1345 $whereclause .= ' (e.groupid = 0 AND e.courseid = 0 AND e.categoryid != 0)';
1348 // Security check: if, by now, we have NOTHING in $whereclause, then it means
1349 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
1350 // events no matter what. Allowing the code to proceed might return a completely
1351 // valid query with only time constraints, thus selecting ALL events in that time frame!
1352 if(empty($whereclause)) {
1357 $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1360 $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1362 if(!empty($whereclause)) {
1363 // We have additional constraints
1364 $whereclause = $timeclause.' AND ('.$whereclause.')';
1367 // Just basic time filtering
1368 $whereclause = $timeclause;
1371 if ($ignorehidden) {
1372 $whereclause .= ' AND e.visible = 1';
1377 LEFT JOIN {modules} m ON e.modulename = m.name
1378 -- Non visible modules will have a value of 0.
1379 WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
1380 ORDER BY e.timestart";
1381 $events = $DB->get_records_sql($sql, $params);
1383 if ($events === false) {
1390 * Return the days of the week.
1392 * @return array array of days
1394 function calendar_get_days() {
1395 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1396 return $calendartype->get_weekdays();
1400 * Get the subscription from a given id.
1403 * @param int $id id of the subscription
1404 * @return stdClass Subscription record from DB
1405 * @throws moodle_exception for an invalid id
1407 function calendar_get_subscription($id) {
1410 $cache = \cache
::make('core', 'calendar_subscriptions');
1411 $subscription = $cache->get($id);
1412 if (empty($subscription)) {
1413 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST
);
1414 $cache->set($id, $subscription);
1417 return $subscription;
1421 * Gets the first day of the week.
1423 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
1427 function calendar_get_starting_weekday() {
1428 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1429 return $calendartype->get_starting_weekday();
1433 * Get a HTML link to a course.
1435 * @param int|stdClass $course the course id or course object
1436 * @return string a link to the course (as HTML); empty if the course id is invalid
1438 function calendar_get_courselink($course) {
1443 if (!is_object($course)) {
1444 $course = calendar_get_course_cached($coursecache, $course);
1446 $context = \context_course
::instance($course->id
);
1447 $fullname = format_string($course->fullname
, true, array('context' => $context));
1448 $url = new \
moodle_url('/course/view.php', array('id' => $course->id
));
1449 $link = \html_writer
::link($url, $fullname);
1455 * Get current module cache.
1457 * Only use this method if you do not know courseid. Otherwise use:
1458 * get_fast_modinfo($courseid)->instances[$modulename][$instance]
1460 * @param array $modulecache in memory module cache
1461 * @param string $modulename name of the module
1462 * @param int $instance module instance number
1463 * @return stdClass|bool $module information
1465 function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
1466 if (!isset($modulecache[$modulename . '_' . $instance])) {
1467 $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
1470 return $modulecache[$modulename . '_' . $instance];
1474 * Get current course cache.
1476 * @param array $coursecache list of course cache
1477 * @param int $courseid id of the course
1478 * @return stdClass $coursecache[$courseid] return the specific course cache
1480 function calendar_get_course_cached(&$coursecache, $courseid) {
1481 if (!isset($coursecache[$courseid])) {
1482 $coursecache[$courseid] = get_course($courseid);
1484 return $coursecache[$courseid];
1488 * Get group from groupid for calendar display
1490 * @param int $groupid
1491 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1493 function calendar_get_group_cached($groupid) {
1494 static $groupscache = array();
1495 if (!isset($groupscache[$groupid])) {
1496 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1498 return $groupscache[$groupid];
1502 * Add calendar event metadata
1504 * @param stdClass $event event info
1505 * @return stdClass $event metadata
1507 function calendar_add_event_metadata($event) {
1508 global $CFG, $OUTPUT;
1510 // Support multilang in event->name.
1511 $event->name
= format_string($event->name
, true);
1513 if (!empty($event->modulename
)) { // Activity event.
1514 // The module name is set. I will assume that it has to be displayed, and
1515 // also that it is an automatically-generated event. And of course that the
1516 // instace id and modulename are set correctly.
1517 $instances = get_fast_modinfo($event->courseid
)->get_instances_of($event->modulename
);
1518 if (!array_key_exists($event->instance
, $instances)) {
1521 $module = $instances[$event->instance
];
1523 $modulename = $module->get_module_type_name(false);
1524 if (get_string_manager()->string_exists($event->eventtype
, $event->modulename
)) {
1525 // Will be used as alt text if the event icon.
1526 $eventtype = get_string($event->eventtype
, $event->modulename
);
1531 $event->icon
= '<img src="' . s($module->get_icon_url()) . '" alt="' . s($eventtype) .
1532 '" title="' . s($modulename) . '" class="icon" />';
1533 $event->referer
= html_writer
::link($module->url
, $event->name
);
1534 $event->courselink
= calendar_get_courselink($module->get_course());
1535 $event->cmid
= $module->id
;
1536 } else if ($event->courseid
== SITEID
) { // Site event.
1537 $event->icon
= '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
1538 get_string('globalevent', 'calendar') . '" class="icon" />';
1539 $event->cssclass
= 'calendar_event_global';
1540 } else if ($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) { // Course event.
1541 $event->icon
= '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
1542 get_string('courseevent', 'calendar') . '" class="icon" />';
1543 $event->courselink
= calendar_get_courselink($event->courseid
);
1544 $event->cssclass
= 'calendar_event_course';
1545 } else if ($event->groupid
) { // Group event.
1546 if ($group = calendar_get_group_cached($event->groupid
)) {
1547 $groupname = format_string($group->name
, true, \context_course
::instance($group->courseid
));
1551 $event->icon
= \html_writer
::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
1552 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
1553 $event->courselink
= calendar_get_courselink($event->courseid
) . ', ' . $groupname;
1554 $event->cssclass
= 'calendar_event_group';
1555 } else if ($event->userid
) { // User event.
1556 $event->icon
= '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
1557 get_string('userevent', 'calendar') . '" class="icon" />';
1558 $event->cssclass
= 'calendar_event_user';
1565 * Get calendar events by id.
1568 * @param array $eventids list of event ids
1569 * @return array Array of event entries, empty array if nothing found
1571 function calendar_get_events_by_id($eventids) {
1574 if (!is_array($eventids) ||
empty($eventids)) {
1578 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
1579 $wheresql = "id $wheresql";
1581 return $DB->get_records_select('event', $wheresql, $params);
1585 * Get control options for calendar.
1587 * @param string $type of calendar
1588 * @param array $data calendar information
1589 * @return string $content return available control for the calender in html
1591 function calendar_top_controls($type, $data) {
1592 global $PAGE, $OUTPUT;
1594 // Get the calendar type we are using.
1595 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1599 // Ensure course id passed if relevant.
1601 if (!empty($data['id'])) {
1602 $courseid = '&course=' . $data['id'];
1605 // If we are passing a month and year then we need to convert this to a timestamp to
1606 // support multiple calendars. No where in core should these be passed, this logic
1607 // here is for third party plugins that may use this function.
1608 if (!empty($data['m']) && !empty($date['y'])) {
1609 if (!isset($data['d'])) {
1612 if (!checkdate($data['m'], $data['d'], $data['y'])) {
1615 $time = make_timestamp($data['y'], $data['m'], $data['d']);
1617 } else if (!empty($data['time'])) {
1618 $time = $data['time'];
1623 // Get the date for the calendar type.
1624 $date = $calendartype->timestamp_to_date_array($time);
1626 $urlbase = $PAGE->url
;
1628 // We need to get the previous and next months in certain cases.
1629 if ($type == 'frontpage' ||
$type == 'course' ||
$type == 'month') {
1630 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1631 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
1632 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
1633 $prevmonthtime['hour'], $prevmonthtime['minute']);
1635 $nextmonth = calendar_add_month($date['mon'], $date['year']);
1636 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
1637 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
1638 $nextmonthtime['hour'], $nextmonthtime['minute']);
1643 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1644 true, $prevmonthtime);
1645 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true,
1647 $calendarlink = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', array('view' => 'month')),
1648 false, false, false, $time);
1650 if (!empty($data['id'])) {
1651 $calendarlink->param('course', $data['id']);
1656 $content .= \html_writer
::start_tag('div', array('class' => 'calendar-controls'));
1657 $content .= $prevlink . '<span class="hide"> | </span>';
1658 $content .= \html_writer
::tag('span', \html_writer
::link($calendarlink,
1659 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1660 ), array('class' => 'current'));
1661 $content .= '<span class="hide"> | </span>' . $right;
1662 $content .= "<span class=\"clearer\"><!-- --></span>\n";
1663 $content .= \html_writer
::end_tag('div');
1667 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1668 true, $prevmonthtime);
1669 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false,
1670 true, $nextmonthtime);
1671 $calendarlink = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', array('view' => 'month')),
1672 false, false, false, $time);
1674 if (!empty($data['id'])) {
1675 $calendarlink->param('course', $data['id']);
1678 $content .= \html_writer
::start_tag('div', array('class' => 'calendar-controls'));
1679 $content .= $prevlink . '<span class="hide"> | </span>';
1680 $content .= \html_writer
::tag('span', \html_writer
::link($calendarlink,
1681 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1682 ), array('class' => 'current'));
1683 $content .= '<span class="hide"> | </span>' . $nextlink;
1684 $content .= "<span class=\"clearer\"><!-- --></span>";
1685 $content .= \html_writer
::end_tag('div');
1688 $calendarlink = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', array('view' => 'upcoming')),
1689 false, false, false, $time);
1690 if (!empty($data['id'])) {
1691 $calendarlink->param('course', $data['id']);
1693 $calendarlink = \html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1694 $content .= \html_writer
::tag('div', $calendarlink, array('class' => 'centered'));
1697 $calendarlink = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', array('view' => 'month')),
1698 false, false, false, $time);
1699 if (!empty($data['id'])) {
1700 $calendarlink->param('course', $data['id']);
1702 $calendarlink = \html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1703 $content .= \html_writer
::tag('h3', $calendarlink);
1706 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1707 'view.php?view=month' . $courseid . '&', false, false, false, false, $prevmonthtime);
1708 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1709 'view.php?view=month' . $courseid . '&', false, false, false, false, $nextmonthtime);
1711 $content .= \html_writer
::start_tag('div', array('class' => 'calendar-controls'));
1712 $content .= $prevlink . '<span class="hide"> | </span>';
1713 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1714 $content .= '<span class="hide"> | </span>' . $nextlink;
1715 $content .= '<span class="clearer"><!-- --></span>';
1716 $content .= \html_writer
::end_tag('div')."\n";
1719 $days = calendar_get_days();
1721 $prevtimestamp = strtotime('-1 day', $time);
1722 $nexttimestamp = strtotime('+1 day', $time);
1724 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1725 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1727 $prevname = $days[$prevdate['wday']]['fullname'];
1728 $nextname = $days[$nextdate['wday']]['fullname'];
1729 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&', false, false,
1730 false, false, $prevtimestamp);
1731 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&', false, false, false,
1732 false, $nexttimestamp);
1734 $content .= \html_writer
::start_tag('div', array('class' => 'calendar-controls'));
1735 $content .= $prevlink;
1736 $content .= '<span class="hide"> | </span><span class="current">' .userdate($time,
1737 get_string('strftimedaydate')) . '</span>';
1738 $content .= '<span class="hide"> | </span>' . $nextlink;
1739 $content .= "<span class=\"clearer\"><!-- --></span>";
1740 $content .= \html_writer
::end_tag('div') . "\n";
1749 * Return the representation day.
1751 * @param int $tstamp Timestamp in GMT
1752 * @param int|bool $now current Unix timestamp
1753 * @param bool $usecommonwords
1754 * @return string the formatted date/time
1756 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1757 static $shortformat;
1759 if (empty($shortformat)) {
1760 $shortformat = get_string('strftimedayshort');
1763 if ($now === false) {
1767 // To have it in one place, if a change is needed.
1768 $formal = userdate($tstamp, $shortformat);
1770 $datestamp = usergetdate($tstamp);
1771 $datenow = usergetdate($now);
1773 if ($usecommonwords == false) {
1774 // We don't want words, just a date.
1776 } else if ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1777 return get_string('today', 'calendar');
1778 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1779 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12
1780 && $datenow['yday'] == 1)) {
1781 return get_string('yesterday', 'calendar');
1782 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] +
1 ) ||
1783 ($datestamp['year'] == $datenow['year'] +
1 && $datenow['mday'] == 31 && $datenow['mon'] == 12
1784 && $datestamp['yday'] == 1)) {
1785 return get_string('tomorrow', 'calendar');
1792 * return the formatted representation time.
1795 * @param int $time the timestamp in UTC, as obtained from the database
1796 * @return string the formatted date/time
1798 function calendar_time_representation($time) {
1799 static $langtimeformat = null;
1801 if ($langtimeformat === null) {
1802 $langtimeformat = get_string('strftimetime');
1805 $timeformat = get_user_preferences('calendar_timeformat');
1806 if (empty($timeformat)) {
1807 $timeformat = get_config(null, 'calendar_site_timeformat');
1810 // Allow language customization of selected time format.
1811 if ($timeformat === CALENDAR_TF_12
) {
1812 $timeformat = get_string('strftimetime12', 'langconfig');
1813 } else if ($timeformat === CALENDAR_TF_24
) {
1814 $timeformat = get_string('strftimetime24', 'langconfig');
1817 return userdate($time, empty($timeformat) ?
$langtimeformat : $timeformat);
1821 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1823 * @param string|moodle_url $linkbase
1824 * @param int $d The number of the day.
1825 * @param int $m The number of the month.
1826 * @param int $y The number of the year.
1827 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1828 * $m and $y are kept for backwards compatibility.
1829 * @return moodle_url|null $linkbase
1831 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
1832 if (empty($linkbase)) {
1836 if (!($linkbase instanceof \moodle_url
)) {
1837 $linkbase = new \
moodle_url($linkbase);
1840 $linkbase->param('time', calendar_get_timestamp($d, $m, $y, $time));
1846 * Build and return a previous month HTML link, with an arrow.
1848 * @param string $text The text label.
1849 * @param string|moodle_url $linkbase The URL stub.
1850 * @param int $d The number of the date.
1851 * @param int $m The number of the month.
1852 * @param int $y year The number of the year.
1853 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1854 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1855 * $m and $y are kept for backwards compatibility.
1856 * @return string HTML string.
1858 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1859 $href = calendar_get_link_href(new \
moodle_url($linkbase), $d, $m, $y, $time);
1866 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1867 'data-drop-zone' => 'nav-link',
1870 return link_arrow_left($text, $href->out(false), $accesshide, 'previous', $attrs);
1874 * Build and return a next month HTML link, with an arrow.
1876 * @param string $text The text label.
1877 * @param string|moodle_url $linkbase The URL stub.
1878 * @param int $d the number of the Day
1879 * @param int $m The number of the month.
1880 * @param int $y The number of the year.
1881 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1882 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1883 * $m and $y are kept for backwards compatibility.
1884 * @return string HTML string.
1886 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1887 $href = calendar_get_link_href(new \
moodle_url($linkbase), $d, $m, $y, $time);
1894 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
1895 'data-drop-zone' => 'nav-link',
1898 return link_arrow_right($text, $href->out(false), $accesshide, 'next', $attrs);
1902 * Return the number of days in month.
1904 * @param int $month the number of the month.
1905 * @param int $year the number of the year
1908 function calendar_days_in_month($month, $year) {
1909 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1910 return $calendartype->get_num_days_in_month($year, $month);
1914 * Get the next following month.
1916 * @param int $month the number of the month.
1917 * @param int $year the number of the year.
1918 * @return array the following month
1920 function calendar_add_month($month, $year) {
1921 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1922 return $calendartype->get_next_month($year, $month);
1926 * Get the previous month.
1928 * @param int $month the number of the month.
1929 * @param int $year the number of the year.
1930 * @return array previous month
1932 function calendar_sub_month($month, $year) {
1933 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1934 return $calendartype->get_prev_month($year, $month);
1938 * Get per-day basis events
1940 * @param array $events list of events
1941 * @param int $month the number of the month
1942 * @param int $year the number of the year
1943 * @param array $eventsbyday event on specific day
1944 * @param array $durationbyday duration of the event in days
1945 * @param array $typesbyday event type (eg: global, course, user, or group)
1946 * @param array $courses list of courses
1949 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1950 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1952 $eventsbyday = array();
1953 $typesbyday = array();
1954 $durationbyday = array();
1956 if ($events === false) {
1960 foreach ($events as $event) {
1961 $startdate = $calendartype->timestamp_to_date_array($event->timestart
);
1962 if ($event->timeduration
) {
1963 $enddate = $calendartype->timestamp_to_date_array($event->timestart +
$event->timeduration
- 1);
1965 $enddate = $startdate;
1968 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair.
1969 if (!($startdate['year'] * 13 +
$startdate['mon'] <= $year * 13 +
$month) &&
1970 ($enddate['year'] * 13 +
$enddate['mon'] >= $year * 13 +
$month)) {
1974 $eventdaystart = intval($startdate['mday']);
1976 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
1977 // Give the event to its day.
1978 $eventsbyday[$eventdaystart][] = $event->id
;
1980 // Mark the day as having such an event.
1981 if ($event->courseid
== SITEID
&& $event->groupid
== 0) {
1982 $typesbyday[$eventdaystart]['startglobal'] = true;
1983 // Set event class for global event.
1984 $events[$event->id
]->class = 'calendar_event_global';
1985 } else if ($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) {
1986 $typesbyday[$eventdaystart]['startcourse'] = true;
1987 // Set event class for course event.
1988 $events[$event->id
]->class = 'calendar_event_course';
1989 } else if ($event->groupid
) {
1990 $typesbyday[$eventdaystart]['startgroup'] = true;
1991 // Set event class for group event.
1992 $events[$event->id
]->class = 'calendar_event_group';
1993 } else if ($event->userid
) {
1994 $typesbyday[$eventdaystart]['startuser'] = true;
1995 // Set event class for user event.
1996 $events[$event->id
]->class = 'calendar_event_user';
2000 if ($event->timeduration
== 0) {
2001 // Proceed with the next.
2005 // The event starts on $month $year or before.
2006 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2007 $lowerbound = intval($startdate['mday']);
2012 // Also, it ends on $month $year or later.
2013 if ($enddate['mon'] == $month && $enddate['year'] == $year) {
2014 $upperbound = intval($enddate['mday']);
2016 $upperbound = calendar_days_in_month($month, $year);
2019 // Mark all days between $lowerbound and $upperbound (inclusive) as duration.
2020 for ($i = $lowerbound +
1; $i <= $upperbound; ++
$i) {
2021 $durationbyday[$i][] = $event->id
;
2022 if ($event->courseid
== SITEID
&& $event->groupid
== 0) {
2023 $typesbyday[$i]['durationglobal'] = true;
2024 } else if ($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) {
2025 $typesbyday[$i]['durationcourse'] = true;
2026 } else if ($event->groupid
) {
2027 $typesbyday[$i]['durationgroup'] = true;
2028 } else if ($event->userid
) {
2029 $typesbyday[$i]['durationuser'] = true;
2038 * Returns the courses to load events for.
2040 * @param array $courseeventsfrom An array of courses to load calendar events for
2041 * @param bool $ignorefilters specify the use of filters, false is set as default
2042 * @return array An array of courses, groups, and user to load calendar events for based upon filters
2044 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
2047 // For backwards compatability we have to check whether the courses array contains
2048 // just id's in which case we need to load course objects.
2049 $coursestoload = array();
2050 foreach ($courseeventsfrom as $id => $something) {
2051 if (!is_object($something)) {
2052 $coursestoload[] = $id;
2053 unset($courseeventsfrom[$id]);
2061 // Get the capabilities that allow seeing group events from all groups.
2062 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
2064 $isloggedin = isloggedin();
2066 if ($ignorefilters ||
calendar_show_event_type(CALENDAR_EVENT_COURSE
)) {
2067 $courses = array_keys($courseeventsfrom);
2069 if ($ignorefilters ||
calendar_show_event_type(CALENDAR_EVENT_GLOBAL
)) {
2070 $courses[] = SITEID
;
2072 $courses = array_unique($courses);
2075 if (!empty($courses) && in_array(SITEID
, $courses)) {
2076 // Sort courses for consistent colour highlighting.
2077 // Effectively ignoring SITEID as setting as last course id.
2078 $key = array_search(SITEID
, $courses);
2079 unset($courses[$key]);
2080 $courses[] = SITEID
;
2083 if ($ignorefilters ||
($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER
))) {
2087 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP
) ||
$ignorefilters)) {
2089 if (count($courseeventsfrom) == 1) {
2090 $course = reset($courseeventsfrom);
2091 if (has_any_capability($allgroupscaps, \context_course
::instance($course->id
))) {
2092 $coursegroups = groups_get_all_groups($course->id
, 0, 0, 'g.id');
2093 $group = array_keys($coursegroups);
2096 if ($group === false) {
2097 if (!empty($CFG->calendar_adminseesall
) && has_any_capability($allgroupscaps, \context_system
::instance())) {
2099 } else if ($isloggedin) {
2100 $groupids = array();
2101 foreach ($courseeventsfrom as $courseid => $course) {
2102 // If the user is an editing teacher in there.
2103 if (!empty($USER->groupmember
[$course->id
])) {
2104 // We've already cached the users groups for this course so we can just use that.
2105 $groupids = array_merge($groupids, $USER->groupmember
[$course->id
]);
2106 } else if ($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
2107 // If this course has groups, show events from all of those related to the current user.
2108 $coursegroups = groups_get_user_groups($course->id
, $USER->id
);
2109 $groupids = array_merge($groupids, $coursegroups['0']);
2112 if (!empty($groupids)) {
2118 if (empty($courses)) {
2122 return array($courses, $group, $user);
2126 * Return the capability for viewing a calendar event.
2128 * @param calendar_event $event event object
2131 function calendar_view_event_allowed(calendar_event
$event) {
2134 // Anyone can see site events.
2135 if ($event->courseid
&& $event->courseid
== SITEID
) {
2139 // If a user can manage events at the site level they can see any event.
2140 $sitecontext = \context_system
::instance();
2141 // If user has manageentries at site level, return true.
2142 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2146 if (!empty($event->groupid
)) {
2147 // If it is a group event we need to be able to manage events in the course, or be in the group.
2148 if (has_capability('moodle/calendar:manageentries', $event->context
) ||
2149 has_capability('moodle/calendar:managegroupentries', $event->context
)) {
2153 $mycourses = enrol_get_my_courses('id');
2154 return isset($mycourses[$event->courseid
]) && groups_is_member($event->groupid
);
2155 } else if ($event->modulename
) {
2156 // If this is a module event we need to be able to see the module.
2157 $coursemodules = [];
2159 // Override events do not have the courseid set.
2160 if ($event->courseid
) {
2161 $courseid = $event->courseid
;
2162 $coursemodules = get_fast_modinfo($event->courseid
)->instances
;
2164 $cmraw = get_coursemodule_from_instance($event->modulename
, $event->instance
, 0, false, MUST_EXIST
);
2165 $courseid = $cmraw->course
;
2166 $coursemodules = get_fast_modinfo($cmraw->course
)->instances
;
2168 $hasmodule = isset($coursemodules[$event->modulename
]);
2169 $hasinstance = isset($coursemodules[$event->modulename
][$event->instance
]);
2171 // If modinfo doesn't know about the module, return false to be safe.
2172 if (!$hasmodule ||
!$hasinstance) {
2176 // Must be able to see the course and the module - MDL-59304.
2177 $cm = $coursemodules[$event->modulename
][$event->instance
];
2178 if (!$cm->uservisible
) {
2181 $mycourses = enrol_get_my_courses('id');
2182 return isset($mycourses[$courseid]);
2183 } else if ($event->categoryid
) {
2184 // If this is a category we need to be able to see the category.
2185 $cat = \coursecat
::get($event->categoryid
, IGNORE_MISSING
);
2190 } else if (!empty($event->courseid
)) {
2191 // If it is a course event we need to be able to manage events in the course, or be in the course.
2192 if (has_capability('moodle/calendar:manageentries', $event->context
)) {
2195 $mycourses = enrol_get_my_courses('id');
2196 return isset($mycourses[$event->courseid
]);
2197 } else if ($event->userid
) {
2198 if ($event->userid
!= $USER->id
) {
2199 // No-one can ever see another users events.
2204 throw new moodle_exception('unknown event type');
2211 * Return the capability for editing calendar event.
2213 * @param calendar_event $event event object
2214 * @param bool $manualedit is the event being edited manually by the user
2215 * @return bool capability to edit event
2217 function calendar_edit_event_allowed($event, $manualedit = false) {
2220 // Must be logged in.
2221 if (!isloggedin()) {
2225 // Can not be using guest account.
2226 if (isguestuser()) {
2230 if ($manualedit && !empty($event->modulename
)) {
2231 $hascallback = component_callback_exists(
2232 'mod_' . $event->modulename
,
2233 'core_calendar_event_timestart_updated'
2236 if (!$hascallback) {
2237 // If the activity hasn't implemented the correct callback
2238 // to handle changes to it's events then don't allow any
2239 // manual changes to them.
2243 $coursemodules = get_fast_modinfo($event->courseid
)->instances
;
2244 $hasmodule = isset($coursemodules[$event->modulename
]);
2245 $hasinstance = isset($coursemodules[$event->modulename
][$event->instance
]);
2247 // If modinfo doesn't know about the module, return false to be safe.
2248 if (!$hasmodule ||
!$hasinstance) {
2252 $coursemodule = $coursemodules[$event->modulename
][$event->instance
];
2253 $context = context_module
::instance($coursemodule->id
);
2254 // This is the capability that allows a user to modify the activity
2255 // settings. Since the activity generated this event we need to check
2256 // that the current user has the same capability before allowing them
2257 // to update the event because the changes to the event will be
2258 // reflected within the activity.
2259 return has_capability('moodle/course:manageactivities', $context);
2262 // You cannot edit URL based calendar subscription events presently.
2263 if (!empty($event->subscriptionid
)) {
2264 if (!empty($event->subscription
->url
)) {
2265 // This event can be updated externally, so it cannot be edited.
2270 $sitecontext = \context_system
::instance();
2272 // If user has manageentries at site level, return true.
2273 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2277 // If groupid is set, it's definitely a group event.
2278 if (!empty($event->groupid
)) {
2279 // Allow users to add/edit group events if -
2280 // 1) They have manageentries for the course OR
2281 // 2) They have managegroupentries AND are in the group.
2282 $group = $DB->get_record('groups', array('id' => $event->groupid
));
2284 has_capability('moodle/calendar:manageentries', $event->context
) ||
2285 (has_capability('moodle/calendar:managegroupentries', $event->context
)
2286 && groups_is_member($event->groupid
)));
2287 } else if (!empty($event->courseid
)) {
2288 // If groupid is not set, but course is set, it's definitely a course event.
2289 return has_capability('moodle/calendar:manageentries', $event->context
);
2290 } else if (!empty($event->categoryid
)) {
2291 // If groupid is not set, but category is set, it's definitely a category event.
2292 return has_capability('moodle/calendar:manageentries', $event->context
);
2293 } else if (!empty($event->userid
) && $event->userid
== $USER->id
) {
2294 // If course is not set, but userid id set, it's a user event.
2295 return (has_capability('moodle/calendar:manageownentries', $event->context
));
2296 } else if (!empty($event->userid
)) {
2297 return (has_capability('moodle/calendar:manageentries', $event->context
));
2304 * Return the capability for deleting a calendar event.
2306 * @param calendar_event $event The event object
2307 * @return bool Whether the user has permission to delete the event or not.
2309 function calendar_delete_event_allowed($event) {
2310 // Only allow delete if you have capabilities and it is not an module event.
2311 return (calendar_edit_event_allowed($event) && empty($event->modulename
));
2315 * Returns the default courses to display on the calendar when there isn't a specific
2316 * course to display.
2318 * @param int $courseid (optional) If passed, an additional course can be returned for admins (the current course).
2319 * @param string $fields Comma separated list of course fields to return.
2320 * @param bool $canmanage If true, this will return the list of courses the current user can create events in, rather
2321 * than the list of courses they see events from (an admin can always add events in a course
2322 * calendar, even if they are not enrolled in the course).
2323 * @return array $courses Array of courses to display
2325 function calendar_get_default_courses($courseid = null, $fields = '*', $canmanage=false) {
2328 if (!isloggedin()) {
2332 if (has_capability('moodle/calendar:manageentries', context_system
::instance()) &&
2333 (!empty($CFG->calendar_adminseesall
) ||
$canmanage)) {
2335 // Add a c. prefix to every field as expected by get_courses function.
2336 $fieldlist = explode(',', $fields);
2338 $prefixedfields = array_map(function($value) {
2339 return 'c.' . trim($value);
2341 $courses = get_courses('all', 'c.shortname', implode(',', $prefixedfields));
2343 $courses = enrol_get_my_courses($fields);
2346 if ($courseid && $courseid != SITEID
) {
2347 if (empty($courses[$courseid]) && has_capability('moodle/calendar:manageentries', context_system
::instance())) {
2348 // Allow a site admin to see calendars from courses he is not enrolled in.
2349 // This will come from $COURSE.
2350 $courses[$courseid] = get_course($courseid);
2358 * Get event format time.
2360 * @param calendar_event $event event object
2361 * @param int $now current time in gmt
2362 * @param array $linkparams list of params for event link
2363 * @param bool $usecommonwords the words as formatted date/time.
2364 * @param int $showtime determine the show time GMT timestamp
2365 * @return string $eventtime link/string for event time
2367 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
2368 $starttime = $event->timestart
;
2369 $endtime = $event->timestart +
$event->timeduration
;
2371 if (empty($linkparams) ||
!is_array($linkparams)) {
2372 $linkparams = array();
2375 $linkparams['view'] = 'day';
2377 // OK, now to get a meaningful display.
2378 // Check if there is a duration for this event.
2379 if ($event->timeduration
) {
2380 // Get the midnight of the day the event will start.
2381 $usermidnightstart = usergetmidnight($starttime);
2382 // Get the midnight of the day the event will end.
2383 $usermidnightend = usergetmidnight($endtime);
2384 // Check if we will still be on the same day.
2385 if ($usermidnightstart == $usermidnightend) {
2386 // Check if we are running all day.
2387 if ($event->timeduration
== DAYSECS
) {
2388 $time = get_string('allday', 'calendar');
2389 } else { // Specify the time we will be running this from.
2390 $datestart = calendar_time_representation($starttime);
2391 $dateend = calendar_time_representation($endtime);
2392 $time = $datestart . ' <strong>»</strong> ' . $dateend;
2395 // Set printable representation.
2397 $day = calendar_day_representation($event->timestart
, $now, $usecommonwords);
2398 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $endtime);
2399 $eventtime = \html_writer
::link($url, $day) . ', ' . $time;
2403 } else { // It must spans two or more days.
2404 $daystart = calendar_day_representation($event->timestart
, $now, $usecommonwords) . ', ';
2405 if ($showtime == $usermidnightstart) {
2408 $timestart = calendar_time_representation($event->timestart
);
2409 $dayend = calendar_day_representation($event->timestart +
$event->timeduration
, $now, $usecommonwords) . ', ';
2410 if ($showtime == $usermidnightend) {
2413 $timeend = calendar_time_representation($event->timestart +
$event->timeduration
);
2415 // Set printable representation.
2416 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2417 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $endtime);
2418 $eventtime = $timestart . ' <strong>»</strong> ' . \html_writer
::link($url, $dayend) . $timeend;
2420 // The event is in the future, print start and end links.
2421 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $starttime);
2422 $eventtime = \html_writer
::link($url, $daystart) . $timestart . ' <strong>»</strong> ';
2424 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $endtime);
2425 $eventtime .= \html_writer
::link($url, $dayend) . $timeend;
2428 } else { // There is no time duration.
2429 $time = calendar_time_representation($event->timestart
);
2430 // Set printable representation.
2432 $day = calendar_day_representation($event->timestart
, $now, $usecommonwords);
2433 $url = calendar_get_link_href(new \
moodle_url(CALENDAR_URL
. 'view.php', $linkparams), 0, 0, 0, $starttime);
2434 $eventtime = \html_writer
::link($url, $day) . ', ' . trim($time);
2440 // Check if It has expired.
2441 if ($event->timestart +
$event->timeduration
< $now) {
2442 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2449 * Checks to see if the requested type of event should be shown for the given user.
2451 * @param int $type The type to check the display for (default is to display all)
2452 * @param stdClass|int|null $user The user to check for - by default the current user
2453 * @return bool True if the tyep should be displayed false otherwise
2455 function calendar_show_event_type($type, $user = null) {
2456 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER
;
2458 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2460 if (!isset($SESSION->calendarshoweventtype
)) {
2461 $SESSION->calendarshoweventtype
= $default;
2463 return $SESSION->calendarshoweventtype
& $type;
2465 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2470 * Sets the display of the event type given $display.
2472 * If $display = true the event type will be shown.
2473 * If $display = false the event type will NOT be shown.
2474 * If $display = null the current value will be toggled and saved.
2476 * @param int $type object of CALENDAR_EVENT_XXX
2477 * @param bool $display option to display event type
2478 * @param stdClass|int $user moodle user object or id, null means current user
2480 function calendar_set_event_type_display($type, $display = null, $user = null) {
2481 $persist = get_user_preferences('calendar_persistflt', 0, $user);
2482 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP
2483 + CALENDAR_EVENT_USER + CALENDAR_EVENT_COURSECAT
;
2484 if ($persist === 0) {
2486 if (!isset($SESSION->calendarshoweventtype
)) {
2487 $SESSION->calendarshoweventtype
= $default;
2489 $preference = $SESSION->calendarshoweventtype
;
2491 $preference = get_user_preferences('calendar_savedflt', $default, $user);
2493 $current = $preference & $type;
2494 if ($display === null) {
2495 $display = !$current;
2497 if ($display && !$current) {
2498 $preference +
= $type;
2499 } else if (!$display && $current) {
2500 $preference -= $type;
2502 if ($persist === 0) {
2503 $SESSION->calendarshoweventtype
= $preference;
2505 if ($preference == $default) {
2506 unset_user_preference('calendar_savedflt', $user);
2508 set_user_preference('calendar_savedflt', $preference, $user);
2514 * Get calendar's allowed types.
2516 * @param stdClass $allowed list of allowed edit for event type
2517 * @param stdClass|int $course object of a course or course id
2518 * @param array $groups array of groups for the given course
2519 * @param stdClass|int $category object of a category
2521 function calendar_get_allowed_types(&$allowed, $course = null, $groups = null, $category = null) {
2524 $allowed = new \
stdClass();
2525 $allowed->user
= has_capability('moodle/calendar:manageownentries', \context_system
::instance());
2526 $allowed->groups
= false;
2527 $allowed->courses
= false;
2528 $allowed->categories
= false;
2529 $allowed->site
= has_capability('moodle/calendar:manageentries', \context_course
::instance(SITEID
));
2530 $getgroupsfunc = function($course, $context, $user) use ($groups) {
2531 if ($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
2532 if (has_capability('moodle/site:accessallgroups', $context)) {
2533 return is_null($groups) ?
groups_get_all_groups($course->id
) : $groups;
2535 if (is_null($groups)) {
2536 return groups_get_all_groups($course->id
, $user->id
);
2538 return array_filter($groups, function($group) use ($user) {
2539 return isset($group->members
[$user->id
]);
2548 if (!empty($course)) {
2549 if (!is_object($course)) {
2550 $course = $DB->get_record('course', array('id' => $course), 'id, groupmode, groupmodeforce', MUST_EXIST
);
2552 if ($course->id
!= SITEID
) {
2553 $coursecontext = \context_course
::instance($course->id
);
2554 $allowed->user
= has_capability('moodle/calendar:manageownentries', $coursecontext);
2556 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2557 $allowed->courses
= array($course->id
=> 1);
2558 $allowed->groups
= $getgroupsfunc($course, $coursecontext, $USER);
2559 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
2560 $allowed->groups
= $getgroupsfunc($course, $coursecontext, $USER);
2565 if (!empty($category)) {
2566 $catcontext = \context_coursecat
::instance($category->id
);
2567 if (has_capability('moodle/category:manage', $catcontext)) {
2568 $allowed->categories
= [$category->id
=> 1];
2574 * Get all of the allowed types for all of the courses and groups
2575 * the logged in user belongs to.
2577 * The returned array will optionally have 5 keys:
2578 * 'user' : true if the logged in user can create user events
2579 * 'site' : true if the logged in user can create site events
2580 * 'category' : array of course categories that the user can create events for
2581 * 'course' : array of courses that the user can create events for
2582 * 'group': array of groups that the user can create events for
2583 * 'groupcourses' : array of courses that the groups belong to (can
2584 * be different from the list in 'course'.
2586 * @return array The array of allowed types.
2588 function calendar_get_all_allowed_types() {
2589 global $CFG, $USER, $DB;
2591 require_once($CFG->libdir
. '/enrollib.php');
2595 $allowed = new stdClass();
2597 calendar_get_allowed_types($allowed);
2599 if ($allowed->user
) {
2600 $types['user'] = true;
2603 if ($allowed->site
) {
2604 $types['site'] = true;
2607 if (coursecat
::has_manage_capability_on_any()) {
2608 $types['category'] = coursecat
::make_categories_list('moodle/category:manage');
2611 // This function warms the context cache for the course so the calls
2612 // to load the course context in calendar_get_allowed_types don't result
2613 // in additional DB queries.
2614 $courses = calendar_get_default_courses(null, 'id, groupmode, groupmodeforce', true);
2616 // We want to pre-fetch all of the groups for each course in a single
2617 // query to avoid calendar_get_allowed_types from hitting the DB for
2618 // each separate course.
2619 $groups = groups_get_all_groups_for_courses($courses);
2621 foreach ($courses as $course) {
2622 $coursegroups = isset($groups[$course->id
]) ?
$groups[$course->id
] : null;
2623 calendar_get_allowed_types($allowed, $course, $coursegroups);
2625 if (!empty($allowed->courses
)) {
2626 $types['course'][$course->id
] = $course;
2629 if (!empty($allowed->groups
)) {
2630 $types['groupcourses'][$course->id
] = $course;
2632 if (!isset($types['group'])) {
2633 $types['group'] = array_values($allowed->groups
);
2635 $types['group'] = array_merge($types['group'], array_values($allowed->groups
));
2644 * See if user can add calendar entries at all used to print the "New Event" button.
2646 * @param stdClass $course object of a course or course id
2647 * @return bool has the capability to add at least one event type
2649 function calendar_user_can_add_event($course) {
2650 if (!isloggedin() ||
isguestuser()) {
2654 calendar_get_allowed_types($allowed, $course);
2656 return (bool)($allowed->user ||
$allowed->groups ||
$allowed->courses ||
$allowed->categories ||
$allowed->site
);
2660 * Check wether the current user is permitted to add events.
2662 * @param stdClass $event object of event
2663 * @return bool has the capability to add event
2665 function calendar_add_event_allowed($event) {
2668 // Can not be using guest account.
2669 if (!isloggedin() or isguestuser()) {
2673 $sitecontext = \context_system
::instance();
2675 // If user has manageentries at site level, always return true.
2676 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2680 switch ($event->eventtype
) {
2682 return has_capability('moodle/category:manage', $event->context
);
2684 return has_capability('moodle/calendar:manageentries', $event->context
);
2686 // Allow users to add/edit group events if -
2687 // 1) They have manageentries (= entries for whole course).
2688 // 2) They have managegroupentries AND are in the group.
2689 $group = $DB->get_record('groups', array('id' => $event->groupid
));
2691 has_capability('moodle/calendar:manageentries', $event->context
) ||
2692 (has_capability('moodle/calendar:managegroupentries', $event->context
)
2693 && groups_is_member($event->groupid
)));
2695 if ($event->userid
== $USER->id
) {
2696 return (has_capability('moodle/calendar:manageownentries', $event->context
));
2698 // There is intentionally no 'break'.
2700 return has_capability('moodle/calendar:manageentries', $event->context
);
2702 return has_capability('moodle/calendar:manageentries', $event->context
);
2707 * Returns option list for the poll interval setting.
2709 * @return array An array of poll interval options. Interval => description.
2711 function calendar_get_pollinterval_choices() {
2713 '0' => new \
lang_string('never', 'calendar'),
2714 HOURSECS
=> new \
lang_string('hourly', 'calendar'),
2715 DAYSECS
=> new \
lang_string('daily', 'calendar'),
2716 WEEKSECS
=> new \
lang_string('weekly', 'calendar'),
2717 '2628000' => new \
lang_string('monthly', 'calendar'),
2718 YEARSECS
=> new \
lang_string('annually', 'calendar')
2723 * Returns option list of available options for the calendar event type, given the current user and course.
2725 * @param int $courseid The id of the course
2726 * @return array An array containing the event types the user can create.
2728 function calendar_get_eventtype_choices($courseid) {
2730 $allowed = new \stdClass
;
2731 calendar_get_allowed_types($allowed, $courseid);
2733 if ($allowed->user
) {
2734 $choices['user'] = get_string('userevents', 'calendar');
2736 if ($allowed->site
) {
2737 $choices['site'] = get_string('siteevents', 'calendar');
2739 if (!empty($allowed->courses
)) {
2740 $choices['course'] = get_string('courseevents', 'calendar');
2742 if (!empty($allowed->categories
)) {
2743 $choices['category'] = get_string('categoryevents', 'calendar');
2745 if (!empty($allowed->groups
) and is_array($allowed->groups
)) {
2746 $choices['group'] = get_string('group');
2749 return array($choices, $allowed->groups
);
2753 * Add an iCalendar subscription to the database.
2755 * @param stdClass $sub The subscription object (e.g. from the form)
2756 * @return int The insert ID, if any.
2758 function calendar_add_subscription($sub) {
2759 global $DB, $USER, $SITE;
2761 // Undo the form definition work around to allow us to have two different
2762 // course selectors present depending on which event type the user selects.
2763 if (!empty($sub->groupcourseid
)) {
2764 $sub->courseid
= $sub->groupcourseid
;
2765 unset($sub->groupcourseid
);
2768 // Pull the group id back out of the value. The form saves the value
2769 // as "<courseid>-<groupid>" to allow the javascript to work correctly.
2770 if (!empty($sub->groupid
)) {
2771 list($courseid, $groupid) = explode('-', $sub->groupid
);
2772 $sub->courseid
= $courseid;
2773 $sub->groupid
= $groupid;
2776 // Default course id if none is set.
2777 if (empty($sub->courseid
)) {
2778 if ($sub->eventtype
=== 'site') {
2779 $sub->courseid
= SITEID
;
2785 if ($sub->eventtype
=== 'site') {
2786 $sub->courseid
= $SITE->id
;
2787 } else if ($sub->eventtype
=== 'group' ||
$sub->eventtype
=== 'course') {
2788 $sub->courseid
= $sub->courseid
;
2789 } else if ($sub->eventtype
=== 'category') {
2790 $sub->categoryid
= $sub->categoryid
;
2795 $sub->userid
= $USER->id
;
2797 // File subscriptions never update.
2798 if (empty($sub->url
)) {
2799 $sub->pollinterval
= 0;
2802 if (!empty($sub->name
)) {
2803 if (empty($sub->id
)) {
2804 $id = $DB->insert_record('event_subscriptions', $sub);
2805 // We cannot cache the data here because $sub is not complete.
2807 // Trigger event, calendar subscription added.
2808 $eventparams = array('objectid' => $sub->id
,
2809 'context' => calendar_get_calendar_context($sub),
2811 'eventtype' => $sub->eventtype
,
2814 switch ($sub->eventtype
) {
2816 $eventparams['other']['categoryid'] = $sub->categoryid
;
2819 $eventparams['other']['courseid'] = $sub->courseid
;
2822 $eventparams['other']['courseid'] = $sub->courseid
;
2823 $eventparams['other']['groupid'] = $sub->groupid
;
2826 $eventparams['other']['courseid'] = $sub->courseid
;
2829 $event = \core\event\calendar_subscription_created
::create($eventparams);
2833 // Why are we doing an update here?
2834 calendar_update_subscription($sub);
2838 print_error('errorbadsubscription', 'importcalendar');
2843 * Add an iCalendar event to the Moodle calendar.
2845 * @param stdClass $event The RFC-2445 iCalendar event
2846 * @param int $unused Deprecated
2847 * @param int $subscriptionid The iCalendar subscription ID
2848 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2849 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2850 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2852 function calendar_add_icalendar_event($event, $unused = null, $subscriptionid, $timezone='UTC') {
2855 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2856 if (empty($event->properties
['SUMMARY'])) {
2860 $name = $event->properties
['SUMMARY'][0]->value
;
2861 $name = str_replace('\n', '<br />', $name);
2862 $name = str_replace('\\', '', $name);
2863 $name = preg_replace('/\s+/u', ' ', $name);
2865 $eventrecord = new \stdClass
;
2866 $eventrecord->name
= clean_param($name, PARAM_NOTAGS
);
2868 if (empty($event->properties
['DESCRIPTION'][0]->value
)) {
2871 $description = $event->properties
['DESCRIPTION'][0]->value
;
2872 $description = clean_param($description, PARAM_NOTAGS
);
2873 $description = str_replace('\n', '<br />', $description);
2874 $description = str_replace('\\', '', $description);
2875 $description = preg_replace('/\s+/u', ' ', $description);
2877 $eventrecord->description
= $description;
2879 // Probably a repeating event with RRULE etc. TODO: skip for now.
2880 if (empty($event->properties
['DTSTART'][0]->value
)) {
2884 if (isset($event->properties
['DTSTART'][0]->parameters
['TZID'])) {
2885 $tz = $event->properties
['DTSTART'][0]->parameters
['TZID'];
2889 $tz = \core_date
::normalise_timezone($tz);
2890 $eventrecord->timestart
= strtotime($event->properties
['DTSTART'][0]->value
. ' ' . $tz);
2891 if (empty($event->properties
['DTEND'])) {
2892 $eventrecord->timeduration
= 0; // No duration if no end time specified.
2894 if (isset($event->properties
['DTEND'][0]->parameters
['TZID'])) {
2895 $endtz = $event->properties
['DTEND'][0]->parameters
['TZID'];
2899 $endtz = \core_date
::normalise_timezone($endtz);
2900 $eventrecord->timeduration
= strtotime($event->properties
['DTEND'][0]->value
. ' ' . $endtz) - $eventrecord->timestart
;
2903 // Check to see if it should be treated as an all day event.
2904 if ($eventrecord->timeduration
== DAYSECS
) {
2905 // Check to see if the event started at Midnight on the imported calendar.
2906 date_default_timezone_set($timezone);
2907 if (date('H:i:s', $eventrecord->timestart
) === "00:00:00") {
2908 // This event should be an all day event. This is not correct, we don't do anything differently for all day events.
2910 $eventrecord->timeduration
= 0;
2912 \core_date
::set_default_server_timezone();
2915 $eventrecord->location
= empty($event->properties
['LOCATION'][0]->value
) ?
'' :
2916 str_replace('\\', '', $event->properties
['LOCATION'][0]->value
);
2917 $eventrecord->uuid
= $event->properties
['UID'][0]->value
;
2918 $eventrecord->timemodified
= time();
2920 // Add the iCal subscription details if required.
2921 // We should never do anything with an event without a subscription reference.
2922 $sub = calendar_get_subscription($subscriptionid);
2923 $eventrecord->subscriptionid
= $subscriptionid;
2924 $eventrecord->userid
= $sub->userid
;
2925 $eventrecord->groupid
= $sub->groupid
;
2926 $eventrecord->courseid
= $sub->courseid
;
2927 $eventrecord->categoryid
= $sub->categoryid
;
2928 $eventrecord->eventtype
= $sub->eventtype
;
2930 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid
,
2931 'subscriptionid' => $eventrecord->subscriptionid
))) {
2932 $eventrecord->id
= $updaterecord->id
;
2933 $return = CALENDAR_IMPORT_EVENT_UPDATED
; // Update.
2935 $return = CALENDAR_IMPORT_EVENT_INSERTED
; // Insert.
2937 if ($createdevent = \calendar_event
::create($eventrecord, false)) {
2938 if (!empty($event->properties
['RRULE'])) {
2939 // Repeating events.
2940 date_default_timezone_set($tz); // Change time zone to parse all events.
2941 $rrule = new \core_calendar\rrule_manager
($event->properties
['RRULE'][0]->value
);
2942 $rrule->parse_rrule();
2943 $rrule->create_events($createdevent);
2944 \core_date
::set_default_server_timezone(); // Change time zone back to what it was.
2953 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2955 * @param int $subscriptionid The ID of the subscription we are acting upon.
2956 * @param int $pollinterval The poll interval to use.
2957 * @param int $action The action to be performed. One of update or remove.
2958 * @throws dml_exception if invalid subscriptionid is provided
2959 * @return string A log of the import progress, including errors
2961 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2962 // Fetch the subscription from the database making sure it exists.
2963 $sub = calendar_get_subscription($subscriptionid);
2965 // Update or remove the subscription, based on action.
2967 case CALENDAR_SUBSCRIPTION_UPDATE
:
2968 // Skip updating file subscriptions.
2969 if (empty($sub->url
)) {
2972 $sub->pollinterval
= $pollinterval;
2973 calendar_update_subscription($sub);
2975 // Update the events.
2976 return "<p>" . get_string('subscriptionupdated', 'calendar', $sub->name
) . "</p>" .
2977 calendar_update_subscription_events($subscriptionid);
2978 case CALENDAR_SUBSCRIPTION_REMOVE
:
2979 calendar_delete_subscription($subscriptionid);
2980 return get_string('subscriptionremoved', 'calendar', $sub->name
);
2989 * Delete subscription and all related events.
2991 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
2993 function calendar_delete_subscription($subscription) {
2996 if (!is_object($subscription)) {
2997 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST
);
3000 // Delete subscription and related events.
3001 $DB->delete_records('event', array('subscriptionid' => $subscription->id
));
3002 $DB->delete_records('event_subscriptions', array('id' => $subscription->id
));
3003 \cache_helper
::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id
));
3005 // Trigger event, calendar subscription deleted.
3006 $eventparams = array('objectid' => $subscription->id
,
3007 'context' => calendar_get_calendar_context($subscription),
3009 'eventtype' => $subscription->eventtype
,
3012 switch ($subscription->eventtype
) {
3014 $eventparams['other']['categoryid'] = $subscription->categoryid
;
3017 $eventparams['other']['courseid'] = $subscription->courseid
;
3020 $eventparams['other']['courseid'] = $subscription->courseid
;
3021 $eventparams['other']['groupid'] = $subscription->groupid
;
3024 $eventparams['other']['courseid'] = $subscription->courseid
;
3026 $event = \core\event\calendar_subscription_deleted
::create($eventparams);
3031 * From a URL, fetch the calendar and return an iCalendar object.
3033 * @param string $url The iCalendar URL
3034 * @return iCalendar The iCalendar object
3036 function calendar_get_icalendar($url) {
3039 require_once($CFG->libdir
. '/filelib.php');
3041 $curl = new \
curl();
3042 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
3043 $calendar = $curl->get($url);
3045 // Http code validation should actually be the job of curl class.
3046 if (!$calendar ||
$curl->info
['http_code'] != 200 ||
!empty($curl->errorno
)) {
3047 throw new \
moodle_exception('errorinvalidicalurl', 'calendar');
3050 $ical = new \
iCalendar();
3051 $ical->unserialize($calendar);
3057 * Import events from an iCalendar object into a course calendar.
3059 * @param iCalendar $ical The iCalendar object.
3060 * @param int $courseid The course ID for the calendar.
3061 * @param int $subscriptionid The subscription ID.
3062 * @return string A log of the import progress, including errors.
3064 function calendar_import_icalendar_events($ical, $unused = null, $subscriptionid = null) {
3071 // Large calendars take a while...
3073 \core_php_time_limit
::raise(300);
3076 // Mark all events in a subscription with a zero timestamp.
3077 if (!empty($subscriptionid)) {
3078 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
3079 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3082 // Grab the timezone from the iCalendar file to be used later.
3083 if (isset($ical->properties
['X-WR-TIMEZONE'][0]->value
)) {
3084 $timezone = $ical->properties
['X-WR-TIMEZONE'][0]->value
;
3090 foreach ($ical->components
['VEVENT'] as $event) {
3091 $res = calendar_add_icalendar_event($event, null, $subscriptionid, $timezone);
3093 case CALENDAR_IMPORT_EVENT_UPDATED
:
3096 case CALENDAR_IMPORT_EVENT_INSERTED
:
3100 $return .= '<p>' . get_string('erroraddingevent', 'calendar') . ': ';
3101 if (empty($event->properties
['SUMMARY'])) {
3102 $return .= '(' . get_string('notitle', 'calendar') . ')';
3104 $return .= $event->properties
['SUMMARY'][0]->value
;
3106 $return .= "</p>\n";
3111 $return .= "<p>" . get_string('eventsimported', 'calendar', $eventcount) . "</p> ";
3112 $return .= "<p>" . get_string('eventsupdated', 'calendar', $updatecount) . "</p>";
3114 // Delete remaining zero-marked events since they're not in remote calendar.
3115 if (!empty($subscriptionid)) {
3116 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3117 if (!empty($deletecount)) {
3118 $DB->delete_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3119 $return .= "<p> " . get_string('eventsdeleted', 'calendar') . ": {$deletecount} </p>\n";
3127 * Fetch a calendar subscription and update the events in the calendar.
3129 * @param int $subscriptionid The course ID for the calendar.
3130 * @return string A log of the import progress, including errors.
3132 function calendar_update_subscription_events($subscriptionid) {
3133 $sub = calendar_get_subscription($subscriptionid);
3135 // Don't update a file subscription.
3136 if (empty($sub->url
)) {
3137 return 'File subscription not updated.';
3140 $ical = calendar_get_icalendar($sub->url
);
3141 $return = calendar_import_icalendar_events($ical, null, $subscriptionid);
3142 $sub->lastupdated
= time();
3144 calendar_update_subscription($sub);
3150 * Update a calendar subscription. Also updates the associated cache.
3152 * @param stdClass|array $subscription Subscription record.
3153 * @throws coding_exception If something goes wrong
3156 function calendar_update_subscription($subscription) {
3159 if (is_array($subscription)) {
3160 $subscription = (object)$subscription;
3162 if (empty($subscription->id
) ||
!$DB->record_exists('event_subscriptions', array('id' => $subscription->id
))) {
3163 throw new \
coding_exception('Cannot update a subscription without a valid id');
3166 $DB->update_record('event_subscriptions', $subscription);
3169 $cache = \cache
::make('core', 'calendar_subscriptions');
3170 $cache->set($subscription->id
, $subscription);
3172 // Trigger event, calendar subscription updated.
3173 $eventparams = array('userid' => $subscription->userid
,
3174 'objectid' => $subscription->id
,
3175 'context' => calendar_get_calendar_context($subscription),
3177 'eventtype' => $subscription->eventtype
,
3180 switch ($subscription->eventtype
) {
3182 $eventparams['other']['categoryid'] = $subscription->categoryid
;
3185 $eventparams['other']['courseid'] = $subscription->courseid
;
3188 $eventparams['other']['courseid'] = $subscription->courseid
;
3189 $eventparams['other']['groupid'] = $subscription->groupid
;
3192 $eventparams['other']['courseid'] = $subscription->courseid
;
3194 $event = \core\event\calendar_subscription_updated
::create($eventparams);
3199 * Checks to see if the user can edit a given subscription feed.
3201 * @param mixed $subscriptionorid Subscription object or id
3202 * @return bool true if current user can edit the subscription else false
3204 function calendar_can_edit_subscription($subscriptionorid) {
3205 if (is_array($subscriptionorid)) {
3206 $subscription = (object)$subscriptionorid;
3207 } else if (is_object($subscriptionorid)) {
3208 $subscription = $subscriptionorid;
3210 $subscription = calendar_get_subscription($subscriptionorid);
3213 $allowed = new \stdClass
;
3214 $courseid = $subscription->courseid
;
3215 $categoryid = $subscription->categoryid
;
3216 $groupid = $subscription->groupid
;
3219 if (!empty($categoryid)) {
3220 $category = \coursecat
::get($categoryid);
3222 calendar_get_allowed_types($allowed, $courseid, null, $category);
3223 switch ($subscription->eventtype
) {
3225 return $allowed->user
;
3227 if (isset($allowed->courses
[$courseid])) {
3228 return $allowed->courses
[$courseid];
3233 if (isset($allowed->categories
[$categoryid])) {
3234 return $allowed->categories
[$categoryid];
3239 return $allowed->site
;
3241 if (isset($allowed->groups
[$groupid])) {
3242 return $allowed->groups
[$groupid];
3252 * Helper function to determine the context of a calendar subscription.
3253 * Subscriptions can be created in two contexts COURSE, or USER.
3255 * @param stdClass $subscription
3256 * @return context instance
3258 function calendar_get_calendar_context($subscription) {
3259 // Determine context based on calendar type.
3260 if ($subscription->eventtype
=== 'site') {
3261 $context = \context_course
::instance(SITEID
);
3262 } else if ($subscription->eventtype
=== 'group' ||
$subscription->eventtype
=== 'course') {
3263 $context = \context_course
::instance($subscription->courseid
);
3265 $context = \context_user
::instance($subscription->userid
);
3271 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
3273 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3277 function core_calendar_user_preferences() {
3279 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS
, 'null' => NULL_NOT_ALLOWED
, 'default' => '0',
3280 'choices' => array('0', CALENDAR_TF_12
, CALENDAR_TF_24
)
3282 $preferences['calendar_startwday'] = array('type' => PARAM_INT
, 'null' => NULL_NOT_ALLOWED
, 'default' => 0,
3283 'choices' => array(0, 1, 2, 3, 4, 5, 6));
3284 $preferences['calendar_maxevents'] = array('type' => PARAM_INT
, 'choices' => range(1, 20));
3285 $preferences['calendar_lookahead'] = array('type' => PARAM_INT
, 'null' => NULL_NOT_ALLOWED
, 'default' => 365,
3286 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3287 $preferences['calendar_persistflt'] = array('type' => PARAM_INT
, 'null' => NULL_NOT_ALLOWED
, 'default' => 0,
3288 'choices' => array(0, 1));
3289 return $preferences;
3293 * Get legacy calendar events
3295 * @param int $tstart Start time of time range for events
3296 * @param int $tend End time of time range for events
3297 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3298 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3299 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3300 * @param boolean $withduration whether only events starting within time range selected
3301 * or events in progress/already started selected as well
3302 * @param boolean $ignorehidden whether to select only visible events or all events
3303 * @param array $categories array of category ids and/or objects.
3304 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3306 function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses,
3307 $withduration = true, $ignorehidden = true, $categories = []) {
3308 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3309 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3310 // parameters, but with the new API method, only null and arrays are accepted.
3311 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3312 // If parameter is true, return null.
3313 if ($param === true) {
3317 // If parameter is false, return an empty array.
3318 if ($param === false) {
3322 // If the parameter is a scalar value, enclose it in an array.
3323 if (!is_array($param)) {
3327 // No normalisation required.
3329 }, [$users, $groups, $courses, $categories]);
3331 $mapper = \core_calendar\local\event\container
::get_event_mapper();
3332 $events = \core_calendar\local\api
::get_events(
3349 return array_reduce($events, function($carry, $event) use ($mapper) {
3350 return $carry +
[$event->get_id() => $mapper->from_event_to_stdclass($event)];
3356 * Get the calendar view output.
3358 * @param \calendar_information $calendar The calendar being represented
3359 * @param string $view The type of calendar to have displayed
3360 * @param bool $includenavigation Whether to include navigation
3361 * @param bool $skipevents Whether to load the events or not
3362 * @return array[array, string]
3364 function calendar_get_view(\calendar_information
$calendar, $view, $includenavigation = true, bool $skipevents = false) {
3367 $renderer = $PAGE->get_renderer('core_calendar');
3368 $type = \core_calendar\type_factory
::get_calendar_instance();
3370 // Calculate the bounds of the month.
3371 $calendardate = $type->timestamp_to_date_array($calendar->time
);
3373 $date = new \
DateTime('now', core_date
::get_user_timezone_object(99));
3376 if ($view === 'day') {
3377 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday']);
3378 $date->setTimestamp($tstart);
3379 $date->modify('+1 day');
3380 } else if ($view === 'upcoming' ||
$view === 'upcoming_mini') {
3381 // Number of days in the future that will be used to fetch events.
3382 if (isset($CFG->calendar_lookahead
)) {
3383 $defaultlookahead = intval($CFG->calendar_lookahead
);
3385 $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD
;
3387 $lookahead = get_user_preferences('calendar_lookahead', $defaultlookahead);
3389 // Maximum number of events to be displayed on upcoming view.
3390 $defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS
;
3391 if (isset($CFG->calendar_maxevents
)) {
3392 $defaultmaxevents = intval($CFG->calendar_maxevents
);
3394 $eventlimit = get_user_preferences('calendar_maxevents', $defaultmaxevents);
3396 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday'],
3397 $calendardate['hours']);
3398 $date->setTimestamp($tstart);
3399 $date->modify('+' . $lookahead . ' days');
3401 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], 1);
3402 $monthdays = $type->get_num_days_in_month($calendardate['year'], $calendardate['mon']);
3403 $date->setTimestamp($tstart);
3404 $date->modify('+' . $monthdays . ' days');
3406 if ($view === 'mini' ||
$view === 'minithree') {
3407 $template = 'core_calendar/calendar_mini';
3409 $template = 'core_calendar/calendar_month';
3413 // We need to extract 1 second to ensure that we don't get into the next day.
3414 $date->modify('-1 second');
3415 $tend = $date->getTimestamp();
3417 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
3418 // If parameter is true, return null.
3419 if ($param === true) {
3423 // If parameter is false, return an empty array.
3424 if ($param === false) {
3428 // If the parameter is a scalar value, enclose it in an array.
3429 if (!is_array($param)) {
3433 // No normalisation required.
3435 }, [$calendar->users
, $calendar->groups
, $calendar->courses
, $calendar->categories
]);
3440 $events = \core_calendar\local\api
::get_events(
3456 if ($proxy = $event->get_course_module()) {
3457 $cminfo = $proxy->get_proxied_instance();
3458 return $cminfo->uservisible
;
3461 if ($proxy = $event->get_category()) {
3462 $category = $proxy->get_proxied_instance();
3464 return $category->is_uservisible();
3473 'events' => $events,
3474 'cache' => new \core_calendar\external\
events_related_objects_cache($events),
3479 if ($view == "month" ||
$view == "mini" ||
$view == "minithree") {
3480 $month = new \core_calendar\external\
month_exporter($calendar, $type, $related);
3481 $month->set_includenavigation($includenavigation);
3482 $month->set_initialeventsloaded(!$skipevents);
3483 $month->set_showcoursefilter($view == "month");
3484 $data = $month->export($renderer);
3485 } else if ($view == "day") {
3486 $day = new \core_calendar\external\
calendar_day_exporter($calendar, $related);
3487 $data = $day->export($renderer);
3488 $template = 'core_calendar/calendar_day';
3489 } else if ($view == "upcoming" ||
$view == "upcoming_mini") {
3490 $upcoming = new \core_calendar\external\
calendar_upcoming_exporter($calendar, $related);
3491 $data = $upcoming->export($renderer);
3493 if ($view == "upcoming") {
3494 $template = 'core_calendar/calendar_upcoming';
3495 } else if ($view == "upcoming_mini") {
3496 $template = 'core_calendar/calendar_upcoming_mini';
3500 return [$data, $template];
3504 * Request and render event form fragment.
3506 * @param array $args The fragment arguments.
3507 * @return string The rendered mform fragment.
3509 function calendar_output_fragment_event_form($args) {
3510 global $CFG, $OUTPUT, $USER;
3514 $eventid = isset($args['eventid']) ?
clean_param($args['eventid'], PARAM_INT
) : null;
3515 $starttime = isset($args['starttime']) ?
clean_param($args['starttime'], PARAM_INT
) : null;
3516 $courseid = isset($args['courseid']) ?
clean_param($args['courseid'], PARAM_INT
) : null;
3517 $categoryid = isset($args['categoryid']) ?
clean_param($args['categoryid'], PARAM_INT
) : null;
3519 $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
3520 $context = \context_user
::instance($USER->id
);
3521 $editoroptions = \core_calendar\local\event\forms\create
::build_editor_options($context);
3522 $formoptions = ['editoroptions' => $editoroptions];
3526 parse_str(clean_param($args['formdata'], PARAM_TEXT
), $data);
3527 if (isset($data['description']['itemid'])) {
3528 $draftitemid = $data['description']['itemid'];
3533 $formoptions['starttime'] = $starttime;
3536 if (is_null($eventid)) {
3537 $mform = new \core_calendar\local\event\forms\
create(
3547 // Let's check first which event types user can add.
3548 calendar_get_allowed_types($allowed, $courseid);
3550 // If the user is on course context and is allowed to add course events set the event type default to course.
3551 if ($courseid != SITEID
&& !empty($allowed->courses
)) {
3552 $data['eventtype'] = 'course';
3553 $data['courseid'] = $courseid;
3554 $data['groupcourseid'] = $courseid;
3555 } else if (!empty($categoryid) && !empty($allowed->category
)) {
3556 $data['eventtype'] = 'category';
3557 $data['categoryid'] = $categoryid;
3559 $mform->set_data($data);
3561 $event = calendar_event
::load($eventid);
3562 $mapper = new \core_calendar\local\event\mappers\
create_update_form_mapper();
3563 $eventdata = $mapper->from_legacy_event_to_data($event);
3564 $data = array_merge((array) $eventdata, $data);
3565 $event->count_repeats();
3566 $formoptions['event'] = $event;
3567 $data['description']['text'] = file_prepare_draft_area(
3569 $event->context
->id
,
3571 'event_description',
3574 $data['description']['text']
3576 $data['description']['itemid'] = $draftitemid;
3578 $mform = new \core_calendar\local\event\forms\
update(
3587 $mform->set_data($data);
3589 // Check to see if this event is part of a subscription or import.
3590 // If so display a warning on edit.
3591 if (isset($event->subscriptionid
) && ($event->subscriptionid
!= null)) {
3592 $renderable = new \core\output\notification
(
3593 get_string('eventsubscriptioneditwarning', 'calendar'),
3594 \core\output\notification
::NOTIFY_INFO
3597 $html .= $OUTPUT->render($renderable);
3602 $mform->is_validated();
3605 $html .= $mform->render();
3610 * Calculate the timestamp from the supplied Gregorian Year, Month, and Day.
3612 * @param int $d The day
3613 * @param int $m The month
3614 * @param int $y The year
3615 * @param int $time The timestamp to use instead of a separate y/m/d.
3616 * @return int The timestamp
3618 function calendar_get_timestamp($d, $m, $y, $time = 0) {
3619 // If a day, month and year were passed then convert it to a timestamp. If these were passed
3620 // then we can assume the day, month and year are passed as Gregorian, as no where in core
3621 // should we be passing these values rather than the time.
3622 if (!empty($d) && !empty($m) && !empty($y)) {
3623 if (checkdate($m, $d, $y)) {
3624 $time = make_timestamp($y, $m, $d);
3628 } else if (empty($time)) {
3636 * Get the calendar footer options.
3638 * @param calendar_information $calendar The calendar information object.
3639 * @return array The data for template and template name.
3641 function calendar_get_footer_options($calendar) {
3642 global $CFG, $USER, $DB, $PAGE;
3644 // Generate hash for iCal link.
3645 $rawhash = $USER->id
. $DB->get_field('user', 'password', ['id' => $USER->id
]) . $CFG->calendar_exportsalt
;
3646 $authtoken = sha1($rawhash);
3648 $renderer = $PAGE->get_renderer('core_calendar');
3649 $footer = new \core_calendar\external\footer_options_exporter
($calendar, $USER->id
, $authtoken);
3650 $data = $footer->export($renderer);
3651 $template = 'core_calendar/footer_options';
3653 return [$data, $template];
3657 * Get the list of potential calendar filter types as a type => name
3662 function calendar_get_filter_types() {
3671 return array_map(function($type) {
3673 'eventtype' => $type,
3674 'name' => get_string("eventtype{$type}", "calendar"),
3680 * Check whether the specified event type is valid.
3682 * @param string $type
3685 function calendar_is_valid_eventtype($type) {
3693 return in_array($type, $validtypes);