MDL-60033 webservice_xmlrpc: extra escaping in the server URL
[moodle.git] / calendar / lib.php
blob3ad809b6b5983d3e027405b7609f0e7845362548
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Calendar extension
20 * @package core_calendar
21 * @copyright 2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
22 * Avgoustos Tsinakos
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 if (!defined('MOODLE_INTERNAL')) {
27 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
30 /**
31 * These are read by the administration component to provide default values
34 /**
35 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
37 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
39 /**
40 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
42 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
44 /**
45 * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
47 define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
49 // This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
50 // Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
52 /**
53 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
55 define('CALENDAR_DEFAULT_WEEKEND', 65);
57 /**
58 * CALENDAR_URL - path to calendar's folder
60 define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
62 /**
63 * CALENDAR_TF_24 - Calendar time in 24 hours format
65 define('CALENDAR_TF_24', '%H:%M');
67 /**
68 * CALENDAR_TF_12 - Calendar time in 12 hours format
70 define('CALENDAR_TF_12', '%I:%M %p');
72 /**
73 * CALENDAR_EVENT_GLOBAL - Global calendar event types
75 define('CALENDAR_EVENT_GLOBAL', 1);
77 /**
78 * CALENDAR_EVENT_COURSE - Course calendar event types
80 define('CALENDAR_EVENT_COURSE', 2);
82 /**
83 * CALENDAR_EVENT_GROUP - group calendar event types
85 define('CALENDAR_EVENT_GROUP', 4);
87 /**
88 * CALENDAR_EVENT_USER - user calendar event types
90 define('CALENDAR_EVENT_USER', 8);
93 /**
94 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
96 define('CALENDAR_IMPORT_FROM_FILE', 0);
98 /**
99 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
101 define('CALENDAR_IMPORT_FROM_URL', 1);
104 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
106 define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
109 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
111 define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
114 * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
116 define('CALENDAR_SUBSCRIPTION_UPDATE', 1);
119 * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
121 define('CALENDAR_SUBSCRIPTION_REMOVE', 2);
124 * CALENDAR_EVENT_USER_OVERRIDE_PRIORITY - Constant for the user override priority.
126 define('CALENDAR_EVENT_USER_OVERRIDE_PRIORITY', 0);
129 * CALENDAR_EVENT_TYPE_STANDARD - Standard events.
131 define('CALENDAR_EVENT_TYPE_STANDARD', 0);
134 * CALENDAR_EVENT_TYPE_ACTION - Action events.
136 define('CALENDAR_EVENT_TYPE_ACTION', 1);
139 * Manage calendar events.
141 * This class provides the required functionality in order to manage calendar events.
142 * It was introduced as part of Moodle 2.0 and was created in order to provide a
143 * better framework for dealing with calendar events in particular regard to file
144 * handling through the new file API.
146 * @package core_calendar
147 * @category calendar
148 * @copyright 2009 Sam Hemelryk
149 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
151 * @property int $id The id within the event table
152 * @property string $name The name of the event
153 * @property string $description The description of the event
154 * @property int $format The format of the description FORMAT_?
155 * @property int $courseid The course the event is associated with (0 if none)
156 * @property int $groupid The group the event is associated with (0 if none)
157 * @property int $userid The user the event is associated with (0 if none)
158 * @property int $repeatid If this is a repeated event this will be set to the
159 * id of the original
160 * @property string $modulename If added by a module this will be the module name
161 * @property int $instance If added by a module this will be the module instance
162 * @property string $eventtype The event type
163 * @property int $timestart The start time as a timestamp
164 * @property int $timeduration The duration of the event in seconds
165 * @property int $visible 1 if the event is visible
166 * @property int $uuid ?
167 * @property int $sequence ?
168 * @property int $timemodified The time last modified as a timestamp
170 class calendar_event {
172 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
173 protected $properties = null;
175 /** @var string The converted event discription with file paths resolved.
176 * This gets populated when someone requests description for the first time */
177 protected $_description = null;
179 /** @var array The options to use with this description editor */
180 protected $editoroptions = array(
181 'subdirs' => false,
182 'forcehttps' => false,
183 'maxfiles' => -1,
184 'maxbytes' => null,
185 'trusttext' => false);
187 /** @var object The context to use with the description editor */
188 protected $editorcontext = null;
191 * Instantiates a new event and optionally populates its properties with the data provided.
193 * @param \stdClass $data Optional. An object containing the properties to for
194 * an event
196 public function __construct($data = null) {
197 global $CFG, $USER;
199 // First convert to object if it is not already (should either be object or assoc array).
200 if (!is_object($data)) {
201 $data = (object) $data;
204 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
206 $data->eventrepeats = 0;
208 if (empty($data->id)) {
209 $data->id = null;
212 if (!empty($data->subscriptionid)) {
213 $data->subscription = calendar_get_subscription($data->subscriptionid);
216 // Default to a user event.
217 if (empty($data->eventtype)) {
218 $data->eventtype = 'user';
221 // Default to the current user.
222 if (empty($data->userid)) {
223 $data->userid = $USER->id;
226 if (!empty($data->timeduration) && is_array($data->timeduration)) {
227 $data->timeduration = make_timestamp(
228 $data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'],
229 $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
232 if (!empty($data->description) && is_array($data->description)) {
233 $data->format = $data->description['format'];
234 $data->description = $data->description['text'];
235 } else if (empty($data->description)) {
236 $data->description = '';
237 $data->format = editors_get_preferred_format();
240 // Ensure form is defaulted correctly.
241 if (empty($data->format)) {
242 $data->format = editors_get_preferred_format();
245 $this->properties = $data;
247 if (empty($data->context)) {
248 $this->properties->context = $this->calculate_context();
253 * Magic set method.
255 * Attempts to call a set_$key method if one exists otherwise falls back
256 * to simply set the property.
258 * @param string $key property name
259 * @param mixed $value value of the property
261 public function __set($key, $value) {
262 if (method_exists($this, 'set_'.$key)) {
263 $this->{'set_'.$key}($value);
265 $this->properties->{$key} = $value;
269 * Magic get method.
271 * Attempts to call a get_$key method to return the property and ralls over
272 * to return the raw property.
274 * @param string $key property name
275 * @return mixed property value
276 * @throws \coding_exception
278 public function __get($key) {
279 if (method_exists($this, 'get_'.$key)) {
280 return $this->{'get_'.$key}();
282 if (!property_exists($this->properties, $key)) {
283 throw new \coding_exception('Undefined property requested');
285 return $this->properties->{$key};
289 * Magic isset method.
291 * PHP needs an isset magic method if you use the get magic method and
292 * still want empty calls to work.
294 * @param string $key $key property name
295 * @return bool|mixed property value, false if property is not exist
297 public function __isset($key) {
298 return !empty($this->properties->{$key});
302 * Calculate the context value needed for an event.
304 * Event's type can be determine by the available value store in $data
305 * It is important to check for the existence of course/courseid to determine
306 * the course event.
307 * Default value is set to CONTEXT_USER
309 * @return \stdClass The context object.
311 protected function calculate_context() {
312 global $USER, $DB;
314 $context = null;
315 if (isset($this->properties->courseid) && $this->properties->courseid > 0) {
316 $context = \context_course::instance($this->properties->courseid);
317 } else if (isset($this->properties->course) && $this->properties->course > 0) {
318 $context = \context_course::instance($this->properties->course);
319 } else if (isset($this->properties->groupid) && $this->properties->groupid > 0) {
320 $group = $DB->get_record('groups', array('id' => $this->properties->groupid));
321 $context = \context_course::instance($group->courseid);
322 } else if (isset($this->properties->userid) && $this->properties->userid > 0
323 && $this->properties->userid == $USER->id) {
324 $context = \context_user::instance($this->properties->userid);
325 } else if (isset($this->properties->userid) && $this->properties->userid > 0
326 && $this->properties->userid != $USER->id &&
327 isset($this->properties->instance) && $this->properties->instance > 0) {
328 $cm = get_coursemodule_from_instance($this->properties->modulename, $this->properties->instance, 0,
329 false, MUST_EXIST);
330 $context = \context_course::instance($cm->course);
331 } else {
332 $context = \context_user::instance($this->properties->userid);
335 return $context;
339 * Returns an array of editoroptions for this event.
341 * @return array event editor options
343 protected function get_editoroptions() {
344 return $this->editoroptions;
348 * Returns an event description: Called by __get
349 * Please use $blah = $event->description;
351 * @return string event description
353 protected function get_description() {
354 global $CFG;
356 require_once($CFG->libdir . '/filelib.php');
358 if ($this->_description === null) {
359 // Check if we have already resolved the context for this event.
360 if ($this->editorcontext === null) {
361 // Switch on the event type to decide upon the appropriate context to use for this event.
362 $this->editorcontext = $this->properties->context;
363 if ($this->properties->eventtype != 'user' && $this->properties->eventtype != 'course'
364 && $this->properties->eventtype != 'site' && $this->properties->eventtype != 'group') {
365 return clean_text($this->properties->description, $this->properties->format);
369 // Work out the item id for the editor, if this is a repeated event
370 // then the files will be associated with the original.
371 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
372 $itemid = $this->properties->repeatid;
373 } else {
374 $itemid = $this->properties->id;
377 // Convert file paths in the description so that things display correctly.
378 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php',
379 $this->editorcontext->id, 'calendar', 'event_description', $itemid);
380 // Clean the text so no nasties get through.
381 $this->_description = clean_text($this->_description, $this->properties->format);
384 // Finally return the description.
385 return $this->_description;
389 * Return the number of repeat events there are in this events series.
391 * @return int number of event repeated
393 public function count_repeats() {
394 global $DB;
395 if (!empty($this->properties->repeatid)) {
396 $this->properties->eventrepeats = $DB->count_records('event',
397 array('repeatid' => $this->properties->repeatid));
398 // We don't want to count ourselves.
399 $this->properties->eventrepeats--;
401 return $this->properties->eventrepeats;
405 * Update or create an event within the database
407 * Pass in a object containing the event properties and this function will
408 * insert it into the database and deal with any associated files
410 * @see self::create()
411 * @see self::update()
413 * @param \stdClass $data object of event
414 * @param bool $checkcapability if moodle should check calendar managing capability or not
415 * @return bool event updated
417 public function update($data, $checkcapability=true) {
418 global $DB, $USER;
420 foreach ($data as $key => $value) {
421 $this->properties->$key = $value;
424 $this->properties->timemodified = time();
425 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
427 // Prepare event data.
428 $eventargs = array(
429 'context' => $this->properties->context,
430 'objectid' => $this->properties->id,
431 'other' => array(
432 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
433 'timestart' => $this->properties->timestart,
434 'name' => $this->properties->name
438 if (empty($this->properties->id) || $this->properties->id < 1) {
440 if ($checkcapability) {
441 if (!calendar_add_event_allowed($this->properties)) {
442 print_error('nopermissiontoupdatecalendar');
446 if ($usingeditor) {
447 switch ($this->properties->eventtype) {
448 case 'user':
449 $this->properties->courseid = 0;
450 $this->properties->course = 0;
451 $this->properties->groupid = 0;
452 $this->properties->userid = $USER->id;
453 break;
454 case 'site':
455 $this->properties->courseid = SITEID;
456 $this->properties->course = SITEID;
457 $this->properties->groupid = 0;
458 $this->properties->userid = $USER->id;
459 break;
460 case 'course':
461 $this->properties->groupid = 0;
462 $this->properties->userid = $USER->id;
463 break;
464 case 'group':
465 $this->properties->userid = $USER->id;
466 break;
467 default:
468 // We should NEVER get here, but just incase we do lets fail gracefully.
469 $usingeditor = false;
470 break;
473 // If we are actually using the editor, we recalculate the context because some default values
474 // were set when calculate_context() was called from the constructor.
475 if ($usingeditor) {
476 $this->properties->context = $this->calculate_context();
477 $this->editorcontext = $this->properties->context;
480 $editor = $this->properties->description;
481 $this->properties->format = $this->properties->description['format'];
482 $this->properties->description = $this->properties->description['text'];
485 // Insert the event into the database.
486 $this->properties->id = $DB->insert_record('event', $this->properties);
488 if ($usingeditor) {
489 $this->properties->description = file_save_draft_area_files(
490 $editor['itemid'],
491 $this->editorcontext->id,
492 'calendar',
493 'event_description',
494 $this->properties->id,
495 $this->editoroptions,
496 $editor['text'],
497 $this->editoroptions['forcehttps']);
498 $DB->set_field('event', 'description', $this->properties->description,
499 array('id' => $this->properties->id));
502 // Log the event entry.
503 $eventargs['objectid'] = $this->properties->id;
504 $eventargs['context'] = $this->properties->context;
505 $event = \core\event\calendar_event_created::create($eventargs);
506 $event->trigger();
508 $repeatedids = array();
510 if (!empty($this->properties->repeat)) {
511 $this->properties->repeatid = $this->properties->id;
512 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id' => $this->properties->id));
514 $eventcopy = clone($this->properties);
515 unset($eventcopy->id);
517 $timestart = new \DateTime('@' . $eventcopy->timestart);
518 $timestart->setTimezone(\core_date::get_user_timezone_object());
520 for ($i = 1; $i < $eventcopy->repeats; $i++) {
522 $timestart->add(new \DateInterval('P7D'));
523 $eventcopy->timestart = $timestart->getTimestamp();
525 // Get the event id for the log record.
526 $eventcopyid = $DB->insert_record('event', $eventcopy);
528 // If the context has been set delete all associated files.
529 if ($usingeditor) {
530 $fs = get_file_storage();
531 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description',
532 $this->properties->id);
533 foreach ($files as $file) {
534 $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
538 $repeatedids[] = $eventcopyid;
540 // Trigger an event.
541 $eventargs['objectid'] = $eventcopyid;
542 $eventargs['other']['timestart'] = $eventcopy->timestart;
543 $event = \core\event\calendar_event_created::create($eventargs);
544 $event->trigger();
548 return true;
549 } else {
551 if ($checkcapability) {
552 if (!calendar_edit_event_allowed($this->properties)) {
553 print_error('nopermissiontoupdatecalendar');
557 if ($usingeditor) {
558 if ($this->editorcontext !== null) {
559 $this->properties->description = file_save_draft_area_files(
560 $this->properties->description['itemid'],
561 $this->editorcontext->id,
562 'calendar',
563 'event_description',
564 $this->properties->id,
565 $this->editoroptions,
566 $this->properties->description['text'],
567 $this->editoroptions['forcehttps']);
568 } else {
569 $this->properties->format = $this->properties->description['format'];
570 $this->properties->description = $this->properties->description['text'];
574 $event = $DB->get_record('event', array('id' => $this->properties->id));
576 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
578 if ($updaterepeated) {
579 // Update all.
580 if ($this->properties->timestart != $event->timestart) {
581 $timestartoffset = $this->properties->timestart - $event->timestart;
582 $sql = "UPDATE {event}
583 SET name = ?,
584 description = ?,
585 timestart = timestart + ?,
586 timeduration = ?,
587 timemodified = ?
588 WHERE repeatid = ?";
589 $params = array($this->properties->name, $this->properties->description, $timestartoffset,
590 $this->properties->timeduration, time(), $event->repeatid);
591 } else {
592 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
593 $params = array($this->properties->name, $this->properties->description,
594 $this->properties->timeduration, time(), $event->repeatid);
596 $DB->execute($sql, $params);
598 // Trigger an update event for each of the calendar event.
599 $events = $DB->get_records('event', array('repeatid' => $event->repeatid), '', '*');
600 foreach ($events as $calendarevent) {
601 $eventargs['objectid'] = $calendarevent->id;
602 $eventargs['other']['timestart'] = $calendarevent->timestart;
603 $event = \core\event\calendar_event_updated::create($eventargs);
604 $event->add_record_snapshot('event', $calendarevent);
605 $event->trigger();
607 } else {
608 $DB->update_record('event', $this->properties);
609 $event = self::load($this->properties->id);
610 $this->properties = $event->properties();
612 // Trigger an update event.
613 $event = \core\event\calendar_event_updated::create($eventargs);
614 $event->add_record_snapshot('event', $this->properties);
615 $event->trigger();
618 return true;
623 * Deletes an event and if selected an repeated events in the same series
625 * This function deletes an event, any associated events if $deleterepeated=true,
626 * and cleans up any files associated with the events.
628 * @see self::delete()
630 * @param bool $deleterepeated delete event repeatedly
631 * @return bool succession of deleting event
633 public function delete($deleterepeated = false) {
634 global $DB;
636 // If $this->properties->id is not set then something is wrong.
637 if (empty($this->properties->id)) {
638 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
639 return false;
641 $calevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
642 // Delete the event.
643 $DB->delete_records('event', array('id' => $this->properties->id));
645 // Trigger an event for the delete action.
646 $eventargs = array(
647 'context' => $this->properties->context,
648 'objectid' => $this->properties->id,
649 'other' => array(
650 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
651 'timestart' => $this->properties->timestart,
652 'name' => $this->properties->name
654 $event = \core\event\calendar_event_deleted::create($eventargs);
655 $event->add_record_snapshot('event', $calevent);
656 $event->trigger();
658 // If we are deleting parent of a repeated event series, promote the next event in the series as parent.
659 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
660 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC",
661 array($this->properties->id), IGNORE_MULTIPLE);
662 if (!empty($newparent)) {
663 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?",
664 array($newparent, $this->properties->id));
665 // Get all records where the repeatid is the same as the event being removed.
666 $events = $DB->get_records('event', array('repeatid' => $newparent));
667 // For each of the returned events trigger an update event.
668 foreach ($events as $calendarevent) {
669 // Trigger an event for the update.
670 $eventargs['objectid'] = $calendarevent->id;
671 $eventargs['other']['timestart'] = $calendarevent->timestart;
672 $event = \core\event\calendar_event_updated::create($eventargs);
673 $event->add_record_snapshot('event', $calendarevent);
674 $event->trigger();
679 // If the editor context hasn't already been set then set it now.
680 if ($this->editorcontext === null) {
681 $this->editorcontext = $this->properties->context;
684 // If the context has been set delete all associated files.
685 if ($this->editorcontext !== null) {
686 $fs = get_file_storage();
687 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
688 foreach ($files as $file) {
689 $file->delete();
693 // If we need to delete repeated events then we will fetch them all and delete one by one.
694 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
695 // Get all records where the repeatid is the same as the event being removed.
696 $events = $DB->get_records('event', array('repeatid' => $this->properties->repeatid));
697 // For each of the returned events populate an event object and call delete.
698 // make sure the arg passed is false as we are already deleting all repeats.
699 foreach ($events as $event) {
700 $event = new calendar_event($event);
701 $event->delete(false);
705 return true;
709 * Fetch all event properties.
711 * This function returns all of the events properties as an object and optionally
712 * can prepare an editor for the description field at the same time. This is
713 * designed to work when the properties are going to be used to set the default
714 * values of a moodle forms form.
716 * @param bool $prepareeditor If set to true a editor is prepared for use with
717 * the mforms editor element. (for description)
718 * @return \stdClass Object containing event properties
720 public function properties($prepareeditor = false) {
721 global $DB;
723 // First take a copy of the properties. We don't want to actually change the
724 // properties or we'd forever be converting back and forwards between an
725 // editor formatted description and not.
726 $properties = clone($this->properties);
727 // Clean the description here.
728 $properties->description = clean_text($properties->description, $properties->format);
730 // If set to true we need to prepare the properties for use with an editor
731 // and prepare the file area.
732 if ($prepareeditor) {
734 // We may or may not have a property id. If we do then we need to work
735 // out the context so we can copy the existing files to the draft area.
736 if (!empty($properties->id)) {
738 if ($properties->eventtype === 'site') {
739 // Site context.
740 $this->editorcontext = $this->properties->context;
741 } else if ($properties->eventtype === 'user') {
742 // User context.
743 $this->editorcontext = $this->properties->context;
744 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
745 // First check the course is valid.
746 $course = $DB->get_record('course', array('id' => $properties->courseid));
747 if (!$course) {
748 print_error('invalidcourse');
750 // Course context.
751 $this->editorcontext = $this->properties->context;
752 // We have a course and are within the course context so we had
753 // better use the courses max bytes value.
754 $this->editoroptions['maxbytes'] = $course->maxbytes;
755 } else {
756 // If we get here we have a custom event type as used by some
757 // modules. In this case the event will have been added by
758 // code and we won't need the editor.
759 $this->editoroptions['maxbytes'] = 0;
760 $this->editoroptions['maxfiles'] = 0;
763 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
764 $contextid = false;
765 } else {
766 // Get the context id that is what we really want.
767 $contextid = $this->editorcontext->id;
769 } else {
771 // If we get here then this is a new event in which case we don't need a
772 // context as there is no existing files to copy to the draft area.
773 $contextid = null;
776 // If the contextid === false we don't support files so no preparing
777 // a draft area.
778 if ($contextid !== false) {
779 // Just encase it has already been submitted.
780 $draftiddescription = file_get_submitted_draft_itemid('description');
781 // Prepare the draft area, this copies existing files to the draft area as well.
782 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar',
783 'event_description', $properties->id, $this->editoroptions, $properties->description);
784 } else {
785 $draftiddescription = 0;
788 // Structure the description field as the editor requires.
789 $properties->description = array('text' => $properties->description, 'format' => $properties->format,
790 'itemid' => $draftiddescription);
793 // Finally return the properties.
794 return $properties;
798 * Toggles the visibility of an event
800 * @param null|bool $force If it is left null the events visibility is flipped,
801 * If it is false the event is made hidden, if it is true it
802 * is made visible.
803 * @return bool if event is successfully updated, toggle will be visible
805 public function toggle_visibility($force = null) {
806 global $DB;
808 // Set visible to the default if it is not already set.
809 if (empty($this->properties->visible)) {
810 $this->properties->visible = 1;
813 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
814 // Make this event visible.
815 $this->properties->visible = 1;
816 } else {
817 // Make this event hidden.
818 $this->properties->visible = 0;
821 // Update the database to reflect this change.
822 $success = $DB->set_field('event', 'visible', $this->properties->visible, array('id' => $this->properties->id));
823 $calendarevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
825 // Prepare event data.
826 $eventargs = array(
827 'context' => $this->properties->context,
828 'objectid' => $this->properties->id,
829 'other' => array(
830 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
831 'timestart' => $this->properties->timestart,
832 'name' => $this->properties->name
835 $event = \core\event\calendar_event_updated::create($eventargs);
836 $event->add_record_snapshot('event', $calendarevent);
837 $event->trigger();
839 return $success;
843 * Returns an event object when provided with an event id.
845 * This function makes use of MUST_EXIST, if the event id passed in is invalid
846 * it will result in an exception being thrown.
848 * @param int|object $param event object or event id
849 * @return calendar_event
851 public static function load($param) {
852 global $DB;
853 if (is_object($param)) {
854 $event = new calendar_event($param);
855 } else {
856 $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST);
857 $event = new calendar_event($event);
859 return $event;
863 * Creates a new event and returns an event object
865 * @param \stdClass|array $properties An object containing event properties
866 * @param bool $checkcapability Check caps or not
867 * @throws \coding_exception
869 * @return calendar_event|bool The event object or false if it failed
871 public static function create($properties, $checkcapability = true) {
872 if (is_array($properties)) {
873 $properties = (object)$properties;
875 if (!is_object($properties)) {
876 throw new \coding_exception('When creating an event properties should be either an object or an assoc array');
878 $event = new calendar_event($properties);
879 if ($event->update($properties, $checkcapability)) {
880 return $event;
881 } else {
882 return false;
887 * Format the text using the external API.
889 * This function should we used when text formatting is required in external functions.
891 * @return array an array containing the text formatted and the text format
893 public function format_external_text() {
895 if ($this->editorcontext === null) {
896 // Switch on the event type to decide upon the appropriate context to use for this event.
897 $this->editorcontext = $this->properties->context;
899 if ($this->properties->eventtype != 'user' && $this->properties->eventtype != 'course'
900 && $this->properties->eventtype != 'site' && $this->properties->eventtype != 'group') {
901 // We don't have a context here, do a normal format_text.
902 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id);
906 // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
907 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
908 $itemid = $this->properties->repeatid;
909 } else {
910 $itemid = $this->properties->id;
913 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id,
914 'calendar', 'event_description', $itemid);
919 * Calendar information class
921 * This class is used simply to organise the information pertaining to a calendar
922 * and is used primarily to make information easily available.
924 * @package core_calendar
925 * @category calendar
926 * @copyright 2010 Sam Hemelryk
927 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
929 class calendar_information {
932 * @var int The timestamp
934 * Rather than setting the day, month and year we will set a timestamp which will be able
935 * to be used by multiple calendars.
937 public $time;
939 /** @var int A course id */
940 public $courseid = null;
942 /** @var array An array of courses */
943 public $courses = array();
945 /** @var array An array of groups */
946 public $groups = array();
948 /** @var array An array of users */
949 public $users = array();
952 * Creates a new instance
954 * @param int $day the number of the day
955 * @param int $month the number of the month
956 * @param int $year the number of the year
957 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
958 * and $calyear to support multiple calendars
960 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
961 // If a day, month and year were passed then convert it to a timestamp. If these were passed
962 // then we can assume the day, month and year are passed as Gregorian, as no where in core
963 // should we be passing these values rather than the time. This is done for BC.
964 if (!empty($day) || !empty($month) || !empty($year)) {
965 $date = usergetdate(time());
966 if (empty($day)) {
967 $day = $date['mday'];
969 if (empty($month)) {
970 $month = $date['mon'];
972 if (empty($year)) {
973 $year = $date['year'];
975 if (checkdate($month, $day, $year)) {
976 $this->time = make_timestamp($year, $month, $day);
977 } else {
978 $this->time = time();
980 } else if (!empty($time)) {
981 $this->time = $time;
982 } else {
983 $this->time = time();
988 * Initialize calendar information
990 * @param stdClass $course object
991 * @param array $coursestoload An array of courses [$course->id => $course]
992 * @param bool $ignorefilters options to use filter
994 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
995 $this->courseid = $course->id;
996 $this->course = $course;
997 list($courses, $group, $user) = calendar_set_filters($coursestoload, $ignorefilters);
998 $this->courses = $courses;
999 $this->groups = $group;
1000 $this->users = $user;
1004 * Ensures the date for the calendar is correct and either sets it to now
1005 * or throws a moodle_exception if not
1007 * @param bool $defaultonow use current time
1008 * @throws moodle_exception
1009 * @return bool validation of checkdate
1011 public function checkdate($defaultonow = true) {
1012 if (!checkdate($this->month, $this->day, $this->year)) {
1013 if ($defaultonow) {
1014 $now = usergetdate(time());
1015 $this->day = intval($now['mday']);
1016 $this->month = intval($now['mon']);
1017 $this->year = intval($now['year']);
1018 return true;
1019 } else {
1020 throw new moodle_exception('invaliddate');
1023 return true;
1027 * Gets todays timestamp for the calendar
1029 * @return int today timestamp
1031 public function timestamp_today() {
1032 return $this->time;
1035 * Gets tomorrows timestamp for the calendar
1037 * @return int tomorrow timestamp
1039 public function timestamp_tomorrow() {
1040 return strtotime('+1 day', $this->time);
1043 * Adds the pretend blocks for the calendar
1045 * @param core_calendar_renderer $renderer
1046 * @param bool $showfilters display filters, false is set as default
1047 * @param string|null $view preference view options (eg: day, month, upcoming)
1049 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
1050 if ($showfilters) {
1051 $filters = new block_contents();
1052 $filters->content = $renderer->fake_block_filters($this->courseid, 0, 0, 0, $view, $this->courses);
1053 $filters->footer = '';
1054 $filters->title = get_string('eventskey', 'calendar');
1055 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
1057 $block = new block_contents;
1058 $block->content = $renderer->fake_block_threemonths($this);
1059 $block->footer = '';
1060 $block->title = get_string('monthlyview', 'calendar');
1061 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
1066 * Get calendar events.
1068 * @param int $tstart Start time of time range for events
1069 * @param int $tend End time of time range for events
1070 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
1071 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
1072 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
1073 * @param boolean $withduration whether only events starting within time range selected
1074 * or events in progress/already started selected as well
1075 * @param boolean $ignorehidden whether to select only visible events or all events
1076 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
1078 function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
1079 global $DB;
1081 $whereclause = '';
1082 $params = array();
1083 // Quick test.
1084 if (empty($users) && empty($groups) && empty($courses)) {
1085 return array();
1088 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
1089 // Events from a number of users
1090 if(!empty($whereclause)) $whereclause .= ' OR';
1091 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED);
1092 $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0)";
1093 $params = array_merge($params, $inparamsusers);
1094 } else if($users === true) {
1095 // Events from ALL users
1096 if(!empty($whereclause)) $whereclause .= ' OR';
1097 $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0)';
1098 } else if($users === false) {
1099 // No user at all, do nothing
1102 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
1103 // Events from a number of groups
1104 if(!empty($whereclause)) $whereclause .= ' OR';
1105 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED);
1106 $whereclause .= " e.groupid $insqlgroups ";
1107 $params = array_merge($params, $inparamsgroups);
1108 } else if($groups === true) {
1109 // Events from ALL groups
1110 if(!empty($whereclause)) $whereclause .= ' OR ';
1111 $whereclause .= ' e.groupid != 0';
1113 // boolean false (no groups at all): we don't need to do anything
1115 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
1116 if(!empty($whereclause)) $whereclause .= ' OR';
1117 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED);
1118 $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
1119 $params = array_merge($params, $inparamscourses);
1120 } else if ($courses === true) {
1121 // Events from ALL courses
1122 if(!empty($whereclause)) $whereclause .= ' OR';
1123 $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
1126 // Security check: if, by now, we have NOTHING in $whereclause, then it means
1127 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
1128 // events no matter what. Allowing the code to proceed might return a completely
1129 // valid query with only time constraints, thus selecting ALL events in that time frame!
1130 if(empty($whereclause)) {
1131 return array();
1134 if($withduration) {
1135 $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1137 else {
1138 $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1140 if(!empty($whereclause)) {
1141 // We have additional constraints
1142 $whereclause = $timeclause.' AND ('.$whereclause.')';
1144 else {
1145 // Just basic time filtering
1146 $whereclause = $timeclause;
1149 if ($ignorehidden) {
1150 $whereclause .= ' AND e.visible = 1';
1153 $sql = "SELECT e.*
1154 FROM {event} e
1155 LEFT JOIN {modules} m ON e.modulename = m.name
1156 -- Non visible modules will have a value of 0.
1157 WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
1158 ORDER BY e.timestart";
1159 $events = $DB->get_records_sql($sql, $params);
1161 if ($events === false) {
1162 $events = array();
1164 return $events;
1168 * Return the days of the week.
1170 * @return array array of days
1172 function calendar_get_days() {
1173 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1174 return $calendartype->get_weekdays();
1178 * Get the subscription from a given id.
1180 * @since Moodle 2.5
1181 * @param int $id id of the subscription
1182 * @return stdClass Subscription record from DB
1183 * @throws moodle_exception for an invalid id
1185 function calendar_get_subscription($id) {
1186 global $DB;
1188 $cache = \cache::make('core', 'calendar_subscriptions');
1189 $subscription = $cache->get($id);
1190 if (empty($subscription)) {
1191 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
1192 $cache->set($id, $subscription);
1195 return $subscription;
1199 * Gets the first day of the week.
1201 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
1203 * @return int
1205 function calendar_get_starting_weekday() {
1206 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1207 return $calendartype->get_starting_weekday();
1211 * Generates the HTML for a miniature calendar.
1213 * @param array $courses list of course to list events from
1214 * @param array $groups list of group
1215 * @param array $users user's info
1216 * @param int|bool $calmonth calendar month in numeric, default is set to false
1217 * @param int|bool $calyear calendar month in numeric, default is set to false
1218 * @param string|bool $placement the place/page the calendar is set to appear - passed on the the controls function
1219 * @param int|bool $courseid id of the course the calendar is displayed on - passed on the the controls function
1220 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
1221 * and $calyear to support multiple calendars
1222 * @return string $content return html table for mini calendar
1224 function calendar_get_mini($courses, $groups, $users, $calmonth = false, $calyear = false, $placement = false,
1225 $courseid = false, $time = 0) {
1226 global $CFG, $OUTPUT;
1228 // Get the calendar type we are using.
1229 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1231 $display = new \stdClass;
1233 // Assume we are not displaying this month for now.
1234 $display->thismonth = false;
1236 $content = '';
1238 // Do this check for backwards compatibility.
1239 // The core should be passing a timestamp rather than month and year.
1240 // If a month and year are passed they will be in Gregorian.
1241 if (!empty($calmonth) && !empty($calyear)) {
1242 // Ensure it is a valid date, else we will just set it to the current timestamp.
1243 if (checkdate($calmonth, 1, $calyear)) {
1244 $time = make_timestamp($calyear, $calmonth, 1);
1245 } else {
1246 $time = time();
1248 $date = usergetdate($time);
1249 if ($calmonth == $date['mon'] && $calyear == $date['year']) {
1250 $display->thismonth = true;
1252 // We can overwrite date now with the date used by the calendar type,
1253 // if it is not Gregorian, otherwise there is no need as it is already in Gregorian.
1254 if ($calendartype->get_name() != 'gregorian') {
1255 $date = $calendartype->timestamp_to_date_array($time);
1257 } else if (!empty($time)) {
1258 // Get the specified date in the calendar type being used.
1259 $date = $calendartype->timestamp_to_date_array($time);
1260 $thisdate = $calendartype->timestamp_to_date_array(time());
1261 if ($date['month'] == $thisdate['month'] && $date['year'] == $thisdate['year']) {
1262 $display->thismonth = true;
1263 // If we are the current month we want to set the date to the current date, not the start of the month.
1264 $date = $thisdate;
1266 } else {
1267 // Get the current date in the calendar type being used.
1268 $time = time();
1269 $date = $calendartype->timestamp_to_date_array($time);
1270 $display->thismonth = true;
1273 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display.
1275 // Get Gregorian date for the start of the month.
1276 $gregoriandate = $calendartype->convert_to_gregorian($date['year'], $date['mon'], 1);
1278 // Store the gregorian date values to be used later.
1279 list($gy, $gm, $gd, $gh, $gmin) = array($gregoriandate['year'], $gregoriandate['month'], $gregoriandate['day'],
1280 $gregoriandate['hour'], $gregoriandate['minute']);
1282 // Get the max number of days in this month for this calendar type.
1283 $display->maxdays = calendar_days_in_month($m, $y);
1284 // Get the starting week day for this month.
1285 $startwday = dayofweek(1, $m, $y);
1286 // Get the days in a week.
1287 $daynames = calendar_get_days();
1288 // Store the number of days in a week.
1289 $numberofdaysinweek = $calendartype->get_num_weekdays();
1291 // Set the min and max weekday.
1292 $display->minwday = calendar_get_starting_weekday();
1293 $display->maxwday = $display->minwday + ($numberofdaysinweek - 1);
1295 // These are used for DB queries, so we want unixtime, so we need to use Gregorian dates.
1296 $display->tstart = make_timestamp($gy, $gm, $gd, $gh, $gmin, 0);
1297 $display->tend = $display->tstart + ($display->maxdays * DAYSECS) - 1;
1299 // Align the starting weekday to fall in our display range.
1300 // This is simple, not foolproof.
1301 if ($startwday < $display->minwday) {
1302 $startwday += $numberofdaysinweek;
1305 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ.
1306 $events = calendar_get_legacy_events($display->tstart, $display->tend, $users, $groups, $courses);
1308 // Set event course class for course events.
1309 if (!empty($events)) {
1310 foreach ($events as $eventid => $event) {
1311 if (!empty($event->modulename)) {
1312 $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
1313 if (empty($instances[$event->instance]->uservisible)) {
1314 unset($events[$eventid]);
1320 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
1321 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
1322 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
1323 // arguments to this function.
1324 $hrefparams = array();
1325 if (!empty($courses)) {
1326 $courses = array_diff($courses, array(SITEID));
1327 if (count($courses) == 1) {
1328 $hrefparams['course'] = reset($courses);
1332 // We want to have easy access by day, since the display is on a per-day basis.
1333 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
1335 // Accessibility: added summary and <abbr> elements.
1336 $summary = get_string('calendarheading', 'calendar', userdate($display->tstart, get_string('strftimemonthyear')));
1337 // Begin table.
1338 $content .= '<table class="minicalendar calendartable" summary="' . $summary . '">';
1339 if (($placement !== false) && ($courseid !== false)) {
1340 $content .= '<caption>' . calendar_top_controls($placement,
1341 array('id' => $courseid, 'time' => $time)) . '</caption>';
1343 $content .= '<tr class="weekdays">'; // Header row: day names.
1345 // Print out the names of the weekdays.
1346 for ($i = $display->minwday; $i <= $display->maxwday; $i++) {
1347 $pos = $i % $numberofdaysinweek;
1348 $content .= '<th scope="col"><abbr title="' . $daynames[$pos]['fullname'] . '">' .
1349 $daynames[$pos]['shortname'] . "</abbr></th>\n";
1352 $content .= '</tr><tr>'; // End of day names; prepare for day numbers.
1354 // For the table display. $week is the row; $dayweek is the column.
1355 $dayweek = $startwday;
1357 // Padding (the first week may have blank days in the beginning).
1358 for ($i = $display->minwday; $i < $startwday; ++$i) {
1359 $content .= '<td class="dayblank">&nbsp;</td>' ."\n";
1362 $weekend = CALENDAR_DEFAULT_WEEKEND;
1363 if (isset($CFG->calendar_weekend)) {
1364 $weekend = intval($CFG->calendar_weekend);
1367 // Now display all the calendar.
1368 $daytime = strtotime('-1 day', $display->tstart);
1369 for ($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
1370 $cellattributes = array();
1371 $daytime = strtotime('+1 day', $daytime);
1372 if ($dayweek > $display->maxwday) {
1373 // We need to change week (table row).
1374 $content .= '</tr><tr>';
1375 $dayweek = $display->minwday;
1378 // Reset vars.
1379 if ($weekend & (1 << ($dayweek % $numberofdaysinweek))) {
1380 // Weekend. This is true no matter what the exact range is.
1381 $class = 'weekend day';
1382 } else {
1383 // Normal working day.
1384 $class = 'day';
1387 $eventids = array();
1388 if (!empty($eventsbyday[$day])) {
1389 $eventids = $eventsbyday[$day];
1392 if (!empty($durationbyday[$day])) {
1393 $eventids = array_unique(array_merge($eventids, $durationbyday[$day]));
1396 $finishclass = false;
1398 if (!empty($eventids)) {
1399 // There is at least one event on this day.
1400 $class .= ' hasevent';
1401 $hrefparams['view'] = 'day';
1402 $dayhref = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $hrefparams), 0, 0, 0, $daytime);
1404 $popupcontent = '';
1405 foreach ($eventids as $eventid) {
1406 if (!isset($events[$eventid])) {
1407 continue;
1409 $event = new \calendar_event($events[$eventid]);
1410 $popupalt = '';
1411 $component = 'moodle';
1412 if (!empty($event->modulename)) {
1413 $popupicon = 'icon';
1414 $popupalt = $event->modulename;
1415 $component = $event->modulename;
1416 } else if ($event->courseid == SITEID) { // Site event.
1417 $popupicon = 'i/siteevent';
1418 } else if ($event->courseid != 0 && $event->courseid != SITEID
1419 && $event->groupid == 0) { // Course event.
1420 $popupicon = 'i/courseevent';
1421 } else if ($event->groupid) { // Group event.
1422 $popupicon = 'i/groupevent';
1423 } else { // Must be a user event.
1424 $popupicon = 'i/userevent';
1427 if ($event->timeduration) {
1428 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
1429 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
1430 if ($enddate['mon'] == $m && $enddate['year'] == $y && $enddate['mday'] == $day) {
1431 $finishclass = true;
1435 $dayhref->set_anchor('event_' . $event->id);
1437 $popupcontent .= \html_writer::start_tag('div');
1438 $popupcontent .= $OUTPUT->pix_icon($popupicon, $popupalt, $component);
1439 // Show ical source if needed.
1440 if (!empty($event->subscription) && $CFG->calendar_showicalsource) {
1441 $a = new \stdClass();
1442 $a->name = format_string($event->name, true);
1443 $a->source = $event->subscription->name;
1444 $name = get_string('namewithsource', 'calendar', $a);
1445 } else {
1446 if ($finishclass) {
1447 $samedate = $startdate['mon'] == $enddate['mon'] &&
1448 $startdate['year'] == $enddate['year'] &&
1449 $startdate['mday'] == $enddate['mday'];
1451 if ($samedate) {
1452 $name = format_string($event->name, true);
1453 } else {
1454 $name = format_string($event->name, true) . ' (' . get_string('eventendtime', 'calendar') . ')';
1456 } else {
1457 $name = format_string($event->name, true);
1460 // Include course's shortname into the event name, if applicable.
1461 if (!empty($event->courseid) && $event->courseid !== SITEID) {
1462 $course = get_course($event->courseid);
1463 $eventnameparams = (object)[
1464 'name' => $name,
1465 'course' => format_string($course->shortname, true, array('context' => $event->context))
1467 $name = get_string('eventnameandcourse', 'calendar', $eventnameparams);
1469 $popupcontent .= \html_writer::link($dayhref, $name);
1470 $popupcontent .= \html_writer::end_tag('div');
1473 if ($display->thismonth && $day == $d) {
1474 $popupdata = calendar_get_popup(true, $daytime, $popupcontent);
1475 } else {
1476 $popupdata = calendar_get_popup(false, $daytime, $popupcontent);
1479 // Class and cell content.
1480 if (isset($typesbyday[$day]['startglobal'])) {
1481 $class .= ' calendar_event_global';
1482 } else if (isset($typesbyday[$day]['startcourse'])) {
1483 $class .= ' calendar_event_course';
1484 } else if (isset($typesbyday[$day]['startgroup'])) {
1485 $class .= ' calendar_event_group';
1486 } else if (isset($typesbyday[$day]['startuser'])) {
1487 $class .= ' calendar_event_user';
1489 if ($finishclass) {
1490 $class .= ' duration_finish';
1492 $data = array(
1493 'url' => $dayhref->out(false),
1494 'day' => $day,
1495 'content' => $popupdata['data-core_calendar-popupcontent'],
1496 'title' => $popupdata['data-core_calendar-title']
1498 $cell = $OUTPUT->render_from_template('core_calendar/minicalendar_day_link', $data);
1499 } else {
1500 $cell = $day;
1503 $durationclass = false;
1504 if (isset($typesbyday[$day]['durationglobal'])) {
1505 $durationclass = ' duration_global';
1506 } else if (isset($typesbyday[$day]['durationcourse'])) {
1507 $durationclass = ' duration_course';
1508 } else if (isset($typesbyday[$day]['durationgroup'])) {
1509 $durationclass = ' duration_group';
1510 } else if (isset($typesbyday[$day]['durationuser'])) {
1511 $durationclass = ' duration_user';
1513 if ($durationclass) {
1514 $class .= ' duration ' . $durationclass;
1517 // If event has a class set then add it to the table day <td> tag.
1518 // Note: only one colour for minicalendar.
1519 if (isset($eventsbyday[$day])) {
1520 foreach ($eventsbyday[$day] as $eventid) {
1521 if (!isset($events[$eventid])) {
1522 continue;
1524 $event = $events[$eventid];
1525 if (!empty($event->class)) {
1526 $class .= ' ' . $event->class;
1528 break;
1532 if ($display->thismonth && $day == $d) {
1533 // The current cell is for today - add appropriate classes and additional information for styling.
1534 $class .= ' today';
1535 $today = get_string('today', 'calendar') . ' ' . userdate(time(), get_string('strftimedayshort'));
1537 if (!isset($eventsbyday[$day]) && !isset($durationbyday[$day])) {
1538 $class .= ' eventnone';
1539 $popupdata = calendar_get_popup(true, false);
1540 $data = array(
1541 'url' => '#',
1542 'day' => $day,
1543 'content' => $popupdata['data-core_calendar-popupcontent'],
1544 'title' => $popupdata['data-core_calendar-title']
1546 $cell = $OUTPUT->render_from_template('core_calendar/minicalendar_day_link', $data);
1548 $cell = get_accesshide($today . ' ') . $cell;
1551 // Just display it.
1552 $cellattributes['class'] = $class;
1553 $content .= \html_writer::tag('td', $cell, $cellattributes);
1556 // Padding (the last week may have blank days at the end).
1557 for ($i = $dayweek; $i <= $display->maxwday; ++$i) {
1558 $content .= '<td class="dayblank">&nbsp;</td>';
1560 $content .= '</tr>'; // Last row ends.
1562 $content .= '</table>'; // Tabular display of days ends.
1563 return $content;
1567 * Gets the calendar popup.
1569 * It called at multiple points in from calendar_get_mini.
1570 * Copied and modified from calendar_get_mini.
1572 * @param bool $today false except when called on the current day.
1573 * @param mixed $timestart $events[$eventid]->timestart, OR false if there are no events.
1574 * @param string $popupcontent content for the popup window/layout.
1575 * @return string eventid for the calendar_tooltip popup window/layout.
1577 function calendar_get_popup($today = false, $timestart, $popupcontent = '') {
1578 $popupcaption = '';
1579 if ($today) {
1580 $popupcaption = get_string('today', 'calendar') . ' ';
1583 if (false === $timestart) {
1584 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
1585 $popupcontent = get_string('eventnone', 'calendar');
1587 } else {
1588 $popupcaption .= get_string('eventsfor', 'calendar', userdate($timestart, get_string('strftimedayshort')));
1591 return array(
1592 'data-core_calendar-title' => $popupcaption,
1593 'data-core_calendar-popupcontent' => $popupcontent,
1598 * Gets the calendar upcoming event.
1600 * @param array $courses array of courses
1601 * @param array|int|bool $groups array of groups, group id or boolean for all/no group events
1602 * @param array|int|bool $users array of users, user id or boolean for all/no user events
1603 * @param int $daysinfuture number of days in the future we 'll look
1604 * @param int $maxevents maximum number of events
1605 * @param int $fromtime start time
1606 * @return array $output array of upcoming events
1608 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
1609 global $COURSE;
1611 $display = new \stdClass;
1612 $display->range = $daysinfuture; // How many days in the future we 'll look.
1613 $display->maxevents = $maxevents;
1615 $output = array();
1617 $processed = 0;
1618 $now = time(); // We 'll need this later.
1619 $usermidnighttoday = usergetmidnight($now);
1621 if ($fromtime) {
1622 $display->tstart = $fromtime;
1623 } else {
1624 $display->tstart = $usermidnighttoday;
1627 // This works correctly with respect to the user's DST, but it is accurate
1628 // only because $fromtime is always the exact midnight of some day!
1629 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
1631 // Get the events matching our criteria.
1632 $events = calendar_get_legacy_events($display->tstart, $display->tend, $users, $groups, $courses);
1634 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
1635 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
1636 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
1637 // arguments to this function.
1638 $hrefparams = array();
1639 if (!empty($courses)) {
1640 $courses = array_diff($courses, array(SITEID));
1641 if (count($courses) == 1) {
1642 $hrefparams['course'] = reset($courses);
1646 if ($events !== false) {
1647 foreach ($events as $event) {
1648 if (!empty($event->modulename)) {
1649 $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
1650 if (empty($instances[$event->instance]->uservisible)) {
1651 continue;
1655 if ($processed >= $display->maxevents) {
1656 break;
1659 $event->time = calendar_format_event_time($event, $now, $hrefparams);
1660 $output[] = $event;
1661 $processed++;
1665 return $output;
1669 * Get a HTML link to a course.
1671 * @param int|stdClass $course the course id or course object
1672 * @return string a link to the course (as HTML); empty if the course id is invalid
1674 function calendar_get_courselink($course) {
1675 if (!$course) {
1676 return '';
1679 if (!is_object($course)) {
1680 $course = calendar_get_course_cached($coursecache, $course);
1682 $context = \context_course::instance($course->id);
1683 $fullname = format_string($course->fullname, true, array('context' => $context));
1684 $url = new \moodle_url('/course/view.php', array('id' => $course->id));
1685 $link = \html_writer::link($url, $fullname);
1687 return $link;
1691 * Get current module cache.
1693 * Only use this method if you do not know courseid. Otherwise use:
1694 * get_fast_modinfo($courseid)->instances[$modulename][$instance]
1696 * @param array $modulecache in memory module cache
1697 * @param string $modulename name of the module
1698 * @param int $instance module instance number
1699 * @return stdClass|bool $module information
1701 function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
1702 if (!isset($modulecache[$modulename . '_' . $instance])) {
1703 $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
1706 return $modulecache[$modulename . '_' . $instance];
1710 * Get current course cache.
1712 * @param array $coursecache list of course cache
1713 * @param int $courseid id of the course
1714 * @return stdClass $coursecache[$courseid] return the specific course cache
1716 function calendar_get_course_cached(&$coursecache, $courseid) {
1717 if (!isset($coursecache[$courseid])) {
1718 $coursecache[$courseid] = get_course($courseid);
1720 return $coursecache[$courseid];
1724 * Get group from groupid for calendar display
1726 * @param int $groupid
1727 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1729 function calendar_get_group_cached($groupid) {
1730 static $groupscache = array();
1731 if (!isset($groupscache[$groupid])) {
1732 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1734 return $groupscache[$groupid];
1738 * Add calendar event metadata
1740 * @param stdClass $event event info
1741 * @return stdClass $event metadata
1743 function calendar_add_event_metadata($event) {
1744 global $CFG, $OUTPUT;
1746 // Support multilang in event->name.
1747 $event->name = format_string($event->name, true);
1749 if (!empty($event->modulename)) { // Activity event.
1750 // The module name is set. I will assume that it has to be displayed, and
1751 // also that it is an automatically-generated event. And of course that the
1752 // instace id and modulename are set correctly.
1753 $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
1754 if (!array_key_exists($event->instance, $instances)) {
1755 return;
1757 $module = $instances[$event->instance];
1759 $modulename = $module->get_module_type_name(false);
1760 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
1761 // Will be used as alt text if the event icon.
1762 $eventtype = get_string($event->eventtype, $event->modulename);
1763 } else {
1764 $eventtype = '';
1767 $event->icon = '<img src="' . s($module->get_icon_url()) . '" alt="' . s($eventtype) .
1768 '" title="' . s($modulename) . '" class="icon" />';
1769 $event->referer = html_writer::link($module->url, $event->name);
1770 $event->courselink = calendar_get_courselink($module->get_course());
1771 $event->cmid = $module->id;
1772 } else if ($event->courseid == SITEID) { // Site event.
1773 $event->icon = '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
1774 get_string('globalevent', 'calendar') . '" class="icon" />';
1775 $event->cssclass = 'calendar_event_global';
1776 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event.
1777 $event->icon = '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
1778 get_string('courseevent', 'calendar') . '" class="icon" />';
1779 $event->courselink = calendar_get_courselink($event->courseid);
1780 $event->cssclass = 'calendar_event_course';
1781 } else if ($event->groupid) { // Group event.
1782 if ($group = calendar_get_group_cached($event->groupid)) {
1783 $groupname = format_string($group->name, true, \context_course::instance($group->courseid));
1784 } else {
1785 $groupname = '';
1787 $event->icon = \html_writer::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
1788 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
1789 $event->courselink = calendar_get_courselink($event->courseid) . ', ' . $groupname;
1790 $event->cssclass = 'calendar_event_group';
1791 } else if ($event->userid) { // User event.
1792 $event->icon = '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
1793 get_string('userevent', 'calendar') . '" class="icon" />';
1794 $event->cssclass = 'calendar_event_user';
1797 return $event;
1801 * Get calendar events by id.
1803 * @since Moodle 2.5
1804 * @param array $eventids list of event ids
1805 * @return array Array of event entries, empty array if nothing found
1807 function calendar_get_events_by_id($eventids) {
1808 global $DB;
1810 if (!is_array($eventids) || empty($eventids)) {
1811 return array();
1814 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
1815 $wheresql = "id $wheresql";
1817 return $DB->get_records_select('event', $wheresql, $params);
1821 * Get control options for calendar.
1823 * @param string $type of calendar
1824 * @param array $data calendar information
1825 * @return string $content return available control for the calender in html
1827 function calendar_top_controls($type, $data) {
1828 global $PAGE, $OUTPUT;
1830 // Get the calendar type we are using.
1831 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1833 $content = '';
1835 // Ensure course id passed if relevant.
1836 $courseid = '';
1837 if (!empty($data['id'])) {
1838 $courseid = '&amp;course=' . $data['id'];
1841 // If we are passing a month and year then we need to convert this to a timestamp to
1842 // support multiple calendars. No where in core should these be passed, this logic
1843 // here is for third party plugins that may use this function.
1844 if (!empty($data['m']) && !empty($date['y'])) {
1845 if (!isset($data['d'])) {
1846 $data['d'] = 1;
1848 if (!checkdate($data['m'], $data['d'], $data['y'])) {
1849 $time = time();
1850 } else {
1851 $time = make_timestamp($data['y'], $data['m'], $data['d']);
1853 } else if (!empty($data['time'])) {
1854 $time = $data['time'];
1855 } else {
1856 $time = time();
1859 // Get the date for the calendar type.
1860 $date = $calendartype->timestamp_to_date_array($time);
1862 $urlbase = $PAGE->url;
1864 // We need to get the previous and next months in certain cases.
1865 if ($type == 'frontpage' || $type == 'course' || $type == 'month') {
1866 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1867 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
1868 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
1869 $prevmonthtime['hour'], $prevmonthtime['minute']);
1871 $nextmonth = calendar_add_month($date['mon'], $date['year']);
1872 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
1873 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
1874 $nextmonthtime['hour'], $nextmonthtime['minute']);
1877 switch ($type) {
1878 case 'frontpage':
1879 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1880 true, $prevmonthtime);
1881 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true,
1882 $nextmonthtime);
1883 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1884 false, false, false, $time);
1886 if (!empty($data['id'])) {
1887 $calendarlink->param('course', $data['id']);
1890 $right = $nextlink;
1892 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1893 $content .= $prevlink . '<span class="hide"> | </span>';
1894 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1895 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1896 ), array('class' => 'current'));
1897 $content .= '<span class="hide"> | </span>' . $right;
1898 $content .= "<span class=\"clearer\"><!-- --></span>\n";
1899 $content .= \html_writer::end_tag('div');
1901 break;
1902 case 'course':
1903 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1904 true, $prevmonthtime);
1905 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false,
1906 true, $nextmonthtime);
1907 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1908 false, false, false, $time);
1910 if (!empty($data['id'])) {
1911 $calendarlink->param('course', $data['id']);
1914 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1915 $content .= $prevlink . '<span class="hide"> | </span>';
1916 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1917 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1918 ), array('class' => 'current'));
1919 $content .= '<span class="hide"> | </span>' . $nextlink;
1920 $content .= "<span class=\"clearer\"><!-- --></span>";
1921 $content .= \html_writer::end_tag('div');
1922 break;
1923 case 'upcoming':
1924 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'upcoming')),
1925 false, false, false, $time);
1926 if (!empty($data['id'])) {
1927 $calendarlink->param('course', $data['id']);
1929 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1930 $content .= \html_writer::tag('div', $calendarlink, array('class' => 'centered'));
1931 break;
1932 case 'display':
1933 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1934 false, false, false, $time);
1935 if (!empty($data['id'])) {
1936 $calendarlink->param('course', $data['id']);
1938 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1939 $content .= \html_writer::tag('h3', $calendarlink);
1940 break;
1941 case 'month':
1942 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1943 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $prevmonthtime);
1944 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1945 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $nextmonthtime);
1947 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1948 $content .= $prevlink . '<span class="hide"> | </span>';
1949 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1950 $content .= '<span class="hide"> | </span>' . $nextlink;
1951 $content .= '<span class="clearer"><!-- --></span>';
1952 $content .= \html_writer::end_tag('div')."\n";
1953 break;
1954 case 'day':
1955 $days = calendar_get_days();
1957 $prevtimestamp = strtotime('-1 day', $time);
1958 $nexttimestamp = strtotime('+1 day', $time);
1960 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1961 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1963 $prevname = $days[$prevdate['wday']]['fullname'];
1964 $nextname = $days[$nextdate['wday']]['fullname'];
1965 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&amp;', false, false,
1966 false, false, $prevtimestamp);
1967 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&amp;', false, false, false,
1968 false, $nexttimestamp);
1970 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1971 $content .= $prevlink;
1972 $content .= '<span class="hide"> | </span><span class="current">' .userdate($time,
1973 get_string('strftimedaydate')) . '</span>';
1974 $content .= '<span class="hide"> | </span>' . $nextlink;
1975 $content .= "<span class=\"clearer\"><!-- --></span>";
1976 $content .= \html_writer::end_tag('div') . "\n";
1978 break;
1981 return $content;
1985 * Formats a filter control element.
1987 * @param moodle_url $url of the filter
1988 * @param int $type constant defining the type filter
1989 * @return string html content of the element
1991 function calendar_filter_controls_element(moodle_url $url, $type) {
1992 global $OUTPUT;
1994 switch ($type) {
1995 case CALENDAR_EVENT_GLOBAL:
1996 $typeforhumans = 'global';
1997 $class = 'calendar_event_global';
1998 break;
1999 case CALENDAR_EVENT_COURSE:
2000 $typeforhumans = 'course';
2001 $class = 'calendar_event_course';
2002 break;
2003 case CALENDAR_EVENT_GROUP:
2004 $typeforhumans = 'groups';
2005 $class = 'calendar_event_group';
2006 break;
2007 case CALENDAR_EVENT_USER:
2008 $typeforhumans = 'user';
2009 $class = 'calendar_event_user';
2010 break;
2013 if (calendar_show_event_type($type)) {
2014 $icon = $OUTPUT->pix_icon('t/hide', get_string('hide'));
2015 $str = get_string('hide' . $typeforhumans . 'events', 'calendar');
2016 } else {
2017 $icon = $OUTPUT->pix_icon('t/show', get_string('show'));
2018 $str = get_string('show' . $typeforhumans . 'events', 'calendar');
2020 $content = \html_writer::start_tag('li', array('class' => 'calendar_event'));
2021 $content .= \html_writer::start_tag('a', array('href' => $url, 'rel' => 'nofollow'));
2022 $content .= \html_writer::tag('span', $icon, array('class' => $class));
2023 $content .= \html_writer::tag('span', $str, array('class' => 'eventname'));
2024 $content .= \html_writer::end_tag('a');
2025 $content .= \html_writer::end_tag('li');
2027 return $content;
2031 * Get the controls filter for calendar.
2033 * Filter is used to hide calendar info from the display page.
2036 * @param moodle_url $returnurl return-url for filter controls
2037 * @return string $content return filter controls in html
2039 function calendar_filter_controls(moodle_url $returnurl) {
2040 $groupevents = true;
2042 $seturl = new \moodle_url('/calendar/set.php', array('return' => base64_encode($returnurl->out_as_local_url(false)),
2043 'sesskey' => sesskey()));
2044 $content = \html_writer::start_tag('ul');
2046 $seturl->param('var', 'showglobal');
2047 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GLOBAL);
2049 $seturl->param('var', 'showcourses');
2050 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_COURSE);
2052 if (isloggedin() && !isguestuser()) {
2053 if ($groupevents) {
2054 // This course MIGHT have group events defined, so show the filter.
2055 $seturl->param('var', 'showgroups');
2056 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GROUP);
2058 $seturl->param('var', 'showuser');
2059 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_USER);
2061 $content .= \html_writer::end_tag('ul');
2063 return $content;
2067 * Return the representation day.
2069 * @param int $tstamp Timestamp in GMT
2070 * @param int|bool $now current Unix timestamp
2071 * @param bool $usecommonwords
2072 * @return string the formatted date/time
2074 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
2075 static $shortformat;
2077 if (empty($shortformat)) {
2078 $shortformat = get_string('strftimedayshort');
2081 if ($now === false) {
2082 $now = time();
2085 // To have it in one place, if a change is needed.
2086 $formal = userdate($tstamp, $shortformat);
2088 $datestamp = usergetdate($tstamp);
2089 $datenow = usergetdate($now);
2091 if ($usecommonwords == false) {
2092 // We don't want words, just a date.
2093 return $formal;
2094 } else if ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
2095 return get_string('today', 'calendar');
2096 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
2097 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12
2098 && $datenow['yday'] == 1)) {
2099 return get_string('yesterday', 'calendar');
2100 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
2101 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12
2102 && $datestamp['yday'] == 1)) {
2103 return get_string('tomorrow', 'calendar');
2104 } else {
2105 return $formal;
2110 * return the formatted representation time.
2113 * @param int $time the timestamp in UTC, as obtained from the database
2114 * @return string the formatted date/time
2116 function calendar_time_representation($time) {
2117 static $langtimeformat = null;
2119 if ($langtimeformat === null) {
2120 $langtimeformat = get_string('strftimetime');
2123 $timeformat = get_user_preferences('calendar_timeformat');
2124 if (empty($timeformat)) {
2125 $timeformat = get_config(null, 'calendar_site_timeformat');
2128 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
2132 * Adds day, month, year arguments to a URL and returns a moodle_url object.
2134 * @param string|moodle_url $linkbase
2135 * @param int $d The number of the day.
2136 * @param int $m The number of the month.
2137 * @param int $y The number of the year.
2138 * @param int $time the unixtime, used for multiple calendar support. The values $d,
2139 * $m and $y are kept for backwards compatibility.
2140 * @return moodle_url|null $linkbase
2142 function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
2143 if (empty($linkbase)) {
2144 return null;
2147 if (!($linkbase instanceof \moodle_url)) {
2148 $linkbase = new \moodle_url($linkbase);
2151 $linkbase->param('time', calendar_get_timestamp($d, $m, $y, $time));
2153 return $linkbase;
2157 * Build and return a previous month HTML link, with an arrow.
2159 * @param string $text The text label.
2160 * @param string|moodle_url $linkbase The URL stub.
2161 * @param int $d The number of the date.
2162 * @param int $m The number of the month.
2163 * @param int $y year The number of the year.
2164 * @param bool $accesshide Default visible, or hide from all except screenreaders.
2165 * @param int $time the unixtime, used for multiple calendar support. The values $d,
2166 * $m and $y are kept for backwards compatibility.
2167 * @return string HTML string.
2169 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
2170 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
2172 if (empty($href)) {
2173 return $text;
2176 $attrs = [
2177 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
2178 'data-drop-zone' => 'nav-link',
2181 return link_arrow_left($text, $href->out(false), $accesshide, 'previous', $attrs);
2185 * Build and return a next month HTML link, with an arrow.
2187 * @param string $text The text label.
2188 * @param string|moodle_url $linkbase The URL stub.
2189 * @param int $d the number of the Day
2190 * @param int $m The number of the month.
2191 * @param int $y The number of the year.
2192 * @param bool $accesshide Default visible, or hide from all except screenreaders.
2193 * @param int $time the unixtime, used for multiple calendar support. The values $d,
2194 * $m and $y are kept for backwards compatibility.
2195 * @return string HTML string.
2197 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
2198 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
2200 if (empty($href)) {
2201 return $text;
2204 $attrs = [
2205 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
2206 'data-drop-zone' => 'nav-link',
2209 return link_arrow_right($text, $href->out(false), $accesshide, 'next', $attrs);
2213 * Return the number of days in month.
2215 * @param int $month the number of the month.
2216 * @param int $year the number of the year
2217 * @return int
2219 function calendar_days_in_month($month, $year) {
2220 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2221 return $calendartype->get_num_days_in_month($year, $month);
2225 * Get the next following month.
2227 * @param int $month the number of the month.
2228 * @param int $year the number of the year.
2229 * @return array the following month
2231 function calendar_add_month($month, $year) {
2232 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2233 return $calendartype->get_next_month($year, $month);
2237 * Get the previous month.
2239 * @param int $month the number of the month.
2240 * @param int $year the number of the year.
2241 * @return array previous month
2243 function calendar_sub_month($month, $year) {
2244 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2245 return $calendartype->get_prev_month($year, $month);
2249 * Get per-day basis events
2251 * @param array $events list of events
2252 * @param int $month the number of the month
2253 * @param int $year the number of the year
2254 * @param array $eventsbyday event on specific day
2255 * @param array $durationbyday duration of the event in days
2256 * @param array $typesbyday event type (eg: global, course, user, or group)
2257 * @param array $courses list of courses
2258 * @return void
2260 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
2261 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2263 $eventsbyday = array();
2264 $typesbyday = array();
2265 $durationbyday = array();
2267 if ($events === false) {
2268 return;
2271 foreach ($events as $event) {
2272 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
2273 if ($event->timeduration) {
2274 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
2275 } else {
2276 $enddate = $startdate;
2279 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair.
2280 if (!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) &&
2281 ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
2282 continue;
2285 $eventdaystart = intval($startdate['mday']);
2287 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2288 // Give the event to its day.
2289 $eventsbyday[$eventdaystart][] = $event->id;
2291 // Mark the day as having such an event.
2292 if ($event->courseid == SITEID && $event->groupid == 0) {
2293 $typesbyday[$eventdaystart]['startglobal'] = true;
2294 // Set event class for global event.
2295 $events[$event->id]->class = 'calendar_event_global';
2296 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
2297 $typesbyday[$eventdaystart]['startcourse'] = true;
2298 // Set event class for course event.
2299 $events[$event->id]->class = 'calendar_event_course';
2300 } else if ($event->groupid) {
2301 $typesbyday[$eventdaystart]['startgroup'] = true;
2302 // Set event class for group event.
2303 $events[$event->id]->class = 'calendar_event_group';
2304 } else if ($event->userid) {
2305 $typesbyday[$eventdaystart]['startuser'] = true;
2306 // Set event class for user event.
2307 $events[$event->id]->class = 'calendar_event_user';
2311 if ($event->timeduration == 0) {
2312 // Proceed with the next.
2313 continue;
2316 // The event starts on $month $year or before.
2317 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2318 $lowerbound = intval($startdate['mday']);
2319 } else {
2320 $lowerbound = 0;
2323 // Also, it ends on $month $year or later.
2324 if ($enddate['mon'] == $month && $enddate['year'] == $year) {
2325 $upperbound = intval($enddate['mday']);
2326 } else {
2327 $upperbound = calendar_days_in_month($month, $year);
2330 // Mark all days between $lowerbound and $upperbound (inclusive) as duration.
2331 for ($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
2332 $durationbyday[$i][] = $event->id;
2333 if ($event->courseid == SITEID && $event->groupid == 0) {
2334 $typesbyday[$i]['durationglobal'] = true;
2335 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
2336 $typesbyday[$i]['durationcourse'] = true;
2337 } else if ($event->groupid) {
2338 $typesbyday[$i]['durationgroup'] = true;
2339 } else if ($event->userid) {
2340 $typesbyday[$i]['durationuser'] = true;
2345 return;
2349 * Returns the courses to load events for.
2351 * @param array $courseeventsfrom An array of courses to load calendar events for
2352 * @param bool $ignorefilters specify the use of filters, false is set as default
2353 * @return array An array of courses, groups, and user to load calendar events for based upon filters
2355 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
2356 global $USER, $CFG;
2358 // For backwards compatability we have to check whether the courses array contains
2359 // just id's in which case we need to load course objects.
2360 $coursestoload = array();
2361 foreach ($courseeventsfrom as $id => $something) {
2362 if (!is_object($something)) {
2363 $coursestoload[] = $id;
2364 unset($courseeventsfrom[$id]);
2368 $courses = array();
2369 $user = false;
2370 $group = false;
2372 // Get the capabilities that allow seeing group events from all groups.
2373 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
2375 $isloggedin = isloggedin();
2377 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
2378 $courses = array_keys($courseeventsfrom);
2380 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
2381 $courses[] = SITEID;
2383 $courses = array_unique($courses);
2384 sort($courses);
2386 if (!empty($courses) && in_array(SITEID, $courses)) {
2387 // Sort courses for consistent colour highlighting.
2388 // Effectively ignoring SITEID as setting as last course id.
2389 $key = array_search(SITEID, $courses);
2390 unset($courses[$key]);
2391 $courses[] = SITEID;
2394 if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
2395 $user = $USER->id;
2398 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
2400 if (count($courseeventsfrom) == 1) {
2401 $course = reset($courseeventsfrom);
2402 if (has_any_capability($allgroupscaps, \context_course::instance($course->id))) {
2403 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
2404 $group = array_keys($coursegroups);
2407 if ($group === false) {
2408 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, \context_system::instance())) {
2409 $group = true;
2410 } else if ($isloggedin) {
2411 $groupids = array();
2412 foreach ($courseeventsfrom as $courseid => $course) {
2413 // If the user is an editing teacher in there.
2414 if (!empty($USER->groupmember[$course->id])) {
2415 // We've already cached the users groups for this course so we can just use that.
2416 $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
2417 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2418 // If this course has groups, show events from all of those related to the current user.
2419 $coursegroups = groups_get_user_groups($course->id, $USER->id);
2420 $groupids = array_merge($groupids, $coursegroups['0']);
2423 if (!empty($groupids)) {
2424 $group = $groupids;
2429 if (empty($courses)) {
2430 $courses = false;
2433 return array($courses, $group, $user);
2437 * Return the capability for editing calendar event.
2439 * @param calendar_event $event event object
2440 * @param bool $manualedit is the event being edited manually by the user
2441 * @return bool capability to edit event
2443 function calendar_edit_event_allowed($event, $manualedit = false) {
2444 global $USER, $DB;
2446 // Must be logged in.
2447 if (!isloggedin()) {
2448 return false;
2451 // Can not be using guest account.
2452 if (isguestuser()) {
2453 return false;
2456 if ($manualedit && !empty($event->modulename)) {
2457 // A user isn't allowed to directly edit an event generated
2458 // by a module.
2459 return false;
2462 // You cannot edit URL based calendar subscription events presently.
2463 if (!empty($event->subscriptionid)) {
2464 if (!empty($event->subscription->url)) {
2465 // This event can be updated externally, so it cannot be edited.
2466 return false;
2470 $sitecontext = \context_system::instance();
2472 // If user has manageentries at site level, return true.
2473 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2474 return true;
2477 // If groupid is set, it's definitely a group event.
2478 if (!empty($event->groupid)) {
2479 // Allow users to add/edit group events if -
2480 // 1) They have manageentries for the course OR
2481 // 2) They have managegroupentries AND are in the group.
2482 $group = $DB->get_record('groups', array('id' => $event->groupid));
2483 return $group && (
2484 has_capability('moodle/calendar:manageentries', $event->context) ||
2485 (has_capability('moodle/calendar:managegroupentries', $event->context)
2486 && groups_is_member($event->groupid)));
2487 } else if (!empty($event->courseid)) {
2488 // If groupid is not set, but course is set, it's definiely a course event.
2489 return has_capability('moodle/calendar:manageentries', $event->context);
2490 } else if (!empty($event->userid) && $event->userid == $USER->id) {
2491 // If course is not set, but userid id set, it's a user event.
2492 return (has_capability('moodle/calendar:manageownentries', $event->context));
2493 } else if (!empty($event->userid)) {
2494 return (has_capability('moodle/calendar:manageentries', $event->context));
2497 return false;
2501 * Return the capability for deleting a calendar event.
2503 * @param calendar_event $event The event object
2504 * @return bool Whether the user has permission to delete the event or not.
2506 function calendar_delete_event_allowed($event) {
2507 // Only allow delete if you have capabilities and it is not an module event.
2508 return (calendar_edit_event_allowed($event) && empty($event->modulename));
2512 * Returns the default courses to display on the calendar when there isn't a specific
2513 * course to display.
2515 * @return array $courses Array of courses to display
2517 function calendar_get_default_courses() {
2518 global $CFG, $DB;
2520 if (!isloggedin()) {
2521 return array();
2524 if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', \context_system::instance())) {
2525 $select = ', ' . \context_helper::get_preload_record_columns_sql('ctx');
2526 $join = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
2527 $sql = "SELECT c.* $select
2528 FROM {course} c
2529 $join
2530 WHERE EXISTS (SELECT 1 FROM {event} e WHERE e.courseid = c.id)
2532 $courses = $DB->get_records_sql($sql, array('contextlevel' => CONTEXT_COURSE), 0, 20);
2533 foreach ($courses as $course) {
2534 \context_helper::preload_from_record($course);
2536 return $courses;
2539 $courses = enrol_get_my_courses();
2541 return $courses;
2545 * Get event format time.
2547 * @param calendar_event $event event object
2548 * @param int $now current time in gmt
2549 * @param array $linkparams list of params for event link
2550 * @param bool $usecommonwords the words as formatted date/time.
2551 * @param int $showtime determine the show time GMT timestamp
2552 * @return string $eventtime link/string for event time
2554 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
2555 $starttime = $event->timestart;
2556 $endtime = $event->timestart + $event->timeduration;
2558 if (empty($linkparams) || !is_array($linkparams)) {
2559 $linkparams = array();
2562 $linkparams['view'] = 'day';
2564 // OK, now to get a meaningful display.
2565 // Check if there is a duration for this event.
2566 if ($event->timeduration) {
2567 // Get the midnight of the day the event will start.
2568 $usermidnightstart = usergetmidnight($starttime);
2569 // Get the midnight of the day the event will end.
2570 $usermidnightend = usergetmidnight($endtime);
2571 // Check if we will still be on the same day.
2572 if ($usermidnightstart == $usermidnightend) {
2573 // Check if we are running all day.
2574 if ($event->timeduration == DAYSECS) {
2575 $time = get_string('allday', 'calendar');
2576 } else { // Specify the time we will be running this from.
2577 $datestart = calendar_time_representation($starttime);
2578 $dateend = calendar_time_representation($endtime);
2579 $time = $datestart . ' <strong>&raquo;</strong> ' . $dateend;
2582 // Set printable representation.
2583 if (!$showtime) {
2584 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2585 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2586 $eventtime = \html_writer::link($url, $day) . ', ' . $time;
2587 } else {
2588 $eventtime = $time;
2590 } else { // It must spans two or more days.
2591 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
2592 if ($showtime == $usermidnightstart) {
2593 $daystart = '';
2595 $timestart = calendar_time_representation($event->timestart);
2596 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
2597 if ($showtime == $usermidnightend) {
2598 $dayend = '';
2600 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
2602 // Set printable representation.
2603 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2604 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2605 $eventtime = $timestart . ' <strong>&raquo;</strong> ' . \html_writer::link($url, $dayend) . $timeend;
2606 } else {
2607 // The event is in the future, print start and end links.
2608 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2609 $eventtime = \html_writer::link($url, $daystart) . $timestart . ' <strong>&raquo;</strong> ';
2611 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2612 $eventtime .= \html_writer::link($url, $dayend) . $timeend;
2615 } else { // There is no time duration.
2616 $time = calendar_time_representation($event->timestart);
2617 // Set printable representation.
2618 if (!$showtime) {
2619 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2620 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2621 $eventtime = \html_writer::link($url, $day) . ', ' . trim($time);
2622 } else {
2623 $eventtime = $time;
2627 // Check if It has expired.
2628 if ($event->timestart + $event->timeduration < $now) {
2629 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2632 return $eventtime;
2636 * Checks to see if the requested type of event should be shown for the given user.
2638 * @param int $type The type to check the display for (default is to display all)
2639 * @param stdClass|int|null $user The user to check for - by default the current user
2640 * @return bool True if the tyep should be displayed false otherwise
2642 function calendar_show_event_type($type, $user = null) {
2643 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
2645 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2646 global $SESSION;
2647 if (!isset($SESSION->calendarshoweventtype)) {
2648 $SESSION->calendarshoweventtype = $default;
2650 return $SESSION->calendarshoweventtype & $type;
2651 } else {
2652 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2657 * Sets the display of the event type given $display.
2659 * If $display = true the event type will be shown.
2660 * If $display = false the event type will NOT be shown.
2661 * If $display = null the current value will be toggled and saved.
2663 * @param int $type object of CALENDAR_EVENT_XXX
2664 * @param bool $display option to display event type
2665 * @param stdClass|int $user moodle user object or id, null means current user
2667 function calendar_set_event_type_display($type, $display = null, $user = null) {
2668 $persist = get_user_preferences('calendar_persistflt', 0, $user);
2669 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
2670 if ($persist === 0) {
2671 global $SESSION;
2672 if (!isset($SESSION->calendarshoweventtype)) {
2673 $SESSION->calendarshoweventtype = $default;
2675 $preference = $SESSION->calendarshoweventtype;
2676 } else {
2677 $preference = get_user_preferences('calendar_savedflt', $default, $user);
2679 $current = $preference & $type;
2680 if ($display === null) {
2681 $display = !$current;
2683 if ($display && !$current) {
2684 $preference += $type;
2685 } else if (!$display && $current) {
2686 $preference -= $type;
2688 if ($persist === 0) {
2689 $SESSION->calendarshoweventtype = $preference;
2690 } else {
2691 if ($preference == $default) {
2692 unset_user_preference('calendar_savedflt', $user);
2693 } else {
2694 set_user_preference('calendar_savedflt', $preference, $user);
2700 * Get calendar's allowed types.
2702 * @param stdClass $allowed list of allowed edit for event type
2703 * @param stdClass|int $course object of a course or course id
2704 * @param array $groups array of groups for the given course
2706 function calendar_get_allowed_types(&$allowed, $course = null, $groups = null) {
2707 global $USER, $DB;
2709 $allowed = new \stdClass();
2710 $allowed->user = has_capability('moodle/calendar:manageownentries', \context_system::instance());
2711 $allowed->groups = false;
2712 $allowed->courses = false;
2713 $allowed->site = has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID));
2714 $getgroupsfunc = function($course, $context, $user) use ($groups) {
2715 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2716 if (has_capability('moodle/site:accessallgroups', $context)) {
2717 return is_null($groups) ? groups_get_all_groups($course->id) : $groups;
2718 } else {
2719 if (is_null($groups)) {
2720 return groups_get_all_groups($course->id, $user->id);
2721 } else {
2722 return array_filter($groups, function($group) use ($user) {
2723 return isset($group->members[$user->id]);
2729 return false;
2732 if (!empty($course)) {
2733 if (!is_object($course)) {
2734 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST);
2736 if ($course->id != SITEID) {
2737 $coursecontext = \context_course::instance($course->id);
2738 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
2740 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2741 $allowed->courses = array($course->id => 1);
2742 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2743 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
2744 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2751 * Get all of the allowed types for all of the courses and groups
2752 * the logged in user belongs to.
2754 * The returned array will optionally have 5 keys:
2755 * 'user' : true if the logged in user can create user events
2756 * 'site' : true if the logged in user can create site events
2757 * 'course' : array of courses that the user can create events for
2758 * 'group': array of groups that the user can create events for
2759 * 'groupcourses' : array of courses that the groups belong to (can
2760 * be different from the list in 'course'.
2762 * @return array The array of allowed types.
2764 function calendar_get_all_allowed_types() {
2765 global $CFG, $USER;
2767 require_once($CFG->libdir . '/enrollib.php');
2769 $types = [];
2771 calendar_get_allowed_types($allowed);
2773 if ($allowed->user) {
2774 $types['user'] = true;
2777 if ($allowed->site) {
2778 $types['site'] = true;
2781 // This function warms the context cache for the course so the calls
2782 // to load the course context in calendar_get_allowed_types don't result
2783 // in additional DB queries.
2784 $courses = enrol_get_users_courses($USER->id, true);
2785 // We want to pre-fetch all of the groups for each course in a single
2786 // query to avoid calendar_get_allowed_types from hitting the DB for
2787 // each separate course.
2788 $groups = groups_get_all_groups_for_courses($courses);
2790 foreach ($courses as $course) {
2791 $coursegroups = isset($groups[$course->id]) ? $groups[$course->id] : null;
2792 calendar_get_allowed_types($allowed, $course, $coursegroups);
2794 if (!empty($allowed->courses)) {
2795 if (!isset($types['course'])) {
2796 $types['course'] = [$course];
2797 } else {
2798 $types['course'][] = $course;
2802 if (!empty($allowed->groups)) {
2803 if (!isset($types['groupcourses'])) {
2804 $types['groupcourses'] = [$course];
2805 } else {
2806 $types['groupcourses'][] = $course;
2809 if (!isset($types['group'])) {
2810 $types['group'] = array_values($allowed->groups);
2811 } else {
2812 $types['group'] = array_merge($types['group'], array_values($allowed->groups));
2817 return $types;
2821 * See if user can add calendar entries at all used to print the "New Event" button.
2823 * @param stdClass $course object of a course or course id
2824 * @return bool has the capability to add at least one event type
2826 function calendar_user_can_add_event($course) {
2827 if (!isloggedin() || isguestuser()) {
2828 return false;
2831 calendar_get_allowed_types($allowed, $course);
2833 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);
2837 * Check wether the current user is permitted to add events.
2839 * @param stdClass $event object of event
2840 * @return bool has the capability to add event
2842 function calendar_add_event_allowed($event) {
2843 global $USER, $DB;
2845 // Can not be using guest account.
2846 if (!isloggedin() or isguestuser()) {
2847 return false;
2850 $sitecontext = \context_system::instance();
2852 // If user has manageentries at site level, always return true.
2853 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2854 return true;
2857 switch ($event->eventtype) {
2858 case 'course':
2859 return has_capability('moodle/calendar:manageentries', $event->context);
2860 case 'group':
2861 // Allow users to add/edit group events if -
2862 // 1) They have manageentries (= entries for whole course).
2863 // 2) They have managegroupentries AND are in the group.
2864 $group = $DB->get_record('groups', array('id' => $event->groupid));
2865 return $group && (
2866 has_capability('moodle/calendar:manageentries', $event->context) ||
2867 (has_capability('moodle/calendar:managegroupentries', $event->context)
2868 && groups_is_member($event->groupid)));
2869 case 'user':
2870 if ($event->userid == $USER->id) {
2871 return (has_capability('moodle/calendar:manageownentries', $event->context));
2873 // There is intentionally no 'break'.
2874 case 'site':
2875 return has_capability('moodle/calendar:manageentries', $event->context);
2876 default:
2877 return has_capability('moodle/calendar:manageentries', $event->context);
2882 * Returns option list for the poll interval setting.
2884 * @return array An array of poll interval options. Interval => description.
2886 function calendar_get_pollinterval_choices() {
2887 return array(
2888 '0' => new \lang_string('never', 'calendar'),
2889 HOURSECS => new \lang_string('hourly', 'calendar'),
2890 DAYSECS => new \lang_string('daily', 'calendar'),
2891 WEEKSECS => new \lang_string('weekly', 'calendar'),
2892 '2628000' => new \lang_string('monthly', 'calendar'),
2893 YEARSECS => new \lang_string('annually', 'calendar')
2898 * Returns option list of available options for the calendar event type, given the current user and course.
2900 * @param int $courseid The id of the course
2901 * @return array An array containing the event types the user can create.
2903 function calendar_get_eventtype_choices($courseid) {
2904 $choices = array();
2905 $allowed = new \stdClass;
2906 calendar_get_allowed_types($allowed, $courseid);
2908 if ($allowed->user) {
2909 $choices['user'] = get_string('userevents', 'calendar');
2911 if ($allowed->site) {
2912 $choices['site'] = get_string('siteevents', 'calendar');
2914 if (!empty($allowed->courses)) {
2915 $choices['course'] = get_string('courseevents', 'calendar');
2917 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2918 $choices['group'] = get_string('group');
2921 return array($choices, $allowed->groups);
2925 * Add an iCalendar subscription to the database.
2927 * @param stdClass $sub The subscription object (e.g. from the form)
2928 * @return int The insert ID, if any.
2930 function calendar_add_subscription($sub) {
2931 global $DB, $USER, $SITE;
2933 if ($sub->eventtype === 'site') {
2934 $sub->courseid = $SITE->id;
2935 } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
2936 $sub->courseid = $sub->course;
2937 } else {
2938 // User events.
2939 $sub->courseid = 0;
2941 $sub->userid = $USER->id;
2943 // File subscriptions never update.
2944 if (empty($sub->url)) {
2945 $sub->pollinterval = 0;
2948 if (!empty($sub->name)) {
2949 if (empty($sub->id)) {
2950 $id = $DB->insert_record('event_subscriptions', $sub);
2951 // We cannot cache the data here because $sub is not complete.
2952 $sub->id = $id;
2953 // Trigger event, calendar subscription added.
2954 $eventparams = array('objectid' => $sub->id,
2955 'context' => calendar_get_calendar_context($sub),
2956 'other' => array('eventtype' => $sub->eventtype, 'courseid' => $sub->courseid)
2958 $event = \core\event\calendar_subscription_created::create($eventparams);
2959 $event->trigger();
2960 return $id;
2961 } else {
2962 // Why are we doing an update here?
2963 calendar_update_subscription($sub);
2964 return $sub->id;
2966 } else {
2967 print_error('errorbadsubscription', 'importcalendar');
2972 * Add an iCalendar event to the Moodle calendar.
2974 * @param stdClass $event The RFC-2445 iCalendar event
2975 * @param int $courseid The course ID
2976 * @param int $subscriptionid The iCalendar subscription ID
2977 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2978 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2979 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2981 function calendar_add_icalendar_event($event, $courseid, $subscriptionid, $timezone='UTC') {
2982 global $DB;
2984 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2985 if (empty($event->properties['SUMMARY'])) {
2986 return 0;
2989 $name = $event->properties['SUMMARY'][0]->value;
2990 $name = str_replace('\n', '<br />', $name);
2991 $name = str_replace('\\', '', $name);
2992 $name = preg_replace('/\s+/u', ' ', $name);
2994 $eventrecord = new \stdClass;
2995 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
2997 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2998 $description = '';
2999 } else {
3000 $description = $event->properties['DESCRIPTION'][0]->value;
3001 $description = clean_param($description, PARAM_NOTAGS);
3002 $description = str_replace('\n', '<br />', $description);
3003 $description = str_replace('\\', '', $description);
3004 $description = preg_replace('/\s+/u', ' ', $description);
3006 $eventrecord->description = $description;
3008 // Probably a repeating event with RRULE etc. TODO: skip for now.
3009 if (empty($event->properties['DTSTART'][0]->value)) {
3010 return 0;
3013 if (isset($event->properties['DTSTART'][0]->parameters['TZID'])) {
3014 $tz = $event->properties['DTSTART'][0]->parameters['TZID'];
3015 } else {
3016 $tz = $timezone;
3018 $tz = \core_date::normalise_timezone($tz);
3019 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value . ' ' . $tz);
3020 if (empty($event->properties['DTEND'])) {
3021 $eventrecord->timeduration = 0; // No duration if no end time specified.
3022 } else {
3023 if (isset($event->properties['DTEND'][0]->parameters['TZID'])) {
3024 $endtz = $event->properties['DTEND'][0]->parameters['TZID'];
3025 } else {
3026 $endtz = $timezone;
3028 $endtz = \core_date::normalise_timezone($endtz);
3029 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value . ' ' . $endtz) - $eventrecord->timestart;
3032 // Check to see if it should be treated as an all day event.
3033 if ($eventrecord->timeduration == DAYSECS) {
3034 // Check to see if the event started at Midnight on the imported calendar.
3035 date_default_timezone_set($timezone);
3036 if (date('H:i:s', $eventrecord->timestart) === "00:00:00") {
3037 // This event should be an all day event. This is not correct, we don't do anything differently for all day events.
3038 // See MDL-56227.
3039 $eventrecord->timeduration = 0;
3041 \core_date::set_default_server_timezone();
3044 $eventrecord->uuid = $event->properties['UID'][0]->value;
3045 $eventrecord->timemodified = time();
3047 // Add the iCal subscription details if required.
3048 // We should never do anything with an event without a subscription reference.
3049 $sub = calendar_get_subscription($subscriptionid);
3050 $eventrecord->subscriptionid = $subscriptionid;
3051 $eventrecord->userid = $sub->userid;
3052 $eventrecord->groupid = $sub->groupid;
3053 $eventrecord->courseid = $sub->courseid;
3054 $eventrecord->eventtype = $sub->eventtype;
3056 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid,
3057 'subscriptionid' => $eventrecord->subscriptionid))) {
3058 $eventrecord->id = $updaterecord->id;
3059 $return = CALENDAR_IMPORT_EVENT_UPDATED; // Update.
3060 } else {
3061 $return = CALENDAR_IMPORT_EVENT_INSERTED; // Insert.
3063 if ($createdevent = \calendar_event::create($eventrecord, false)) {
3064 if (!empty($event->properties['RRULE'])) {
3065 // Repeating events.
3066 date_default_timezone_set($tz); // Change time zone to parse all events.
3067 $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
3068 $rrule->parse_rrule();
3069 $rrule->create_events($createdevent);
3070 \core_date::set_default_server_timezone(); // Change time zone back to what it was.
3072 return $return;
3073 } else {
3074 return 0;
3079 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
3081 * @param int $subscriptionid The ID of the subscription we are acting upon.
3082 * @param int $pollinterval The poll interval to use.
3083 * @param int $action The action to be performed. One of update or remove.
3084 * @throws dml_exception if invalid subscriptionid is provided
3085 * @return string A log of the import progress, including errors
3087 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
3088 // Fetch the subscription from the database making sure it exists.
3089 $sub = calendar_get_subscription($subscriptionid);
3091 // Update or remove the subscription, based on action.
3092 switch ($action) {
3093 case CALENDAR_SUBSCRIPTION_UPDATE:
3094 // Skip updating file subscriptions.
3095 if (empty($sub->url)) {
3096 break;
3098 $sub->pollinterval = $pollinterval;
3099 calendar_update_subscription($sub);
3101 // Update the events.
3102 return "<p>" . get_string('subscriptionupdated', 'calendar', $sub->name) . "</p>" .
3103 calendar_update_subscription_events($subscriptionid);
3104 case CALENDAR_SUBSCRIPTION_REMOVE:
3105 calendar_delete_subscription($subscriptionid);
3106 return get_string('subscriptionremoved', 'calendar', $sub->name);
3107 break;
3108 default:
3109 break;
3111 return '';
3115 * Delete subscription and all related events.
3117 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
3119 function calendar_delete_subscription($subscription) {
3120 global $DB;
3122 if (!is_object($subscription)) {
3123 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST);
3126 // Delete subscription and related events.
3127 $DB->delete_records('event', array('subscriptionid' => $subscription->id));
3128 $DB->delete_records('event_subscriptions', array('id' => $subscription->id));
3129 \cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id));
3131 // Trigger event, calendar subscription deleted.
3132 $eventparams = array('objectid' => $subscription->id,
3133 'context' => calendar_get_calendar_context($subscription),
3134 'other' => array('courseid' => $subscription->courseid)
3136 $event = \core\event\calendar_subscription_deleted::create($eventparams);
3137 $event->trigger();
3141 * From a URL, fetch the calendar and return an iCalendar object.
3143 * @param string $url The iCalendar URL
3144 * @return iCalendar The iCalendar object
3146 function calendar_get_icalendar($url) {
3147 global $CFG;
3149 require_once($CFG->libdir . '/filelib.php');
3151 $curl = new \curl();
3152 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
3153 $calendar = $curl->get($url);
3155 // Http code validation should actually be the job of curl class.
3156 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
3157 throw new \moodle_exception('errorinvalidicalurl', 'calendar');
3160 $ical = new \iCalendar();
3161 $ical->unserialize($calendar);
3163 return $ical;
3167 * Import events from an iCalendar object into a course calendar.
3169 * @param iCalendar $ical The iCalendar object.
3170 * @param int $courseid The course ID for the calendar.
3171 * @param int $subscriptionid The subscription ID.
3172 * @return string A log of the import progress, including errors.
3174 function calendar_import_icalendar_events($ical, $courseid, $subscriptionid = null) {
3175 global $DB;
3177 $return = '';
3178 $eventcount = 0;
3179 $updatecount = 0;
3181 // Large calendars take a while...
3182 if (!CLI_SCRIPT) {
3183 \core_php_time_limit::raise(300);
3186 // Mark all events in a subscription with a zero timestamp.
3187 if (!empty($subscriptionid)) {
3188 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
3189 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3192 // Grab the timezone from the iCalendar file to be used later.
3193 if (isset($ical->properties['X-WR-TIMEZONE'][0]->value)) {
3194 $timezone = $ical->properties['X-WR-TIMEZONE'][0]->value;
3195 } else {
3196 $timezone = 'UTC';
3199 $return = '';
3200 foreach ($ical->components['VEVENT'] as $event) {
3201 $res = calendar_add_icalendar_event($event, $courseid, $subscriptionid, $timezone);
3202 switch ($res) {
3203 case CALENDAR_IMPORT_EVENT_UPDATED:
3204 $updatecount++;
3205 break;
3206 case CALENDAR_IMPORT_EVENT_INSERTED:
3207 $eventcount++;
3208 break;
3209 case 0:
3210 $return .= '<p>' . get_string('erroraddingevent', 'calendar') . ': ';
3211 if (empty($event->properties['SUMMARY'])) {
3212 $return .= '(' . get_string('notitle', 'calendar') . ')';
3213 } else {
3214 $return .= $event->properties['SUMMARY'][0]->value;
3216 $return .= "</p>\n";
3217 break;
3221 $return .= "<p>" . get_string('eventsimported', 'calendar', $eventcount) . "</p> ";
3222 $return .= "<p>" . get_string('eventsupdated', 'calendar', $updatecount) . "</p>";
3224 // Delete remaining zero-marked events since they're not in remote calendar.
3225 if (!empty($subscriptionid)) {
3226 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3227 if (!empty($deletecount)) {
3228 $DB->delete_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3229 $return .= "<p> " . get_string('eventsdeleted', 'calendar') . ": {$deletecount} </p>\n";
3233 return $return;
3237 * Fetch a calendar subscription and update the events in the calendar.
3239 * @param int $subscriptionid The course ID for the calendar.
3240 * @return string A log of the import progress, including errors.
3242 function calendar_update_subscription_events($subscriptionid) {
3243 $sub = calendar_get_subscription($subscriptionid);
3245 // Don't update a file subscription.
3246 if (empty($sub->url)) {
3247 return 'File subscription not updated.';
3250 $ical = calendar_get_icalendar($sub->url);
3251 $return = calendar_import_icalendar_events($ical, $sub->courseid, $subscriptionid);
3252 $sub->lastupdated = time();
3254 calendar_update_subscription($sub);
3256 return $return;
3260 * Update a calendar subscription. Also updates the associated cache.
3262 * @param stdClass|array $subscription Subscription record.
3263 * @throws coding_exception If something goes wrong
3264 * @since Moodle 2.5
3266 function calendar_update_subscription($subscription) {
3267 global $DB;
3269 if (is_array($subscription)) {
3270 $subscription = (object)$subscription;
3272 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
3273 throw new \coding_exception('Cannot update a subscription without a valid id');
3276 $DB->update_record('event_subscriptions', $subscription);
3278 // Update cache.
3279 $cache = \cache::make('core', 'calendar_subscriptions');
3280 $cache->set($subscription->id, $subscription);
3282 // Trigger event, calendar subscription updated.
3283 $eventparams = array('userid' => $subscription->userid,
3284 'objectid' => $subscription->id,
3285 'context' => calendar_get_calendar_context($subscription),
3286 'other' => array('eventtype' => $subscription->eventtype, 'courseid' => $subscription->courseid)
3288 $event = \core\event\calendar_subscription_updated::create($eventparams);
3289 $event->trigger();
3293 * Checks to see if the user can edit a given subscription feed.
3295 * @param mixed $subscriptionorid Subscription object or id
3296 * @return bool true if current user can edit the subscription else false
3298 function calendar_can_edit_subscription($subscriptionorid) {
3299 if (is_array($subscriptionorid)) {
3300 $subscription = (object)$subscriptionorid;
3301 } else if (is_object($subscriptionorid)) {
3302 $subscription = $subscriptionorid;
3303 } else {
3304 $subscription = calendar_get_subscription($subscriptionorid);
3307 $allowed = new \stdClass;
3308 $courseid = $subscription->courseid;
3309 $groupid = $subscription->groupid;
3311 calendar_get_allowed_types($allowed, $courseid);
3312 switch ($subscription->eventtype) {
3313 case 'user':
3314 return $allowed->user;
3315 case 'course':
3316 if (isset($allowed->courses[$courseid])) {
3317 return $allowed->courses[$courseid];
3318 } else {
3319 return false;
3321 case 'site':
3322 return $allowed->site;
3323 case 'group':
3324 if (isset($allowed->groups[$groupid])) {
3325 return $allowed->groups[$groupid];
3326 } else {
3327 return false;
3329 default:
3330 return false;
3335 * Helper function to determine the context of a calendar subscription.
3336 * Subscriptions can be created in two contexts COURSE, or USER.
3338 * @param stdClass $subscription
3339 * @return context instance
3341 function calendar_get_calendar_context($subscription) {
3342 // Determine context based on calendar type.
3343 if ($subscription->eventtype === 'site') {
3344 $context = \context_course::instance(SITEID);
3345 } else if ($subscription->eventtype === 'group' || $subscription->eventtype === 'course') {
3346 $context = \context_course::instance($subscription->courseid);
3347 } else {
3348 $context = \context_user::instance($subscription->userid);
3350 return $context;
3354 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
3356 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3358 * @return array
3360 function core_calendar_user_preferences() {
3361 $preferences = [];
3362 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED, 'default' => '0',
3363 'choices' => array('0', CALENDAR_TF_12, CALENDAR_TF_24)
3365 $preferences['calendar_startwday'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3366 'choices' => array(0, 1, 2, 3, 4, 5, 6));
3367 $preferences['calendar_maxevents'] = array('type' => PARAM_INT, 'choices' => range(1, 20));
3368 $preferences['calendar_lookahead'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 365,
3369 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3370 $preferences['calendar_persistflt'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3371 'choices' => array(0, 1));
3372 return $preferences;
3376 * Get legacy calendar events
3378 * @param int $tstart Start time of time range for events
3379 * @param int $tend End time of time range for events
3380 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3381 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3382 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3383 * @param boolean $withduration whether only events starting within time range selected
3384 * or events in progress/already started selected as well
3385 * @param boolean $ignorehidden whether to select only visible events or all events
3386 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3388 function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses, $withduration = true, $ignorehidden = true) {
3389 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3390 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3391 // parameters, but with the new API method, only null and arrays are accepted.
3392 list($userparam, $groupparam, $courseparam) = array_map(function($param) {
3393 // If parameter is true, return null.
3394 if ($param === true) {
3395 return null;
3398 // If parameter is false, return an empty array.
3399 if ($param === false) {
3400 return [];
3403 // If the parameter is a scalar value, enclose it in an array.
3404 if (!is_array($param)) {
3405 return [$param];
3408 // No normalisation required.
3409 return $param;
3410 }, [$users, $groups, $courses]);
3412 $mapper = \core_calendar\local\event\container::get_event_mapper();
3413 $events = \core_calendar\local\api::get_events(
3414 $tstart,
3415 $tend,
3416 null,
3417 null,
3418 null,
3419 null,
3421 null,
3422 $userparam,
3423 $groupparam,
3424 $courseparam,
3425 $withduration,
3426 $ignorehidden
3429 return array_reduce($events, function($carry, $event) use ($mapper) {
3430 return $carry + [$event->get_id() => $mapper->from_event_to_stdclass($event)];
3431 }, []);
3436 * Get the calendar view output.
3438 * @param \calendar_information $calendar The calendar being represented
3439 * @param string $view The type of calendar to have displayed
3440 * @return array[array, string]
3442 function calendar_get_view(\calendar_information $calendar, $view) {
3443 global $PAGE, $CFG;
3445 $renderer = $PAGE->get_renderer('core_calendar');
3446 $type = \core_calendar\type_factory::get_calendar_instance();
3448 // Calculate the bounds of the month.
3449 $date = $type->timestamp_to_date_array($calendar->time);
3450 $tstart = $type->convert_to_timestamp($date['year'], $date['mon'], 1);
3452 if ($view === 'day') {
3453 $tend = $tstart + DAYSECS - 1;
3454 $selectortitle = get_string('dayviewfor', 'calendar');
3455 } else if ($view === 'upcoming') {
3456 if (isset($CFG->calendar_lookahead)) {
3457 $defaultlookahead = intval($CFG->calendar_lookahead);
3458 } else {
3459 $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD;
3461 $tend = $tstart + get_user_preferences('calendar_lookahead', $defaultlookahead);
3462 $selectortitle = get_string('upcomingeventsfor', 'calendar');
3463 } else {
3464 $monthdays = $type->get_num_days_in_month($date['year'], $date['mon']);
3465 $tend = $tstart + ($monthdays * DAYSECS) - 1;
3466 $selectortitle = get_string('detailedmonthviewfor', 'calendar');
3469 list($userparam, $groupparam, $courseparam) = array_map(function($param) {
3470 // If parameter is true, return null.
3471 if ($param === true) {
3472 return null;
3475 // If parameter is false, return an empty array.
3476 if ($param === false) {
3477 return [];
3480 // If the parameter is a scalar value, enclose it in an array.
3481 if (!is_array($param)) {
3482 return [$param];
3485 // No normalisation required.
3486 return $param;
3487 }, [$calendar->users, $calendar->groups, $calendar->courses]);
3489 $events = \core_calendar\local\api::get_events(
3490 $tstart,
3491 $tend,
3492 null,
3493 null,
3494 null,
3495 null,
3497 null,
3498 $userparam,
3499 $groupparam,
3500 $courseparam,
3501 true,
3502 true,
3503 function ($event) {
3504 if ($proxy = $event->get_course_module()) {
3505 $cminfo = $proxy->get_proxied_instance();
3506 return $cminfo->uservisible;
3510 return true;
3514 $related = [
3515 'events' => $events,
3516 'cache' => new \core_calendar\external\events_related_objects_cache($events),
3519 $month = new \core_calendar\external\month_exporter($calendar, $type, $related);
3520 $data = $month->export($renderer);
3521 $template = 'core_calendar/month_detailed';
3523 return [$data, $template];
3527 * Request and render event form fragment.
3529 * @param array $args The fragment arguments.
3530 * @return string The rendered mform fragment.
3532 function calendar_output_fragment_event_form($args) {
3533 global $CFG, $OUTPUT;
3534 require_once($CFG->dirroot.'/calendar/event_form.php');
3536 $html = '';
3537 $data = null;
3538 $eventid = isset($args['eventid']) ? clean_param($args['eventid'], PARAM_INT) : null;
3539 $starttime = isset($args['starttime']) ? clean_param($args['starttime'], PARAM_INT) : null;
3540 $event = null;
3541 $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
3542 $formoptions = [];
3544 if ($hasformdata) {
3545 parse_str(clean_param($args['formdata'], PARAM_TEXT), $data);
3548 if (isset($args['haserror'])) {
3549 $formoptions['haserror'] = clean_param($args['haserror'], PARAM_BOOL);
3552 if ($starttime) {
3553 $formoptions['starttime'] = $starttime;
3556 if (is_null($eventid)) {
3557 $mform = new \core_calendar\local\event\forms\create(
3558 null,
3559 $formoptions,
3560 'post',
3562 null,
3563 true,
3564 $data
3566 } else {
3567 $event = calendar_event::load($eventid);
3568 $event->count_repeats();
3569 $formoptions['event'] = $event;
3570 $mform = new \core_calendar\local\event\forms\update(
3571 null,
3572 $formoptions,
3573 'post',
3575 null,
3576 true,
3577 $data
3581 if ($hasformdata) {
3582 $mform->is_validated();
3583 } else if (!is_null($event)) {
3584 $mapper = new \core_calendar\local\event\mappers\create_update_form_mapper();
3585 $data = $mapper->from_legacy_event_to_data($event);
3586 $mform->set_data($data);
3588 // Check to see if this event is part of a subscription or import.
3589 // If so display a warning on edit.
3590 if (isset($event->subscriptionid) && ($event->subscriptionid != null)) {
3591 $renderable = new \core\output\notification(
3592 get_string('eventsubscriptioneditwarning', 'calendar'),
3593 \core\output\notification::NOTIFY_INFO
3596 $html .= $OUTPUT->render($renderable);
3600 $html .= $mform->render();
3601 return $html;
3605 * Calculate the timestamp from the supplied Gregorian Year, Month, and Day.
3607 * @param int $d The day
3608 * @param int $m The month
3609 * @param int $y The year
3610 * @param int $time The timestamp to use instead of a separate y/m/d.
3611 * @return int The timestamp
3613 function calendar_get_timestamp($d, $m, $y, $time = 0) {
3614 // If a day, month and year were passed then convert it to a timestamp. If these were passed
3615 // then we can assume the day, month and year are passed as Gregorian, as no where in core
3616 // should we be passing these values rather than the time.
3617 if (!empty($d) && !empty($m) && !empty($y)) {
3618 if (checkdate($m, $d, $y)) {
3619 $time = make_timestamp($y, $m, $d);
3620 } else {
3621 $time = time();
3623 } else if (empty($time)) {
3624 $time = time();
3627 return $time;
3631 * Get the calendar footer options.
3633 * @param calendar_information $calendar The calendar information object.
3634 * @return array The data for template and template name.
3636 function calendar_get_footer_options($calendar) {
3637 global $CFG, $USER, $DB, $PAGE;
3639 // Generate hash for iCal link.
3640 $rawhash = $USER->id . $DB->get_field('user', 'password', ['id' => $USER->id]) . $CFG->calendar_exportsalt;
3641 $authtoken = sha1($rawhash);
3643 $renderer = $PAGE->get_renderer('core_calendar');
3644 $footer = new \core_calendar\external\footer_options_exporter($calendar, $USER->id, $authtoken);
3645 $data = $footer->export($renderer);
3646 $template = 'core_calendar/footer_options';
3648 return [$data, $template];