2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * External calendar API
21 * @package core_calendar
23 * @copyright 2012 Ankit Agarwal
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') ||
die;
30 require_once("$CFG->libdir/externallib.php");
31 require_once($CFG->dirroot
. '/calendar/lib.php');
33 use \core_calendar\local\api
as local_api
;
34 use \core_calendar\local\event\container
as event_container
;
35 use \core_calendar\local\event\forms\create
as create_event_form
;
36 use \core_calendar\local\event\forms\update
as update_event_form
;
37 use \core_calendar\local\event\mappers\create_update_form_mapper
;
38 use \core_calendar\external\event_exporter
;
39 use \core_calendar\external\events_exporter
;
40 use \core_calendar\external\events_grouped_by_course_exporter
;
41 use \core_calendar\external\events_related_objects_cache
;
44 * Calendar external functions
46 * @package core_calendar
48 * @copyright 2012 Ankit Agarwal
49 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
52 class core_calendar_external
extends external_api
{
56 * Returns description of method parameters
58 * @return external_function_parameters
61 public static function delete_calendar_events_parameters() {
62 return new external_function_parameters(
63 array('events' => new external_multiple_structure(
64 new external_single_structure(
66 'eventid' => new external_value(PARAM_INT
, 'Event ID', VALUE_REQUIRED
, '', NULL_NOT_ALLOWED
),
67 'repeat' => new external_value(PARAM_BOOL
, 'Delete comeplete series if repeated event')
68 ), 'List of events to delete'
76 * Delete Calendar events
78 * @param array $eventids A list of event ids with repeat flag to delete
82 public static function delete_calendar_events($events) {
85 // Parameter validation.
86 $params = self
::validate_parameters(self
:: delete_calendar_events_parameters(), array('events' => $events));
88 $transaction = $DB->start_delegated_transaction();
90 foreach ($params['events'] as $event) {
91 $eventobj = calendar_event
::load($event['eventid']);
93 // Let's check if the user is allowed to delete an event.
94 if (!calendar_delete_event_allowed($eventobj)) {
95 throw new moodle_exception('nopermissions', 'error', '', get_string('deleteevent', 'calendar'));
97 // Time to do the magic.
98 $eventobj->delete($event['repeat']);
101 // Everything done smoothly, let's commit.
102 $transaction->allow_commit();
108 * Returns description of method result value
110 * @return external_description
113 public static function delete_calendar_events_returns() {
118 * Returns description of method parameters
120 * @return external_function_parameters
123 public static function get_calendar_events_parameters() {
124 return new external_function_parameters(
125 array('events' => new external_single_structure(
127 'eventids' => new external_multiple_structure(
128 new external_value(PARAM_INT
, 'event ids')
129 , 'List of event ids',
130 VALUE_DEFAULT
, array()),
131 'courseids' => new external_multiple_structure(
132 new external_value(PARAM_INT
, 'course ids')
133 , 'List of course ids for which events will be returned',
134 VALUE_DEFAULT
, array()),
135 'groupids' => new external_multiple_structure(
136 new external_value(PARAM_INT
, 'group ids')
137 , 'List of group ids for which events should be returned',
138 VALUE_DEFAULT
, array()),
139 'categoryids' => new external_multiple_structure(
140 new external_value(PARAM_INT
, 'Category ids'),
141 'List of category ids for which events will be returned',
142 VALUE_DEFAULT
, array()),
143 ), 'Event details', VALUE_DEFAULT
, array()),
144 'options' => new external_single_structure(
146 'userevents' => new external_value(PARAM_BOOL
,
147 "Set to true to return current user's user events",
148 VALUE_DEFAULT
, true, NULL_ALLOWED
),
149 'siteevents' => new external_value(PARAM_BOOL
,
150 "Set to true to return site events",
151 VALUE_DEFAULT
, true, NULL_ALLOWED
),
152 'timestart' => new external_value(PARAM_INT
,
153 "Time from which events should be returned",
154 VALUE_DEFAULT
, 0, NULL_ALLOWED
),
155 'timeend' => new external_value(PARAM_INT
,
156 "Time to which the events should be returned. We treat 0 and null as no end",
157 VALUE_DEFAULT
, 0, NULL_ALLOWED
),
158 'ignorehidden' => new external_value(PARAM_BOOL
,
159 "Ignore hidden events or not",
160 VALUE_DEFAULT
, true, NULL_ALLOWED
),
162 ), 'Options', VALUE_DEFAULT
, array())
168 * Get Calendar events
170 * @param array $events A list of events
171 * @param array $options various options
172 * @return array Array of event details
175 public static function get_calendar_events($events = array(), $options = array()) {
176 global $SITE, $DB, $USER;
178 // Parameter validation.
179 $params = self
::validate_parameters(self
::get_calendar_events_parameters(), array('events' => $events, 'options' => $options));
180 $funcparam = array('courses' => array(), 'groups' => array(), 'categories' => array());
181 $hassystemcap = has_capability('moodle/calendar:manageentries', context_system
::instance());
183 $coursecategories = array();
185 // Let us find out courses and their categories that we can return events from.
186 if (!$hassystemcap) {
187 $courseobjs = enrol_get_my_courses();
188 $courses = array_keys($courseobjs);
190 $coursecategories = array_flip(array_map(function($course) {
191 return $course->category
;
194 foreach ($params['events']['courseids'] as $id) {
196 $context = context_course
::instance($id);
197 self
::validate_context($context);
198 $funcparam['courses'][] = $id;
199 } catch (Exception
$e) {
203 'warningcode' => 'nopermissions',
204 'message' => 'No access rights in course context '.$e->getMessage().$e->getTraceAsString()
209 $courses = $params['events']['courseids'];
210 $funcparam['courses'] = $courses;
212 if (!empty($courses)) {
213 list($wheresql, $sqlparams) = $DB->get_in_or_equal($courses);
214 $wheresql = "id $wheresql";
215 $coursecategories = array_flip(array_map(function($course) {
216 return $course->category
;
217 }, $DB->get_records_select('course', $wheresql, $sqlparams, '', 'category')));
221 // Let us findout groups that we can return events from.
222 if (!$hassystemcap) {
223 $groups = groups_get_my_groups();
224 $groups = array_keys($groups);
225 foreach ($params['events']['groupids'] as $id) {
226 if (in_array($id, $groups)) {
227 $funcparam['groups'][] = $id;
229 $warnings[] = array('item' => $id, 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to access this group');
233 $groups = $params['events']['groupids'];
234 $funcparam['groups'] = $groups;
237 $categories = array();
238 if ($hassystemcap ||
!empty($courses)) {
239 // Use the category id as the key in the following array. That way we do not have to remove duplicates and
240 // have a faster lookup later.
243 if (!empty($params['events']['categoryids'])) {
244 $catobjs = \core_course_category
::get_many(
245 array_merge($params['events']['categoryids'], array_keys($coursecategories)));
246 foreach ($catobjs as $catobj) {
247 if (isset($coursecategories[$catobj->id
]) ||
248 has_capability('moodle/category:manage', $catobj->get_context())) {
249 // If the user has access to a course in this category or can manage the category,
250 // then they can see all parent categories too.
251 $categories[$catobj->id
] = true;
252 foreach ($catobj->get_parents() as $catid) {
253 $categories[$catid] = true;
257 $funcparam['categories'] = array_keys($categories);
259 // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
260 $calcatcache = cache
::make('core', 'calendar_categories');
261 // Do not use cache if the user has the system capability as $coursecategories might not represent the
262 // courses the user is enrolled in.
263 $categories = (!$hassystemcap) ?
$calcatcache->get('site') : false;
264 if ($categories !== false) {
265 // The ids are stored in a list in the cache.
266 $funcparam['categories'] = $categories;
267 $categories = array_flip($categories);
270 foreach (\core_course_category
::get_all() as $category) {
271 if (isset($coursecategories[$category->id
]) ||
272 has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
273 // If the user has access to a course in this category or can manage the category,
274 // then they can see all parent categories too.
275 $categories[$category->id
] = true;
276 foreach ($category->get_parents() as $catid) {
277 $categories[$catid] = true;
281 $funcparam['categories'] = array_keys($categories);
282 if (!$hassystemcap) {
283 $calcatcache->set('site', $funcparam['categories']);
289 // Do we need user events?
290 if (!empty($params['options']['userevents'])) {
291 $funcparam['users'] = array($USER->id
);
293 $funcparam['users'] = false;
296 // Do we need site events?
297 if (!empty($params['options']['siteevents'])) {
298 $funcparam['courses'][] = $SITE->id
;
301 // We treat 0 and null as no end.
302 if (empty($params['options']['timeend'])) {
303 $params['options']['timeend'] = PHP_INT_MAX
;
306 // Event list does not check visibility and permissions, we'll check that later.
307 $eventlist = calendar_get_legacy_events($params['options']['timestart'], $params['options']['timeend'],
308 $funcparam['users'], $funcparam['groups'], $funcparam['courses'], true,
309 $params['options']['ignorehidden'], $funcparam['categories']);
311 // WS expects arrays.
314 // We need to get events asked for eventids.
315 if ($eventsbyid = calendar_get_events_by_id($params['events']['eventids'])) {
316 $eventlist +
= $eventsbyid;
318 foreach ($eventlist as $eventid => $eventobj) {
319 $event = (array) $eventobj;
320 // Description formatting.
321 $calendareventobj = new calendar_event($event);
322 list($event['description'], $event['format']) = $calendareventobj->format_external_text();
325 // User can see everything, no further check is needed.
326 $events[$eventid] = $event;
327 } else if (!empty($eventobj->modulename
)) {
328 $courseid = $eventobj->courseid
;
330 if (!$calendareventobj->context ||
!($context = $calendareventobj->context
->get_course_context(false))) {
333 $courseid = $context->instanceid
;
335 $instances = get_fast_modinfo($courseid)->get_instances_of($eventobj->modulename
);
336 if (!empty($instances[$eventobj->instance
]->uservisible
)) {
337 $events[$eventid] = $event;
340 // Can the user actually see this event?
341 $eventobj = calendar_event
::load($eventobj);
342 if ((($eventobj->courseid
== $SITE->id
) && (empty($eventobj->categoryid
))) ||
343 (!empty($eventobj->categoryid
) && isset($categories[$eventobj->categoryid
])) ||
344 (!empty($eventobj->groupid
) && in_array($eventobj->groupid
, $groups)) ||
345 (!empty($eventobj->courseid
) && in_array($eventobj->courseid
, $courses)) ||
346 ($USER->id
== $eventobj->userid
) ||
347 (calendar_edit_event_allowed($eventobj))) {
348 $events[$eventid] = $event;
350 $warnings[] = array('item' => $eventid, 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to view this event');
354 return array('events' => $events, 'warnings' => $warnings);
358 * Returns description of method result value
360 * @return external_description
363 public static function get_calendar_events_returns() {
364 return new external_single_structure(array(
365 'events' => new external_multiple_structure( new external_single_structure(
367 'id' => new external_value(PARAM_INT
, 'event id'),
368 'name' => new external_value(PARAM_TEXT
, 'event name'),
369 'description' => new external_value(PARAM_RAW
, 'Description', VALUE_OPTIONAL
, null, NULL_ALLOWED
),
370 'format' => new external_format_value('description'),
371 'courseid' => new external_value(PARAM_INT
, 'course id'),
372 'categoryid' => new external_value(PARAM_INT
, 'Category id (only for category events).',
374 'groupid' => new external_value(PARAM_INT
, 'group id'),
375 'userid' => new external_value(PARAM_INT
, 'user id'),
376 'repeatid' => new external_value(PARAM_INT
, 'repeat id'),
377 'modulename' => new external_value(PARAM_TEXT
, 'module name', VALUE_OPTIONAL
, null, NULL_ALLOWED
),
378 'instance' => new external_value(PARAM_INT
, 'instance id'),
379 'eventtype' => new external_value(PARAM_TEXT
, 'Event type'),
380 'timestart' => new external_value(PARAM_INT
, 'timestart'),
381 'timeduration' => new external_value(PARAM_INT
, 'time duration'),
382 'visible' => new external_value(PARAM_INT
, 'visible'),
383 'uuid' => new external_value(PARAM_TEXT
, 'unique id of ical events', VALUE_OPTIONAL
, null, NULL_NOT_ALLOWED
),
384 'sequence' => new external_value(PARAM_INT
, 'sequence'),
385 'timemodified' => new external_value(PARAM_INT
, 'time modified'),
386 'subscriptionid' => new external_value(PARAM_INT
, 'Subscription id', VALUE_OPTIONAL
, null, NULL_ALLOWED
),
389 'warnings' => new external_warnings()
395 * Returns description of method parameters.
398 * @return external_function_parameters
400 public static function get_calendar_action_events_by_timesort_parameters() {
401 return new external_function_parameters(
403 'timesortfrom' => new external_value(PARAM_INT
, 'Time sort from', VALUE_DEFAULT
, 0),
404 'timesortto' => new external_value(PARAM_INT
, 'Time sort to', VALUE_DEFAULT
, null),
405 'aftereventid' => new external_value(PARAM_INT
, 'The last seen event id', VALUE_DEFAULT
, 0),
406 'limitnum' => new external_value(PARAM_INT
, 'Limit number', VALUE_DEFAULT
, 20),
407 'limittononsuspendedevents' => new external_value(PARAM_BOOL
,
408 'Limit the events to courses the user is not suspended in', VALUE_DEFAULT
, false),
409 'userid' => new external_value(PARAM_INT
, 'The user id', VALUE_DEFAULT
, null),
415 * Get calendar action events based on the timesort value.
418 * @param null|int $timesortfrom Events after this time (inclusive)
419 * @param null|int $timesortto Events before this time (inclusive)
420 * @param null|int $aftereventid Get events with ids greater than this one
421 * @param int $limitnum Limit the number of results to this value
422 * @param null|int $userid The user id
425 public static function get_calendar_action_events_by_timesort($timesortfrom = 0, $timesortto = null,
426 $aftereventid = 0, $limitnum = 20, $limittononsuspendedevents = false,
430 $params = self
::validate_parameters(
431 self
::get_calendar_action_events_by_timesort_parameters(),
433 'timesortfrom' => $timesortfrom,
434 'timesortto' => $timesortto,
435 'aftereventid' => $aftereventid,
436 'limitnum' => $limitnum,
437 'limittononsuspendedevents' => $limittononsuspendedevents,
441 if ($params['userid']) {
442 $user = \core_user
::get_user($params['userid']);
447 $context = \context_user
::instance($user->id
);
448 self
::validate_context($context);
450 if (empty($params['aftereventid'])) {
451 $params['aftereventid'] = null;
454 $renderer = $PAGE->get_renderer('core_calendar');
455 $events = local_api
::get_action_events_by_timesort(
456 $params['timesortfrom'],
457 $params['timesortto'],
458 $params['aftereventid'],
460 $params['limittononsuspendedevents'],
464 $exportercache = new events_related_objects_cache($events);
465 $exporter = new events_exporter($events, ['cache' => $exportercache]);
467 return $exporter->export($renderer);
471 * Returns description of method result value.
474 * @return external_description
476 public static function get_calendar_action_events_by_timesort_returns() {
477 return events_exporter
::get_read_structure();
481 * Returns description of method parameters.
483 * @return external_function_parameters
485 public static function get_calendar_action_events_by_course_parameters() {
486 return new external_function_parameters(
488 'courseid' => new external_value(PARAM_INT
, 'Course id'),
489 'timesortfrom' => new external_value(PARAM_INT
, 'Time sort from', VALUE_DEFAULT
, null),
490 'timesortto' => new external_value(PARAM_INT
, 'Time sort to', VALUE_DEFAULT
, null),
491 'aftereventid' => new external_value(PARAM_INT
, 'The last seen event id', VALUE_DEFAULT
, 0),
492 'limitnum' => new external_value(PARAM_INT
, 'Limit number', VALUE_DEFAULT
, 20)
498 * Get calendar action events for the given course.
501 * @param int $courseid Only events in this course
502 * @param null|int $timesortfrom Events after this time (inclusive)
503 * @param null|int $timesortto Events before this time (inclusive)
504 * @param null|int $aftereventid Get events with ids greater than this one
505 * @param int $limitnum Limit the number of results to this value
508 public static function get_calendar_action_events_by_course(
509 $courseid, $timesortfrom = null, $timesortto = null, $aftereventid = 0, $limitnum = 20) {
514 $params = self
::validate_parameters(
515 self
::get_calendar_action_events_by_course_parameters(),
517 'courseid' => $courseid,
518 'timesortfrom' => $timesortfrom,
519 'timesortto' => $timesortto,
520 'aftereventid' => $aftereventid,
521 'limitnum' => $limitnum,
524 $context = \context_user
::instance($USER->id
);
525 self
::validate_context($context);
527 if (empty($params['aftereventid'])) {
528 $params['aftereventid'] = null;
531 $courses = enrol_get_my_courses('*', null, 0, [$courseid]);
532 $courses = array_values($courses);
534 if (empty($courses)) {
538 $course = $courses[0];
539 $renderer = $PAGE->get_renderer('core_calendar');
540 $events = local_api
::get_action_events_by_course(
542 $params['timesortfrom'],
543 $params['timesortto'],
544 $params['aftereventid'],
548 $exportercache = new events_related_objects_cache($events, $courses);
549 $exporter = new events_exporter($events, ['cache' => $exportercache]);
551 return $exporter->export($renderer);
555 * Returns description of method result value.
557 * @return external_description
559 public static function get_calendar_action_events_by_course_returns() {
560 return events_exporter
::get_read_structure();
564 * Returns description of method parameters.
566 * @return external_function_parameters
568 public static function get_calendar_action_events_by_courses_parameters() {
569 return new external_function_parameters(
571 'courseids' => new external_multiple_structure(
572 new external_value(PARAM_INT
, 'Course id')
574 'timesortfrom' => new external_value(PARAM_INT
, 'Time sort from', VALUE_DEFAULT
, null),
575 'timesortto' => new external_value(PARAM_INT
, 'Time sort to', VALUE_DEFAULT
, null),
576 'limitnum' => new external_value(PARAM_INT
, 'Limit number', VALUE_DEFAULT
, 10)
582 * Get calendar action events for a given list of courses.
585 * @param array $courseids Only include events for these courses
586 * @param null|int $timesortfrom Events after this time (inclusive)
587 * @param null|int $timesortto Events before this time (inclusive)
588 * @param int $limitnum Limit the number of results per course to this value
591 public static function get_calendar_action_events_by_courses(
592 array $courseids, $timesortfrom = null, $timesortto = null, $limitnum = 10) {
597 $params = self
::validate_parameters(
598 self
::get_calendar_action_events_by_courses_parameters(),
600 'courseids' => $courseids,
601 'timesortfrom' => $timesortfrom,
602 'timesortto' => $timesortto,
603 'limitnum' => $limitnum,
606 $context = \context_user
::instance($USER->id
);
607 self
::validate_context($context);
609 if (empty($params['courseids'])) {
610 return ['groupedbycourse' => []];
613 $renderer = $PAGE->get_renderer('core_calendar');
614 $courses = enrol_get_my_courses('*', null, 0, $params['courseids']);
615 $courses = array_values($courses);
617 if (empty($courses)) {
618 return ['groupedbycourse' => []];
621 $events = local_api
::get_action_events_by_courses(
623 $params['timesortfrom'],
624 $params['timesortto'],
628 if (empty($events)) {
629 return ['groupedbycourse' => []];
632 $exportercache = new events_related_objects_cache($events, $courses);
633 $exporter = new events_grouped_by_course_exporter($events, ['cache' => $exportercache]);
635 return $exporter->export($renderer);
639 * Returns description of method result value.
641 * @return external_description
643 public static function get_calendar_action_events_by_courses_returns() {
644 return events_grouped_by_course_exporter
::get_read_structure();
648 * Returns description of method parameters.
650 * @return external_function_parameters.
653 public static function create_calendar_events_parameters() {
654 // Userid is always current user, so no need to get it from client.
655 // Module based calendar events are not allowed here. Hence no need of instance and modulename.
656 // subscription id and uuid is not allowed as this is not an ical api.
657 return new external_function_parameters(
658 array('events' => new external_multiple_structure(
659 new external_single_structure(
661 'name' => new external_value(PARAM_TEXT
, 'event name', VALUE_REQUIRED
, '', NULL_NOT_ALLOWED
),
662 'description' => new external_value(PARAM_RAW
, 'Description', VALUE_DEFAULT
, null, NULL_ALLOWED
),
663 'format' => new external_format_value('description', VALUE_DEFAULT
),
664 'courseid' => new external_value(PARAM_INT
, 'course id', VALUE_DEFAULT
, 0, NULL_NOT_ALLOWED
),
665 'groupid' => new external_value(PARAM_INT
, 'group id', VALUE_DEFAULT
, 0, NULL_NOT_ALLOWED
),
666 'repeats' => new external_value(PARAM_INT
, 'number of repeats', VALUE_DEFAULT
, 0, NULL_NOT_ALLOWED
),
667 'eventtype' => new external_value(PARAM_TEXT
, 'Event type', VALUE_DEFAULT
, 'user', NULL_NOT_ALLOWED
),
668 'timestart' => new external_value(PARAM_INT
, 'timestart', VALUE_DEFAULT
, time(), NULL_NOT_ALLOWED
),
669 'timeduration' => new external_value(PARAM_INT
, 'time duration', VALUE_DEFAULT
, 0, NULL_NOT_ALLOWED
),
670 'visible' => new external_value(PARAM_INT
, 'visible', VALUE_DEFAULT
, 1, NULL_NOT_ALLOWED
),
671 'sequence' => new external_value(PARAM_INT
, 'sequence', VALUE_DEFAULT
, 1, NULL_NOT_ALLOWED
),
679 * Create calendar events.
681 * @param array $events A list of events to create.
682 * @return array array of events created.
684 * @throws moodle_exception if user doesnt have the permission to create events.
686 public static function create_calendar_events($events) {
689 // Parameter validation.
690 $params = self
::validate_parameters(self
::create_calendar_events_parameters(), array('events' => $events));
692 $transaction = $DB->start_delegated_transaction();
696 foreach ($params['events'] as $event) {
698 // Let us set some defaults.
699 $event['userid'] = $USER->id
;
700 $event['modulename'] = '';
701 $event['instance'] = 0;
702 $event['subscriptionid'] = null;
704 $event['format'] = external_validate_format($event['format']);
705 if ($event['repeats'] > 0) {
706 $event['repeat'] = 1;
708 $event['repeat'] = 0;
711 $eventobj = new calendar_event($event);
713 // Let's check if the user is allowed to delete an event.
714 if (!calendar_add_event_allowed($eventobj)) {
715 $warnings [] = array('item' => $event['name'], 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to create this event');
718 // Let's create the event.
719 $var = $eventobj->create($event);
720 $var = (array)$var->properties();
721 if ($event['repeat']) {
722 $children = $DB->get_records('event', array('repeatid' => $var['id']));
723 foreach ($children as $child) {
724 $return[] = (array) $child;
731 // Everything done smoothly, let's commit.
732 $transaction->allow_commit();
733 return array('events' => $return, 'warnings' => $warnings);
737 * Returns description of method result value.
739 * @return external_description.
742 public static function create_calendar_events_returns() {
743 return new external_single_structure(
745 'events' => new external_multiple_structure( new external_single_structure(
747 'id' => new external_value(PARAM_INT
, 'event id'),
748 'name' => new external_value(PARAM_TEXT
, 'event name'),
749 'description' => new external_value(PARAM_RAW
, 'Description', VALUE_OPTIONAL
),
750 'format' => new external_format_value('description'),
751 'courseid' => new external_value(PARAM_INT
, 'course id'),
752 'groupid' => new external_value(PARAM_INT
, 'group id'),
753 'userid' => new external_value(PARAM_INT
, 'user id'),
754 'repeatid' => new external_value(PARAM_INT
, 'repeat id', VALUE_OPTIONAL
),
755 'modulename' => new external_value(PARAM_TEXT
, 'module name', VALUE_OPTIONAL
),
756 'instance' => new external_value(PARAM_INT
, 'instance id'),
757 'eventtype' => new external_value(PARAM_TEXT
, 'Event type'),
758 'timestart' => new external_value(PARAM_INT
, 'timestart'),
759 'timeduration' => new external_value(PARAM_INT
, 'time duration'),
760 'visible' => new external_value(PARAM_INT
, 'visible'),
761 'uuid' => new external_value(PARAM_TEXT
, 'unique id of ical events', VALUE_OPTIONAL
, '', NULL_NOT_ALLOWED
),
762 'sequence' => new external_value(PARAM_INT
, 'sequence'),
763 'timemodified' => new external_value(PARAM_INT
, 'time modified'),
764 'subscriptionid' => new external_value(PARAM_INT
, 'Subscription id', VALUE_OPTIONAL
),
767 'warnings' => new external_warnings()
773 * Returns description of method parameters.
775 * @return external_function_parameters
777 public static function get_calendar_event_by_id_parameters() {
778 return new external_function_parameters(
780 'eventid' => new external_value(PARAM_INT
, 'The event id to be retrieved'),
786 * Get calendar event by id.
788 * @param int $eventid The calendar event id to be retrieved.
789 * @return array Array of event details
791 public static function get_calendar_event_by_id($eventid) {
794 $params = self
::validate_parameters(self
::get_calendar_event_by_id_parameters(), ['eventid' => $eventid]);
795 $context = \context_user
::instance($USER->id
);
797 self
::validate_context($context);
800 $legacyevent = calendar_event
::load($eventid);
801 // Must check we can see this event.
802 if (!calendar_view_event_allowed($legacyevent)) {
803 // We can't return a warning in this case because the event is not optional.
804 // We don't know the context for the event and it's not worth loading it.
805 $syscontext = context_system
::instance();
806 throw new \required_capability_exception
($syscontext, 'moodle/course:view', 'nopermission', '');
809 $legacyevent->count_repeats();
811 $eventmapper = event_container
::get_event_mapper();
812 $event = $eventmapper->from_legacy_event_to_event($legacyevent);
814 $cache = new events_related_objects_cache([$event]);
816 'context' => $cache->get_context($event),
817 'course' => $cache->get_course($event),
820 $exporter = new event_exporter($event, $relatedobjects);
821 $renderer = $PAGE->get_renderer('core_calendar');
823 return array('event' => $exporter->export($renderer), 'warnings' => $warnings);
827 * Returns description of method result value
829 * @return external_description
831 public static function get_calendar_event_by_id_returns() {
832 $eventstructure = event_exporter
::get_read_structure();
834 return new external_single_structure(array(
835 'event' => $eventstructure,
836 'warnings' => new external_warnings()
842 * Returns description of method parameters.
844 * @return external_function_parameters.
846 public static function submit_create_update_form_parameters() {
847 return new external_function_parameters(
849 'formdata' => new external_value(PARAM_RAW
, 'The data from the event form'),
855 * Handles the event form submission.
857 * @param string $formdata The event form data in a URI encoded param string
858 * @return array The created or modified event
859 * @throws moodle_exception
861 public static function submit_create_update_form($formdata) {
862 global $USER, $PAGE, $CFG;
863 require_once($CFG->libdir
."/filelib.php");
865 // Parameter validation.
866 $params = self
::validate_parameters(self
::submit_create_update_form_parameters(), ['formdata' => $formdata]);
867 $context = \context_user
::instance($USER->id
);
870 self
::validate_context($context);
871 parse_str($params['formdata'], $data);
874 // Request via WS, ignore sesskey checks in form library.
875 $USER->ignoresesskey
= true;
878 $eventtype = isset($data['eventtype']) ?
$data['eventtype'] : null;
879 $coursekey = ($eventtype == 'group') ?
'groupcourseid' : 'courseid';
880 $courseid = (!empty($data[$coursekey])) ?
$data[$coursekey] : null;
881 $editoroptions = \core_calendar\local\event\forms\create
::build_editor_options($context);
882 $formoptions = ['editoroptions' => $editoroptions, 'courseid' => $courseid];
883 $formoptions['eventtypes'] = calendar_get_allowed_event_types($courseid);
885 require_once($CFG->libdir
. '/grouplib.php');
886 $groupcoursedata = groups_get_course_data($courseid);
887 if (!empty($groupcoursedata->groups
)) {
888 $formoptions['groups'] = [];
889 foreach ($groupcoursedata->groups
as $groupid => $groupdata) {
890 $formoptions['groups'][$groupid] = $groupdata->name
;
895 if (!empty($data['id'])) {
896 $eventid = clean_param($data['id'], PARAM_INT
);
897 $legacyevent = calendar_event
::load($eventid);
898 $legacyevent->count_repeats();
899 $formoptions['event'] = $legacyevent;
900 $mform = new update_event_form(null, $formoptions, 'post', '', null, true, $data);
903 $mform = new create_event_form(null, $formoptions, 'post', '', null, true, $data);
906 if ($validateddata = $mform->get_data()) {
907 $formmapper = new create_update_form_mapper();
908 $properties = $formmapper->from_data_to_event_properties($validateddata);
910 if (is_null($legacyevent)) {
911 $legacyevent = new \
calendar_event($properties);
912 // Need to do this in order to initialise the description
913 // property which then triggers the update function below
914 // to set the appropriate default properties on the event.
915 $properties = $legacyevent->properties(true);
918 if (!calendar_edit_event_allowed($legacyevent, true)) {
919 print_error('nopermissiontoupdatecalendar');
922 $legacyevent->update($properties);
923 $eventcontext = $legacyevent->context
;
925 file_remove_editor_orphaned_files($validateddata->description
);
927 // Take any files added to the description draft file area and
928 // convert them into the proper event description file area. Also
929 // parse the description text and replace the URLs to the draft files
930 // with the @@PLUGIN_FILE@@ placeholder to be persisted in the DB.
931 $description = file_save_draft_area_files(
932 $validateddata->description
['itemid'],
937 create_event_form
::build_editor_options($eventcontext),
938 $validateddata->description
['text']
941 // If draft files were found then we need to save the new
942 // description value.
943 if ($description != $validateddata->description
['text']) {
944 $properties->id
= $legacyevent->id
;
945 $properties->description
= $description;
946 $legacyevent->update($properties);
949 $eventmapper = event_container
::get_event_mapper();
950 $event = $eventmapper->from_legacy_event_to_event($legacyevent);
951 $cache = new events_related_objects_cache([$event]);
953 'context' => $cache->get_context($event),
954 'course' => $cache->get_course($event),
956 $exporter = new event_exporter($event, $relatedobjects);
957 $renderer = $PAGE->get_renderer('core_calendar');
959 return [ 'event' => $exporter->export($renderer) ];
961 return [ 'validationerror' => true ];
966 * Returns description of method result value.
968 * @return external_description.
970 public static function submit_create_update_form_returns() {
971 $eventstructure = event_exporter
::get_read_structure();
972 $eventstructure->required
= VALUE_OPTIONAL
;
974 return new external_single_structure(
976 'event' => $eventstructure,
977 'validationerror' => new external_value(PARAM_BOOL
, 'Invalid form data', VALUE_DEFAULT
, false),
983 * Get data for the monthly calendar view.
985 * @param int $year The year to be shown
986 * @param int $month The month to be shown
987 * @param int $courseid The course to be included
988 * @param int $categoryid The category to be included
989 * @param bool $includenavigation Whether to include navigation
990 * @param bool $mini Whether to return the mini month view or not
991 * @param int $day The day we want to keep as the current day
994 public static function get_calendar_monthly_view($year, $month, $courseid, $categoryid, $includenavigation, $mini, $day) {
997 // Parameter validation.
998 $params = self
::validate_parameters(self
::get_calendar_monthly_view_parameters(), [
1001 'courseid' => $courseid,
1002 'categoryid' => $categoryid,
1003 'includenavigation' => $includenavigation,
1008 $context = \context_user
::instance($USER->id
);
1009 self
::validate_context($context);
1010 $PAGE->set_url('/calendar/');
1012 $type = \core_calendar\type_factory
::get_calendar_instance();
1014 $time = $type->convert_to_timestamp($params['year'], $params['month'], $params['day']);
1015 $calendar = \calendar_information
::create($time, $params['courseid'], $params['categoryid']);
1016 self
::validate_context($calendar->context
);
1018 $view = $params['mini'] ?
'mini' : 'month';
1019 list($data, $template) = calendar_get_view($calendar, $view, $params['includenavigation']);
1025 * Returns description of method parameters.
1027 * @return external_function_parameters
1029 public static function get_calendar_monthly_view_parameters() {
1030 return new external_function_parameters(
1032 'year' => new external_value(PARAM_INT
, 'Year to be viewed', VALUE_REQUIRED
),
1033 'month' => new external_value(PARAM_INT
, 'Month to be viewed', VALUE_REQUIRED
),
1034 'courseid' => new external_value(PARAM_INT
, 'Course being viewed', VALUE_DEFAULT
, SITEID
, NULL_ALLOWED
),
1035 'categoryid' => new external_value(PARAM_INT
, 'Category being viewed', VALUE_DEFAULT
, null, NULL_ALLOWED
),
1036 'includenavigation' => new external_value(
1038 'Whether to show course navigation',
1043 'mini' => new external_value(
1045 'Whether to return the mini month view or not',
1050 'day' => new external_value(PARAM_INT
, 'Day to be viewed', VALUE_DEFAULT
, 1),
1056 * Returns description of method result value.
1058 * @return external_description
1060 public static function get_calendar_monthly_view_returns() {
1061 return \core_calendar\external\month_exporter
::get_read_structure();
1065 * Get data for the daily calendar view.
1067 * @param int $year The year to be shown
1068 * @param int $month The month to be shown
1069 * @param int $day The day to be shown
1070 * @param int $courseid The course to be included
1073 public static function get_calendar_day_view($year, $month, $day, $courseid, $categoryid) {
1074 global $DB, $USER, $PAGE;
1076 // Parameter validation.
1077 $params = self
::validate_parameters(self
::get_calendar_day_view_parameters(), [
1081 'courseid' => $courseid,
1082 'categoryid' => $categoryid,
1085 $context = \context_user
::instance($USER->id
);
1086 self
::validate_context($context);
1088 $type = \core_calendar\type_factory
::get_calendar_instance();
1090 $time = $type->convert_to_timestamp($params['year'], $params['month'], $params['day']);
1091 $calendar = \calendar_information
::create($time, $params['courseid'], $params['categoryid']);
1092 self
::validate_context($calendar->context
);
1094 list($data, $template) = calendar_get_view($calendar, 'day');
1100 * Returns description of method parameters.
1102 * @return external_function_parameters
1104 public static function get_calendar_day_view_parameters() {
1105 return new external_function_parameters(
1107 'year' => new external_value(PARAM_INT
, 'Year to be viewed', VALUE_REQUIRED
),
1108 'month' => new external_value(PARAM_INT
, 'Month to be viewed', VALUE_REQUIRED
),
1109 'day' => new external_value(PARAM_INT
, 'Day to be viewed', VALUE_REQUIRED
),
1110 'courseid' => new external_value(PARAM_INT
, 'Course being viewed', VALUE_DEFAULT
, SITEID
, NULL_ALLOWED
),
1111 'categoryid' => new external_value(PARAM_INT
, 'Category being viewed', VALUE_DEFAULT
, null, NULL_ALLOWED
),
1117 * Returns description of method result value.
1119 * @return external_description
1121 public static function get_calendar_day_view_returns() {
1122 return \core_calendar\external\calendar_day_exporter
::get_read_structure();
1127 * Returns description of method parameters.
1129 * @return external_function_parameters
1131 public static function update_event_start_day_parameters() {
1132 return new external_function_parameters(
1134 'eventid' => new external_value(PARAM_INT
, 'Id of event to be updated', VALUE_REQUIRED
),
1135 'daytimestamp' => new external_value(PARAM_INT
, 'Timestamp for the new start day', VALUE_REQUIRED
),
1141 * Change the start day for the given calendar event to the day that
1142 * corresponds with the provided timestamp.
1144 * The timestamp only needs to be anytime within the desired day as only
1145 * the date data is extracted from it.
1147 * The event's original time of day is maintained, only the date is shifted.
1149 * @param int $eventid Id of event to be updated
1150 * @param int $daytimestamp Timestamp for the new start day
1153 public static function update_event_start_day($eventid, $daytimestamp) {
1154 global $USER, $PAGE;
1156 // Parameter validation.
1157 $params = self
::validate_parameters(self
::update_event_start_day_parameters(), [
1158 'eventid' => $eventid,
1159 'daytimestamp' => $daytimestamp,
1162 $vault = event_container
::get_event_vault();
1163 $mapper = event_container
::get_event_mapper();
1164 $event = $vault->get_event_by_id($eventid);
1167 throw new \
moodle_exception('Unable to find event with id ' . $eventid);
1170 $legacyevent = $mapper->from_event_to_legacy_event($event);
1172 if (!calendar_edit_event_allowed($legacyevent, true)) {
1173 print_error('nopermissiontoupdatecalendar');
1176 self
::validate_context($legacyevent->context
);
1178 $newdate = usergetdate($daytimestamp);
1179 $startdatestring = implode('-', [$newdate['year'], $newdate['mon'], $newdate['mday']]);
1180 $startdate = new DateTimeImmutable($startdatestring);
1181 $event = local_api
::update_event_start_day($event, $startdate);
1182 $cache = new events_related_objects_cache([$event]);
1184 'context' => $cache->get_context($event),
1185 'course' => $cache->get_course($event),
1187 $exporter = new event_exporter($event, $relatedobjects);
1188 $renderer = $PAGE->get_renderer('core_calendar');
1190 return array('event' => $exporter->export($renderer));
1194 * Returns description of method result value.
1196 * @return external_description
1198 public static function update_event_start_day_returns() {
1199 return new external_single_structure(
1201 'event' => event_exporter
::get_read_structure()
1207 * Get data for the monthly calendar view.
1209 * @param int $courseid The course to be included
1210 * @param int $categoryid The category to be included
1213 public static function get_calendar_upcoming_view($courseid, $categoryid) {
1214 global $DB, $USER, $PAGE;
1216 // Parameter validation.
1217 $params = self
::validate_parameters(self
::get_calendar_upcoming_view_parameters(), [
1218 'courseid' => $courseid,
1219 'categoryid' => $categoryid,
1222 $context = \context_user
::instance($USER->id
);
1223 self
::validate_context($context);
1224 $PAGE->set_url('/calendar/');
1226 $calendar = \calendar_information
::create(time(), $params['courseid'], $params['categoryid']);
1227 self
::validate_context($calendar->context
);
1229 list($data, $template) = calendar_get_view($calendar, 'upcoming');
1235 * Returns description of method parameters.
1237 * @return external_function_parameters
1239 public static function get_calendar_upcoming_view_parameters() {
1240 return new external_function_parameters(
1242 'courseid' => new external_value(PARAM_INT
, 'Course being viewed', VALUE_DEFAULT
, SITEID
, NULL_ALLOWED
),
1243 'categoryid' => new external_value(PARAM_INT
, 'Category being viewed', VALUE_DEFAULT
, null, NULL_ALLOWED
),
1249 * Returns description of method result value.
1251 * @return external_description
1253 public static function get_calendar_upcoming_view_returns() {
1254 return \core_calendar\external\calendar_upcoming_exporter
::get_read_structure();
1259 * Returns description of method parameters.
1261 * @return external_function_parameters.
1264 public static function get_calendar_access_information_parameters() {
1265 return new external_function_parameters(
1267 'courseid' => new external_value(PARAM_INT
, 'Course to check, empty for site calendar events.', VALUE_DEFAULT
, 0),
1273 * Convenience function to retrieve some permissions information for the given course calendar.
1275 * @param int $courseid Course to check, empty for site.
1276 * @return array The access information
1277 * @throws moodle_exception
1280 public static function get_calendar_access_information($courseid = 0) {
1282 $params = self
::validate_parameters(self
::get_calendar_access_information_parameters(), ['courseid' => $courseid]);
1284 if (empty($params['courseid']) ||
$params['courseid'] == SITEID
) {
1285 $context = \context_system
::instance();
1287 $context = \context_course
::instance($params['courseid']);
1290 self
::validate_context($context);
1293 'canmanageentries' => has_capability('moodle/calendar:manageentries', $context),
1294 'canmanageownentries' => has_capability('moodle/calendar:manageownentries', $context),
1295 'canmanagegroupentries' => has_capability('moodle/calendar:managegroupentries', $context),
1301 * Returns description of method result value.
1303 * @return external_description.
1306 public static function get_calendar_access_information_returns() {
1308 return new external_single_structure(
1310 'canmanageentries' => new external_value(PARAM_BOOL
, 'Whether the user can manage entries.'),
1311 'canmanageownentries' => new external_value(PARAM_BOOL
, 'Whether the user can manage its own entries.'),
1312 'canmanagegroupentries' => new external_value(PARAM_BOOL
, 'Whether the user can manage group entries.'),
1313 'warnings' => new external_warnings(),
1319 * Returns description of method parameters.
1321 * @return external_function_parameters.
1324 public static function get_allowed_event_types_parameters() {
1325 return new external_function_parameters(
1327 'courseid' => new external_value(PARAM_INT
, 'Course to check, empty for site.', VALUE_DEFAULT
, 0),
1333 * Get the type of events a user can create in the given course.
1335 * @param int $courseid Course to check, empty for site.
1336 * @return array The types allowed
1337 * @throws moodle_exception
1340 public static function get_allowed_event_types($courseid = 0) {
1342 $params = self
::validate_parameters(self
::get_allowed_event_types_parameters(), ['courseid' => $courseid]);
1344 if (empty($params['courseid']) ||
$params['courseid'] == SITEID
) {
1345 $context = \context_system
::instance();
1347 $context = \context_course
::instance($params['courseid']);
1350 self
::validate_context($context);
1352 $allowedeventtypes = array_filter(calendar_get_allowed_event_types($params['courseid']));
1355 'allowedeventtypes' => array_keys($allowedeventtypes),
1361 * Returns description of method result value.
1363 * @return external_description.
1366 public static function get_allowed_event_types_returns() {
1368 return new external_single_structure(
1370 'allowedeventtypes' => new external_multiple_structure(
1371 new external_value(PARAM_NOTAGS
, 'Allowed event types to be created in the given course.')
1373 'warnings' => new external_warnings(),
1379 * Convert the specified dates into unix timestamps.
1381 * @param array $datetimes Array of arrays containing date time details, each in the format:
1382 * ['year' => a, 'month' => b, 'day' => c,
1383 * 'hour' => d (optional), 'minute' => e (optional), 'key' => 'x' (optional)]
1384 * @return array Provided array of dates converted to unix timestamps
1385 * @throws moodle_exception If one or more of the dates provided does not convert to a valid timestamp.
1387 public static function get_timestamps($datetimes) {
1388 $params = self
::validate_parameters(self
::get_timestamps_parameters(), ['data' => $datetimes]);
1390 $type = \core_calendar\type_factory
::get_calendar_instance();
1391 $timestamps = ['timestamps' => []];
1393 foreach ($params['data'] as $key => $datetime) {
1394 $hour = $datetime['hour'] ??
0;
1395 $minute = $datetime['minute'] ??
0;
1398 $timestamp = $type->convert_to_timestamp(
1399 $datetime['year'], $datetime['month'], $datetime['day'], $hour, $minute);
1401 $timestamps['timestamps'][] = [
1402 'key' => $datetime['key'] ??
$key,
1403 'timestamp' => $timestamp,
1406 } catch (Exception
$e) {
1407 throw new moodle_exception('One or more of the dates provided were invalid');
1415 * Describes the parameters for get_timestamps.
1417 * @return external_function_parameters
1419 public static function get_timestamps_parameters() {
1420 return new external_function_parameters ([
1421 'data' => new external_multiple_structure(
1422 new external_single_structure(
1424 'key' => new external_value(PARAM_ALPHANUMEXT
, 'key', VALUE_OPTIONAL
),
1425 'year' => new external_value(PARAM_INT
, 'year'),
1426 'month' => new external_value(PARAM_INT
, 'month'),
1427 'day' => new external_value(PARAM_INT
, 'day'),
1428 'hour' => new external_value(PARAM_INT
, 'hour', VALUE_OPTIONAL
),
1429 'minute' => new external_value(PARAM_INT
, 'minute', VALUE_OPTIONAL
),
1437 * Describes the timestamps return format.
1439 * @return external_single_structure
1441 public static function get_timestamps_returns() {
1442 return new external_single_structure(
1444 'timestamps' => new external_multiple_structure(
1445 new external_single_structure(
1447 'key' => new external_value(PARAM_ALPHANUMEXT
, 'Timestamp key'),
1448 'timestamp' => new external_value(PARAM_INT
, 'Unix timestamp'),