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/>.
18 * External calendar API
20 * @package core_calendar
22 * @copyright 2012 Ankit Agarwal
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') ||
die;
29 require_once($CFG->dirroot
. '/calendar/lib.php');
31 use core_calendar\local\api
as local_api
;
32 use core_calendar\local\event\container
as event_container
;
33 use core_calendar\local\event\forms\create
as create_event_form
;
34 use core_calendar\local\event\forms\update
as update_event_form
;
35 use core_calendar\local\event\mappers\create_update_form_mapper
;
36 use core_calendar\external\event_exporter
;
37 use core_calendar\external\events_exporter
;
38 use core_calendar\external\events_grouped_by_course_exporter
;
39 use core_calendar\external\events_related_objects_cache
;
40 use core_external\external_api
;
41 use core_external\external_format_value
;
42 use core_external\external_function_parameters
;
43 use core_external\external_multiple_structure
;
44 use core_external\external_single_structure
;
45 use core_external\external_value
;
46 use core_external\external_warnings
;
47 use core_external\util
as external_util
;
50 * Calendar external functions
52 * @package core_calendar
54 * @copyright 2012 Ankit Agarwal
55 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
58 class core_calendar_external
extends external_api
{
60 * Returns description of method parameters
62 * @return external_function_parameters
65 public static function delete_calendar_events_parameters() {
66 return new external_function_parameters(
67 array('events' => new external_multiple_structure(
68 new external_single_structure(
70 'eventid' => new external_value(PARAM_INT
, 'Event ID', VALUE_REQUIRED
, '', NULL_NOT_ALLOWED
),
71 'repeat' => new external_value(PARAM_BOOL
, 'Delete comeplete series if repeated event')
72 ), 'List of events to delete'
80 * Delete Calendar events
82 * @param array $eventids A list of event ids with repeat flag to delete
86 public static function delete_calendar_events($events) {
89 // Parameter validation.
90 $params = self
::validate_parameters(self
:: delete_calendar_events_parameters(), array('events' => $events));
92 $transaction = $DB->start_delegated_transaction();
94 foreach ($params['events'] as $event) {
95 $eventobj = calendar_event
::load($event['eventid']);
97 // Let's check if the user is allowed to delete an event.
98 if (!calendar_delete_event_allowed($eventobj)) {
99 throw new moodle_exception('nopermissions', 'error', '', get_string('deleteevent', 'calendar'));
101 // Time to do the magic.
102 $eventobj->delete($event['repeat']);
105 // Everything done smoothly, let's commit.
106 $transaction->allow_commit();
112 * Returns description of method result value
114 * @return \core_external\external_description
117 public static function delete_calendar_events_returns() {
122 * Returns description of method parameters
124 * @return external_function_parameters
127 public static function get_calendar_events_parameters() {
128 return new external_function_parameters(
129 array('events' => new external_single_structure(
131 'eventids' => new external_multiple_structure(
132 new external_value(PARAM_INT
, 'event ids')
133 , 'List of event ids',
134 VALUE_DEFAULT
, array()),
135 'courseids' => new external_multiple_structure(
136 new external_value(PARAM_INT
, 'course ids')
137 , 'List of course ids for which events will be returned',
138 VALUE_DEFAULT
, array()),
139 'groupids' => new external_multiple_structure(
140 new external_value(PARAM_INT
, 'group ids')
141 , 'List of group ids for which events should be returned',
142 VALUE_DEFAULT
, array()),
143 'categoryids' => new external_multiple_structure(
144 new external_value(PARAM_INT
, 'Category ids'),
145 'List of category ids for which events will be returned',
146 VALUE_DEFAULT
, array()),
147 ), 'Event details', VALUE_DEFAULT
, array()),
148 'options' => new external_single_structure(
150 'userevents' => new external_value(PARAM_BOOL
,
151 "Set to true to return current user's user events",
152 VALUE_DEFAULT
, true, NULL_ALLOWED
),
153 'siteevents' => new external_value(PARAM_BOOL
,
154 "Set to true to return site events",
155 VALUE_DEFAULT
, true, NULL_ALLOWED
),
156 'timestart' => new external_value(PARAM_INT
,
157 "Time from which events should be returned",
158 VALUE_DEFAULT
, 0, NULL_ALLOWED
),
159 'timeend' => new external_value(PARAM_INT
,
160 "Time to which the events should be returned. We treat 0 and null as no end",
161 VALUE_DEFAULT
, 0, NULL_ALLOWED
),
162 'ignorehidden' => new external_value(PARAM_BOOL
,
163 "Ignore hidden events or not",
164 VALUE_DEFAULT
, true, NULL_ALLOWED
),
166 ), 'Options', VALUE_DEFAULT
, array())
172 * Get Calendar events
174 * @param array $events A list of events
175 * @param array $options various options
176 * @return array Array of event details
179 public static function get_calendar_events($events = array(), $options = array()) {
180 global $SITE, $DB, $USER;
182 // Parameter validation.
183 $params = self
::validate_parameters(self
::get_calendar_events_parameters(), array('events' => $events, 'options' => $options));
184 $funcparam = array('courses' => array(), 'groups' => array(), 'categories' => array());
185 $hassystemcap = has_capability('moodle/calendar:manageentries', context_system
::instance());
187 $coursecategories = array();
189 // Let us find out courses and their categories that we can return events from.
190 if (!$hassystemcap) {
191 $courseobjs = enrol_get_my_courses();
192 $courses = array_keys($courseobjs);
194 $coursecategories = array_flip(array_map(function($course) {
195 return $course->category
;
198 foreach ($params['events']['courseids'] as $id) {
200 $context = context_course
::instance($id);
201 self
::validate_context($context);
202 $funcparam['courses'][] = $id;
203 } catch (Exception
$e) {
207 'warningcode' => 'nopermissions',
208 'message' => 'No access rights in course context '.$e->getMessage().$e->getTraceAsString()
213 $courses = $params['events']['courseids'];
214 $funcparam['courses'] = $courses;
216 if (!empty($courses)) {
217 list($wheresql, $sqlparams) = $DB->get_in_or_equal($courses);
218 $wheresql = "id $wheresql";
219 $coursecategories = array_flip(array_map(function($course) {
220 return $course->category
;
221 }, $DB->get_records_select('course', $wheresql, $sqlparams, '', 'category')));
225 // Let us findout groups that we can return events from.
226 if (!$hassystemcap) {
227 $groups = groups_get_my_groups();
228 $groups = array_keys($groups);
229 foreach ($params['events']['groupids'] as $id) {
230 if (in_array($id, $groups)) {
231 $funcparam['groups'][] = $id;
233 $warnings[] = array('item' => $id, 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to access this group');
237 $groups = $params['events']['groupids'];
238 $funcparam['groups'] = $groups;
241 $categories = array();
242 if ($hassystemcap ||
!empty($courses)) {
243 // Use the category id as the key in the following array. That way we do not have to remove duplicates and
244 // have a faster lookup later.
247 if (!empty($params['events']['categoryids'])) {
248 $catobjs = \core_course_category
::get_many(
249 array_merge($params['events']['categoryids'], array_keys($coursecategories)));
250 foreach ($catobjs as $catobj) {
251 if (isset($coursecategories[$catobj->id
]) ||
252 has_capability('moodle/category:manage', $catobj->get_context())) {
253 // If the user has access to a course in this category or can manage the category,
254 // then they can see all parent categories too.
255 $categories[$catobj->id
] = true;
256 foreach ($catobj->get_parents() as $catid) {
257 $categories[$catid] = true;
261 $funcparam['categories'] = array_keys($categories);
263 // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
264 $calcatcache = cache
::make('core', 'calendar_categories');
265 // Do not use cache if the user has the system capability as $coursecategories might not represent the
266 // courses the user is enrolled in.
267 $categories = (!$hassystemcap) ?
$calcatcache->get('site') : false;
268 if ($categories !== false) {
269 // The ids are stored in a list in the cache.
270 $funcparam['categories'] = $categories;
271 $categories = array_flip($categories);
274 foreach (\core_course_category
::get_all() as $category) {
275 if (isset($coursecategories[$category->id
]) ||
276 has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
277 // If the user has access to a course in this category or can manage the category,
278 // then they can see all parent categories too.
279 $categories[$category->id
] = true;
280 foreach ($category->get_parents() as $catid) {
281 $categories[$catid] = true;
285 $funcparam['categories'] = array_keys($categories);
286 if (!$hassystemcap) {
287 $calcatcache->set('site', $funcparam['categories']);
293 // Do we need user events?
294 if (!empty($params['options']['userevents'])) {
295 $funcparam['users'] = array($USER->id
);
297 $funcparam['users'] = false;
300 // Do we need site events?
301 if (!empty($params['options']['siteevents'])) {
302 $funcparam['courses'][] = $SITE->id
;
305 // We treat 0 and null as no end.
306 if (empty($params['options']['timeend'])) {
307 $params['options']['timeend'] = PHP_INT_MAX
;
310 // Event list does not check visibility and permissions, we'll check that later.
311 $eventlist = calendar_get_legacy_events($params['options']['timestart'], $params['options']['timeend'],
312 $funcparam['users'], $funcparam['groups'], $funcparam['courses'], true,
313 $params['options']['ignorehidden'], $funcparam['categories']);
315 // WS expects arrays.
318 // We need to get events asked for eventids.
319 if ($eventsbyid = calendar_get_events_by_id($params['events']['eventids'])) {
320 $eventlist +
= $eventsbyid;
322 foreach ($eventlist as $eventid => $eventobj) {
323 $event = (array) $eventobj;
324 // Description formatting.
325 $calendareventobj = new calendar_event($event);
326 $event['name'] = $calendareventobj->format_external_name();
327 list($event['description'], $event['format']) = $calendareventobj->format_external_text();
330 // User can see everything, no further check is needed.
331 $events[$eventid] = $event;
332 } else if (!empty($eventobj->modulename
)) {
333 $courseid = $eventobj->courseid
;
335 if (!$calendareventobj->context ||
!($context = $calendareventobj->context
->get_course_context(false))) {
338 $courseid = $context->instanceid
;
340 $instances = get_fast_modinfo($courseid)->get_instances_of($eventobj->modulename
);
341 if (!empty($instances[$eventobj->instance
]->uservisible
)) {
342 $events[$eventid] = $event;
345 // Can the user actually see this event?
346 $eventobj = calendar_event
::load($eventobj);
347 if ((($eventobj->courseid
== $SITE->id
) && (empty($eventobj->categoryid
))) ||
348 (!empty($eventobj->categoryid
) && isset($categories[$eventobj->categoryid
])) ||
349 (!empty($eventobj->groupid
) && in_array($eventobj->groupid
, $groups)) ||
350 (!empty($eventobj->courseid
) && in_array($eventobj->courseid
, $courses)) ||
351 ($USER->id
== $eventobj->userid
) ||
352 (calendar_edit_event_allowed($eventobj))) {
353 $events[$eventid] = $event;
355 $warnings[] = array('item' => $eventid, 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to view this event');
359 return array('events' => $events, 'warnings' => $warnings);
363 * Returns description of method result value
365 * @return \core_external\external_description
368 public static function get_calendar_events_returns() {
369 return new external_single_structure(array(
370 'events' => new external_multiple_structure( new external_single_structure(
372 'id' => new external_value(PARAM_INT
, 'event id'),
373 'name' => new external_value(PARAM_RAW
, 'event name'),
374 'description' => new external_value(PARAM_RAW
, 'Description', VALUE_OPTIONAL
, null, NULL_ALLOWED
),
375 'format' => new external_format_value('description'),
376 'courseid' => new external_value(PARAM_INT
, 'course id'),
377 'categoryid' => new external_value(PARAM_INT
, 'Category id (only for category events).',
379 'groupid' => new external_value(PARAM_INT
, 'group id'),
380 'userid' => new external_value(PARAM_INT
, 'user id'),
381 'repeatid' => new external_value(PARAM_INT
, 'repeat id'),
382 'modulename' => new external_value(PARAM_TEXT
, 'module name', VALUE_OPTIONAL
, null, NULL_ALLOWED
),
383 'instance' => new external_value(PARAM_INT
, 'instance id'),
384 'eventtype' => new external_value(PARAM_TEXT
, 'Event type'),
385 'timestart' => new external_value(PARAM_INT
, 'timestart'),
386 'timeduration' => new external_value(PARAM_INT
, 'time duration'),
387 'visible' => new external_value(PARAM_INT
, 'visible'),
388 'uuid' => new external_value(PARAM_TEXT
, 'unique id of ical events', VALUE_OPTIONAL
, null, NULL_NOT_ALLOWED
),
389 'sequence' => new external_value(PARAM_INT
, 'sequence'),
390 'timemodified' => new external_value(PARAM_INT
, 'time modified'),
391 'subscriptionid' => new external_value(PARAM_INT
, 'Subscription id', VALUE_OPTIONAL
, null, NULL_ALLOWED
),
394 'warnings' => new external_warnings()
400 * Returns description of method parameters.
403 * @return external_function_parameters
405 public static function get_calendar_action_events_by_timesort_parameters() {
406 return new external_function_parameters(
408 'timesortfrom' => new external_value(PARAM_INT
, 'Time sort from', VALUE_DEFAULT
, 0),
409 'timesortto' => new external_value(PARAM_INT
, 'Time sort to', VALUE_DEFAULT
, null),
410 'aftereventid' => new external_value(PARAM_INT
, 'The last seen event id', VALUE_DEFAULT
, 0),
411 'limitnum' => new external_value(PARAM_INT
, 'Limit number', VALUE_DEFAULT
, 20),
412 'limittononsuspendedevents' => new external_value(PARAM_BOOL
,
413 'Limit the events to courses the user is not suspended in', VALUE_DEFAULT
, false),
414 'userid' => new external_value(PARAM_INT
, 'The user id', VALUE_DEFAULT
, null),
415 'searchvalue' => new external_value(PARAM_RAW
, 'The value a user wishes to search against', VALUE_DEFAULT
, null)
421 * Get calendar action events based on the timesort value.
424 * @param null|int $timesortfrom Events after this time (inclusive)
425 * @param null|int $timesortto Events before this time (inclusive)
426 * @param null|int $aftereventid Get events with ids greater than this one
427 * @param int $limitnum Limit the number of results to this value
428 * @param null|int $userid The user id
429 * @param string|null $searchvalue The value a user wishes to search against
432 public static function get_calendar_action_events_by_timesort($timesortfrom = 0, $timesortto = null,
433 $aftereventid = 0, $limitnum = 20, $limittononsuspendedevents = false,
434 $userid = null, ?
string $searchvalue = null) {
437 $params = self
::validate_parameters(
438 self
::get_calendar_action_events_by_timesort_parameters(),
440 'timesortfrom' => $timesortfrom,
441 'timesortto' => $timesortto,
442 'aftereventid' => $aftereventid,
443 'limitnum' => $limitnum,
444 'limittononsuspendedevents' => $limittononsuspendedevents,
446 'searchvalue' => $searchvalue
449 if ($params['userid']) {
450 $user = \core_user
::get_user($params['userid']);
455 $context = \context_user
::instance($user->id
);
456 self
::validate_context($context);
458 if ($params['userid'] && $USER->id
!== $params['userid'] && !has_capability('moodle/calendar:manageentries', $context)) {
459 throw new \required_capability_exception
($context, 'moodle/calendar:manageentries', 'nopermission', '');
462 if (empty($params['aftereventid'])) {
463 $params['aftereventid'] = null;
466 $renderer = $PAGE->get_renderer('core_calendar');
467 $events = local_api
::get_action_events_by_timesort(
468 $params['timesortfrom'],
469 $params['timesortto'],
470 $params['aftereventid'],
472 $params['limittononsuspendedevents'],
474 clean_param($params['searchvalue'], PARAM_TEXT
)
477 $exportercache = new events_related_objects_cache($events);
478 $exporter = new events_exporter($events, ['cache' => $exportercache]);
480 return $exporter->export($renderer);
484 * Returns description of method result value.
487 * @return \core_external\external_description
489 public static function get_calendar_action_events_by_timesort_returns() {
490 return events_exporter
::get_read_structure();
494 * Returns description of method parameters.
496 * @return external_function_parameters
498 public static function get_calendar_action_events_by_course_parameters() {
499 return new external_function_parameters(
501 'courseid' => new external_value(PARAM_INT
, 'Course id'),
502 'timesortfrom' => new external_value(PARAM_INT
, 'Time sort from', VALUE_DEFAULT
, null),
503 'timesortto' => new external_value(PARAM_INT
, 'Time sort to', VALUE_DEFAULT
, null),
504 'aftereventid' => new external_value(PARAM_INT
, 'The last seen event id', VALUE_DEFAULT
, 0),
505 'limitnum' => new external_value(PARAM_INT
, 'Limit number', VALUE_DEFAULT
, 20),
506 'searchvalue' => new external_value(PARAM_RAW
, 'The value a user wishes to search against', VALUE_DEFAULT
, null)
512 * Get calendar action events for the given course.
515 * @param int $courseid Only events in this course
516 * @param null|int $timesortfrom Events after this time (inclusive)
517 * @param null|int $timesortto Events before this time (inclusive)
518 * @param null|int $aftereventid Get events with ids greater than this one
519 * @param int $limitnum Limit the number of results to this value
520 * @param string|null $searchvalue The value a user wishes to search against
523 public static function get_calendar_action_events_by_course(
524 $courseid, $timesortfrom = null, $timesortto = null, $aftereventid = 0, $limitnum = 20, ?
string $searchvalue = null) {
529 $params = self
::validate_parameters(
530 self
::get_calendar_action_events_by_course_parameters(),
532 'courseid' => $courseid,
533 'timesortfrom' => $timesortfrom,
534 'timesortto' => $timesortto,
535 'aftereventid' => $aftereventid,
536 'limitnum' => $limitnum,
537 'searchvalue' => $searchvalue
540 $context = \context_user
::instance($USER->id
);
541 self
::validate_context($context);
543 if (empty($params['aftereventid'])) {
544 $params['aftereventid'] = null;
547 $courses = enrol_get_my_courses('*', null, 0, [$courseid]);
548 $courses = array_values($courses);
550 if (empty($courses)) {
554 $course = $courses[0];
555 $renderer = $PAGE->get_renderer('core_calendar');
556 $events = local_api
::get_action_events_by_course(
558 $params['timesortfrom'],
559 $params['timesortto'],
560 $params['aftereventid'],
562 clean_param($params['searchvalue'], PARAM_TEXT
)
565 $exportercache = new events_related_objects_cache($events, $courses);
566 $exporter = new events_exporter($events, ['cache' => $exportercache]);
568 return $exporter->export($renderer);
572 * Returns description of method result value.
574 * @return \core_external\external_description
576 public static function get_calendar_action_events_by_course_returns() {
577 return events_exporter
::get_read_structure();
581 * Returns description of method parameters.
583 * @return external_function_parameters
585 public static function get_calendar_action_events_by_courses_parameters() {
586 return new external_function_parameters(
588 'courseids' => new external_multiple_structure(
589 new external_value(PARAM_INT
, 'Course id')
591 'timesortfrom' => new external_value(PARAM_INT
, 'Time sort from', VALUE_DEFAULT
, null),
592 'timesortto' => new external_value(PARAM_INT
, 'Time sort to', VALUE_DEFAULT
, null),
593 'limitnum' => new external_value(PARAM_INT
, 'Limit number', VALUE_DEFAULT
, 10),
594 'searchvalue' => new external_value(PARAM_RAW
, 'The value a user wishes to search against', VALUE_DEFAULT
, null)
600 * Get calendar action events for a given list of courses.
603 * @param array $courseids Only include events for these courses
604 * @param null|int $timesortfrom Events after this time (inclusive)
605 * @param null|int $timesortto Events before this time (inclusive)
606 * @param int $limitnum Limit the number of results per course to this value
607 * @param string|null $searchvalue The value a user wishes to search against
610 public static function get_calendar_action_events_by_courses(
611 array $courseids, $timesortfrom = null, $timesortto = null, $limitnum = 10, ?
string $searchvalue = null) {
616 $params = self
::validate_parameters(
617 self
::get_calendar_action_events_by_courses_parameters(),
619 'courseids' => $courseids,
620 'timesortfrom' => $timesortfrom,
621 'timesortto' => $timesortto,
622 'limitnum' => $limitnum,
623 'searchvalue' => $searchvalue
626 $context = \context_user
::instance($USER->id
);
627 self
::validate_context($context);
629 if (empty($params['courseids'])) {
630 return ['groupedbycourse' => []];
633 $renderer = $PAGE->get_renderer('core_calendar');
634 $courses = enrol_get_my_courses('*', null, 0, $params['courseids']);
635 $courses = array_values($courses);
637 if (empty($courses)) {
638 return ['groupedbycourse' => []];
641 $events = local_api
::get_action_events_by_courses(
643 $params['timesortfrom'],
644 $params['timesortto'],
646 clean_param($params['searchvalue'], PARAM_TEXT
)
649 if (empty($events)) {
650 return ['groupedbycourse' => []];
653 $exportercache = new events_related_objects_cache($events, $courses);
654 $exporter = new events_grouped_by_course_exporter($events, ['cache' => $exportercache]);
656 return $exporter->export($renderer);
660 * Returns description of method result value.
662 * @return \core_external\external_description
664 public static function get_calendar_action_events_by_courses_returns() {
665 return events_grouped_by_course_exporter
::get_read_structure();
669 * Returns description of method parameters.
671 * @return external_function_parameters.
674 public static function create_calendar_events_parameters() {
675 // Userid is always current user, so no need to get it from client.
676 // Module based calendar events are not allowed here. Hence no need of instance and modulename.
677 // subscription id and uuid is not allowed as this is not an ical api.
678 return new external_function_parameters(
679 array('events' => new external_multiple_structure(
680 new external_single_structure(
682 'name' => new external_value(PARAM_TEXT
, 'event name', VALUE_REQUIRED
, '', NULL_NOT_ALLOWED
),
683 'description' => new external_value(PARAM_RAW
, 'Description', VALUE_DEFAULT
, null, NULL_ALLOWED
),
684 'format' => new external_format_value('description', VALUE_DEFAULT
),
685 'courseid' => new external_value(PARAM_INT
, 'course id', VALUE_DEFAULT
, 0, NULL_NOT_ALLOWED
),
686 'groupid' => new external_value(PARAM_INT
, 'group id', VALUE_DEFAULT
, 0, NULL_NOT_ALLOWED
),
687 'repeats' => new external_value(PARAM_INT
, 'number of repeats', VALUE_DEFAULT
, 0, NULL_NOT_ALLOWED
),
688 'eventtype' => new external_value(PARAM_TEXT
, 'Event type', VALUE_DEFAULT
, 'user', NULL_NOT_ALLOWED
),
689 'timestart' => new external_value(PARAM_INT
, 'timestart', VALUE_DEFAULT
, time(), NULL_NOT_ALLOWED
),
690 'timeduration' => new external_value(PARAM_INT
, 'time duration', VALUE_DEFAULT
, 0, NULL_NOT_ALLOWED
),
691 'visible' => new external_value(PARAM_INT
, 'visible', VALUE_DEFAULT
, 1, NULL_NOT_ALLOWED
),
692 'sequence' => new external_value(PARAM_INT
, 'sequence', VALUE_DEFAULT
, 1, NULL_NOT_ALLOWED
),
700 * Create calendar events.
702 * @param array $events A list of events to create.
703 * @return array array of events created.
705 * @throws moodle_exception if user doesnt have the permission to create events.
707 public static function create_calendar_events($events) {
710 // Parameter validation.
711 $params = self
::validate_parameters(self
::create_calendar_events_parameters(), array('events' => $events));
713 $transaction = $DB->start_delegated_transaction();
717 foreach ($params['events'] as $event) {
719 // Let us set some defaults.
720 $event['userid'] = $USER->id
;
721 $event['modulename'] = '';
722 $event['instance'] = 0;
723 $event['subscriptionid'] = null;
725 $event['format'] = external_util
::validate_format($event['format']);
726 if ($event['repeats'] > 0) {
727 $event['repeat'] = 1;
729 $event['repeat'] = 0;
732 $eventobj = new calendar_event($event);
734 // Let's check if the user is allowed to delete an event.
735 if (!calendar_add_event_allowed($eventobj)) {
736 $warnings [] = array('item' => $event['name'], 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to create this event');
739 // Let's create the event.
740 $var = $eventobj->create($event);
741 $var = (array)$var->properties();
742 if ($event['repeat']) {
743 $children = $DB->get_records('event', array('repeatid' => $var['id']));
744 foreach ($children as $child) {
745 $return[] = (array) $child;
752 // Everything done smoothly, let's commit.
753 $transaction->allow_commit();
754 return array('events' => $return, 'warnings' => $warnings);
758 * Returns description of method result value.
760 * @return \core_external\external_description.
763 public static function create_calendar_events_returns() {
764 return new external_single_structure(
766 'events' => new external_multiple_structure( new external_single_structure(
768 'id' => new external_value(PARAM_INT
, 'event id'),
769 'name' => new external_value(PARAM_RAW
, 'event name'),
770 'description' => new external_value(PARAM_RAW
, 'Description', VALUE_OPTIONAL
),
771 'format' => new external_format_value('description'),
772 'courseid' => new external_value(PARAM_INT
, 'course id'),
773 'groupid' => new external_value(PARAM_INT
, 'group id'),
774 'userid' => new external_value(PARAM_INT
, 'user id'),
775 'repeatid' => new external_value(PARAM_INT
, 'repeat id', VALUE_OPTIONAL
),
776 'modulename' => new external_value(PARAM_TEXT
, 'module name', VALUE_OPTIONAL
),
777 'instance' => new external_value(PARAM_INT
, 'instance id'),
778 'eventtype' => new external_value(PARAM_TEXT
, 'Event type'),
779 'timestart' => new external_value(PARAM_INT
, 'timestart'),
780 'timeduration' => new external_value(PARAM_INT
, 'time duration'),
781 'visible' => new external_value(PARAM_INT
, 'visible'),
782 'uuid' => new external_value(PARAM_TEXT
, 'unique id of ical events', VALUE_OPTIONAL
, '', NULL_NOT_ALLOWED
),
783 'sequence' => new external_value(PARAM_INT
, 'sequence'),
784 'timemodified' => new external_value(PARAM_INT
, 'time modified'),
785 'subscriptionid' => new external_value(PARAM_INT
, 'Subscription id', VALUE_OPTIONAL
),
788 'warnings' => new external_warnings()
794 * Returns description of method parameters.
796 * @return external_function_parameters
798 public static function get_calendar_event_by_id_parameters() {
799 return new external_function_parameters(
801 'eventid' => new external_value(PARAM_INT
, 'The event id to be retrieved'),
807 * Get calendar event by id.
809 * @param int $eventid The calendar event id to be retrieved.
810 * @return array Array of event details
812 public static function get_calendar_event_by_id($eventid) {
815 $params = self
::validate_parameters(self
::get_calendar_event_by_id_parameters(), ['eventid' => $eventid]);
816 $context = \context_user
::instance($USER->id
);
818 self
::validate_context($context);
821 $eventvault = event_container
::get_event_vault();
822 if ($event = $eventvault->get_event_by_id($params['eventid'])) {
823 $mapper = event_container
::get_event_mapper();
824 if (!calendar_view_event_allowed($mapper->from_event_to_legacy_event($event))) {
825 throw new moodle_exception('nopermissiontoviewcalendar', 'error');
830 // We can't return a warning in this case because the event is not optional.
831 // We don't know the context for the event and it's not worth loading it.
832 $syscontext = context_system
::instance();
833 throw new \required_capability_exception
($syscontext, 'moodle/course:view', 'nopermissions', 'error');
836 $cache = new events_related_objects_cache([$event]);
838 'context' => $cache->get_context($event),
839 'course' => $cache->get_course($event),
842 $exporter = new event_exporter($event, $relatedobjects);
843 $renderer = $PAGE->get_renderer('core_calendar');
845 return array('event' => $exporter->export($renderer), 'warnings' => $warnings);
849 * Returns description of method result value
851 * @return \core_external\external_description
853 public static function get_calendar_event_by_id_returns() {
854 $eventstructure = event_exporter
::get_read_structure();
856 return new external_single_structure(array(
857 'event' => $eventstructure,
858 'warnings' => new external_warnings()
864 * Returns description of method parameters.
866 * @return external_function_parameters.
868 public static function submit_create_update_form_parameters() {
869 return new external_function_parameters(
871 'formdata' => new external_value(PARAM_RAW
, 'The data from the event form'),
877 * Handles the event form submission.
879 * @param string $formdata The event form data in a URI encoded param string
880 * @return array The created or modified event
881 * @throws moodle_exception
883 public static function submit_create_update_form($formdata) {
884 global $USER, $PAGE, $CFG;
885 require_once($CFG->libdir
."/filelib.php");
887 // Parameter validation.
888 $params = self
::validate_parameters(self
::submit_create_update_form_parameters(), ['formdata' => $formdata]);
889 $context = \context_user
::instance($USER->id
);
892 self
::validate_context($context);
893 parse_str($params['formdata'], $data);
896 // Request via WS, ignore sesskey checks in form library.
897 $USER->ignoresesskey
= true;
900 $eventtype = isset($data['eventtype']) ?
$data['eventtype'] : null;
901 $coursekey = ($eventtype == 'group') ?
'groupcourseid' : 'courseid';
902 $courseid = (!empty($data[$coursekey])) ?
$data[$coursekey] : null;
903 $editoroptions = \core_calendar\local\event\forms\create
::build_editor_options($context);
904 $formoptions = ['editoroptions' => $editoroptions, 'courseid' => $courseid];
905 $formoptions['eventtypes'] = calendar_get_allowed_event_types($courseid);
907 require_once($CFG->libdir
. '/grouplib.php');
908 $groupcoursedata = groups_get_course_data($courseid);
909 if (!empty($groupcoursedata->groups
)) {
910 $formoptions['groups'] = [];
911 foreach ($groupcoursedata->groups
as $groupid => $groupdata) {
912 $formoptions['groups'][$groupid] = $groupdata->name
;
917 if (!empty($data['id'])) {
918 $eventid = clean_param($data['id'], PARAM_INT
);
919 $legacyevent = calendar_event
::load($eventid);
920 $legacyevent->count_repeats();
921 $formoptions['event'] = $legacyevent;
922 $mform = new update_event_form(null, $formoptions, 'post', '', null, true, $data);
925 $mform = new create_event_form(null, $formoptions, 'post', '', null, true, $data);
928 if ($validateddata = $mform->get_data()) {
929 $formmapper = new create_update_form_mapper();
930 $properties = $formmapper->from_data_to_event_properties($validateddata);
932 if (is_null($legacyevent)) {
933 $legacyevent = new \
calendar_event($properties);
934 // Need to do this in order to initialise the description
935 // property which then triggers the update function below
936 // to set the appropriate default properties on the event.
937 $properties = $legacyevent->properties(true);
940 if (!calendar_edit_event_allowed($legacyevent, true)) {
941 throw new \
moodle_exception('nopermissiontoupdatecalendar');
944 $legacyevent->update($properties);
945 $eventcontext = $legacyevent->context
;
947 file_remove_editor_orphaned_files($validateddata->description
);
949 // Take any files added to the description draft file area and
950 // convert them into the proper event description file area. Also
951 // parse the description text and replace the URLs to the draft files
952 // with the @@PLUGIN_FILE@@ placeholder to be persisted in the DB.
953 $description = file_save_draft_area_files(
954 $validateddata->description
['itemid'],
959 create_event_form
::build_editor_options($eventcontext),
960 $validateddata->description
['text']
963 // If draft files were found then we need to save the new
964 // description value.
965 if ($description != $validateddata->description
['text']) {
966 $properties->id
= $legacyevent->id
;
967 $properties->description
= $description;
968 $legacyevent->update($properties);
971 $eventmapper = event_container
::get_event_mapper();
972 $event = $eventmapper->from_legacy_event_to_event($legacyevent);
973 $cache = new events_related_objects_cache([$event]);
975 'context' => $cache->get_context($event),
976 'course' => $cache->get_course($event),
978 $exporter = new event_exporter($event, $relatedobjects);
979 $renderer = $PAGE->get_renderer('core_calendar');
981 return [ 'event' => $exporter->export($renderer) ];
983 return [ 'validationerror' => true ];
988 * Returns description of method result value.
990 * @return \core_external\external_description.
992 public static function submit_create_update_form_returns() {
993 $eventstructure = event_exporter
::get_read_structure();
994 $eventstructure->required
= VALUE_OPTIONAL
;
996 return new external_single_structure(
998 'event' => $eventstructure,
999 'validationerror' => new external_value(PARAM_BOOL
, 'Invalid form data', VALUE_DEFAULT
, false),
1005 * Get data for the monthly calendar view.
1007 * @param int $year The year to be shown
1008 * @param int $month The month to be shown
1009 * @param int $courseid The course to be included
1010 * @param int $categoryid The category to be included
1011 * @param bool $includenavigation Whether to include navigation
1012 * @param bool $mini Whether to return the mini month view or not
1013 * @param int $day The day we want to keep as the current day
1014 * @param string|null $view The view mode for the calendar.
1017 public static function get_calendar_monthly_view($year, $month, $courseid, $categoryid, $includenavigation, $mini, $day,
1018 ?
string $view = null) {
1019 global $USER, $PAGE;
1021 // Parameter validation.
1022 $params = self
::validate_parameters(self
::get_calendar_monthly_view_parameters(), [
1025 'courseid' => $courseid,
1026 'categoryid' => $categoryid,
1027 'includenavigation' => $includenavigation,
1033 $context = \context_user
::instance($USER->id
);
1034 self
::validate_context($context);
1035 $PAGE->set_url('/calendar/');
1037 $type = \core_calendar\type_factory
::get_calendar_instance();
1039 $time = $type->convert_to_timestamp($params['year'], $params['month'], $params['day']);
1040 $calendar = \calendar_information
::create($time, $params['courseid'], $params['categoryid']);
1041 self
::validate_context($calendar->context
);
1043 $view = $params['view'] ??
($params['mini'] ?
'mini' : 'month');
1044 list($data, $template) = calendar_get_view($calendar, $view, $params['includenavigation']);
1050 * Returns description of method parameters.
1052 * @return external_function_parameters
1054 public static function get_calendar_monthly_view_parameters() {
1055 return new external_function_parameters(
1057 'year' => new external_value(PARAM_INT
, 'Year to be viewed', VALUE_REQUIRED
),
1058 'month' => new external_value(PARAM_INT
, 'Month to be viewed', VALUE_REQUIRED
),
1059 'courseid' => new external_value(PARAM_INT
, 'Course being viewed', VALUE_DEFAULT
, SITEID
, NULL_ALLOWED
),
1060 'categoryid' => new external_value(PARAM_INT
, 'Category being viewed', VALUE_DEFAULT
, null, NULL_ALLOWED
),
1061 'includenavigation' => new external_value(
1063 'Whether to show course navigation',
1068 'mini' => new external_value(
1070 'Whether to return the mini month view or not',
1075 'day' => new external_value(PARAM_INT
, 'Day to be viewed', VALUE_DEFAULT
, 1),
1076 'view' => new external_value(PARAM_ALPHA
, 'The view mode of the calendar', VALUE_DEFAULT
, 'month', NULL_ALLOWED
),
1082 * Returns description of method result value.
1084 * @return \core_external\external_description
1086 public static function get_calendar_monthly_view_returns() {
1087 return \core_calendar\external\month_exporter
::get_read_structure();
1091 * Get data for the daily calendar view.
1093 * @param int $year The year to be shown
1094 * @param int $month The month to be shown
1095 * @param int $day The day to be shown
1096 * @param int $courseid The course to be included
1099 public static function get_calendar_day_view($year, $month, $day, $courseid, $categoryid) {
1100 global $DB, $USER, $PAGE;
1102 // Parameter validation.
1103 $params = self
::validate_parameters(self
::get_calendar_day_view_parameters(), [
1107 'courseid' => $courseid,
1108 'categoryid' => $categoryid,
1111 $context = \context_user
::instance($USER->id
);
1112 self
::validate_context($context);
1114 $type = \core_calendar\type_factory
::get_calendar_instance();
1116 $time = $type->convert_to_timestamp($params['year'], $params['month'], $params['day']);
1117 $calendar = \calendar_information
::create($time, $params['courseid'], $params['categoryid']);
1118 self
::validate_context($calendar->context
);
1120 list($data, $template) = calendar_get_view($calendar, 'day');
1126 * Returns description of method parameters.
1128 * @return external_function_parameters
1130 public static function get_calendar_day_view_parameters() {
1131 return new external_function_parameters(
1133 'year' => new external_value(PARAM_INT
, 'Year to be viewed', VALUE_REQUIRED
),
1134 'month' => new external_value(PARAM_INT
, 'Month to be viewed', VALUE_REQUIRED
),
1135 'day' => new external_value(PARAM_INT
, 'Day to be viewed', VALUE_REQUIRED
),
1136 'courseid' => new external_value(PARAM_INT
, 'Course being viewed', VALUE_DEFAULT
, SITEID
, NULL_ALLOWED
),
1137 'categoryid' => new external_value(PARAM_INT
, 'Category being viewed', VALUE_DEFAULT
, null, NULL_ALLOWED
),
1143 * Returns description of method result value.
1145 * @return \core_external\external_description
1147 public static function get_calendar_day_view_returns() {
1148 return \core_calendar\external\calendar_day_exporter
::get_read_structure();
1153 * Returns description of method parameters.
1155 * @return external_function_parameters
1157 public static function update_event_start_day_parameters() {
1158 return new external_function_parameters(
1160 'eventid' => new external_value(PARAM_INT
, 'Id of event to be updated', VALUE_REQUIRED
),
1161 'daytimestamp' => new external_value(PARAM_INT
, 'Timestamp for the new start day', VALUE_REQUIRED
),
1167 * Change the start day for the given calendar event to the day that
1168 * corresponds with the provided timestamp.
1170 * The timestamp only needs to be anytime within the desired day as only
1171 * the date data is extracted from it.
1173 * The event's original time of day is maintained, only the date is shifted.
1175 * @param int $eventid Id of event to be updated
1176 * @param int $daytimestamp Timestamp for the new start day
1179 public static function update_event_start_day($eventid, $daytimestamp) {
1180 global $USER, $PAGE;
1182 // Parameter validation.
1183 $params = self
::validate_parameters(self
::update_event_start_day_parameters(), [
1184 'eventid' => $eventid,
1185 'daytimestamp' => $daytimestamp,
1188 $vault = event_container
::get_event_vault();
1189 $mapper = event_container
::get_event_mapper();
1190 $event = $vault->get_event_by_id($eventid);
1193 throw new \
moodle_exception('Unable to find event with id ' . $eventid);
1196 $legacyevent = $mapper->from_event_to_legacy_event($event);
1198 if (!calendar_edit_event_allowed($legacyevent, true)) {
1199 throw new \
moodle_exception('nopermissiontoupdatecalendar');
1202 self
::validate_context($legacyevent->context
);
1204 $newdate = usergetdate($daytimestamp);
1205 $startdatestring = implode('-', [$newdate['year'], $newdate['mon'], $newdate['mday']]);
1206 $startdate = new DateTimeImmutable($startdatestring);
1207 $event = local_api
::update_event_start_day($event, $startdate);
1208 $cache = new events_related_objects_cache([$event]);
1210 'context' => $cache->get_context($event),
1211 'course' => $cache->get_course($event),
1213 $exporter = new event_exporter($event, $relatedobjects);
1214 $renderer = $PAGE->get_renderer('core_calendar');
1216 return array('event' => $exporter->export($renderer));
1220 * Returns description of method result value.
1222 * @return \core_external\external_description
1224 public static function update_event_start_day_returns() {
1225 return new external_single_structure(
1227 'event' => event_exporter
::get_read_structure()
1233 * Get data for the monthly calendar view.
1235 * @param int $courseid The course to be included
1236 * @param int $categoryid The category to be included
1239 public static function get_calendar_upcoming_view($courseid, $categoryid) {
1240 global $DB, $USER, $PAGE;
1242 // Parameter validation.
1243 $params = self
::validate_parameters(self
::get_calendar_upcoming_view_parameters(), [
1244 'courseid' => $courseid,
1245 'categoryid' => $categoryid,
1248 $context = \context_user
::instance($USER->id
);
1249 self
::validate_context($context);
1250 $PAGE->set_url('/calendar/');
1252 $calendar = \calendar_information
::create(time(), $params['courseid'], $params['categoryid']);
1253 self
::validate_context($calendar->context
);
1255 list($data, $template) = calendar_get_view($calendar, 'upcoming');
1261 * Returns description of method parameters.
1263 * @return external_function_parameters
1265 public static function get_calendar_upcoming_view_parameters() {
1266 return new external_function_parameters(
1268 'courseid' => new external_value(PARAM_INT
, 'Course being viewed', VALUE_DEFAULT
, SITEID
, NULL_ALLOWED
),
1269 'categoryid' => new external_value(PARAM_INT
, 'Category being viewed', VALUE_DEFAULT
, null, NULL_ALLOWED
),
1275 * Returns description of method result value.
1277 * @return \core_external\external_description
1279 public static function get_calendar_upcoming_view_returns() {
1280 return \core_calendar\external\calendar_upcoming_exporter
::get_read_structure();
1285 * Returns description of method parameters.
1287 * @return external_function_parameters.
1290 public static function get_calendar_access_information_parameters() {
1291 return new external_function_parameters(
1293 'courseid' => new external_value(PARAM_INT
, 'Course to check, empty for site calendar events.', VALUE_DEFAULT
, 0),
1299 * Convenience function to retrieve some permissions information for the given course calendar.
1301 * @param int $courseid Course to check, empty for site.
1302 * @return array The access information
1303 * @throws moodle_exception
1306 public static function get_calendar_access_information($courseid = 0) {
1308 $params = self
::validate_parameters(self
::get_calendar_access_information_parameters(), ['courseid' => $courseid]);
1310 if (empty($params['courseid']) ||
$params['courseid'] == SITEID
) {
1311 $context = \context_system
::instance();
1313 $context = \context_course
::instance($params['courseid']);
1316 self
::validate_context($context);
1319 'canmanageentries' => has_capability('moodle/calendar:manageentries', $context),
1320 'canmanageownentries' => has_capability('moodle/calendar:manageownentries', $context),
1321 'canmanagegroupentries' => has_capability('moodle/calendar:managegroupentries', $context),
1327 * Returns description of method result value.
1329 * @return \core_external\external_description.
1332 public static function get_calendar_access_information_returns() {
1334 return new external_single_structure(
1336 'canmanageentries' => new external_value(PARAM_BOOL
, 'Whether the user can manage entries.'),
1337 'canmanageownentries' => new external_value(PARAM_BOOL
, 'Whether the user can manage its own entries.'),
1338 'canmanagegroupentries' => new external_value(PARAM_BOOL
, 'Whether the user can manage group entries.'),
1339 'warnings' => new external_warnings(),
1345 * Returns description of method parameters.
1347 * @return external_function_parameters.
1350 public static function get_allowed_event_types_parameters() {
1351 return new external_function_parameters(
1353 'courseid' => new external_value(PARAM_INT
, 'Course to check, empty for site.', VALUE_DEFAULT
, 0),
1359 * Get the type of events a user can create in the given course.
1361 * @param int $courseid Course to check, empty for site.
1362 * @return array The types allowed
1363 * @throws moodle_exception
1366 public static function get_allowed_event_types($courseid = 0) {
1368 $params = self
::validate_parameters(self
::get_allowed_event_types_parameters(), ['courseid' => $courseid]);
1370 if (empty($params['courseid']) ||
$params['courseid'] == SITEID
) {
1371 $context = \context_system
::instance();
1373 $context = \context_course
::instance($params['courseid']);
1376 self
::validate_context($context);
1378 $allowedeventtypes = array_filter(calendar_get_allowed_event_types($params['courseid']));
1381 'allowedeventtypes' => array_keys($allowedeventtypes),
1387 * Returns description of method result value.
1389 * @return \core_external\external_description.
1392 public static function get_allowed_event_types_returns() {
1394 return new external_single_structure(
1396 'allowedeventtypes' => new external_multiple_structure(
1397 new external_value(PARAM_NOTAGS
, 'Allowed event types to be created in the given course.')
1399 'warnings' => new external_warnings(),
1405 * Convert the specified dates into unix timestamps.
1407 * @param array $datetimes Array of arrays containing date time details, each in the format:
1408 * ['year' => a, 'month' => b, 'day' => c,
1409 * 'hour' => d (optional), 'minute' => e (optional), 'key' => 'x' (optional)]
1410 * @return array Provided array of dates converted to unix timestamps
1411 * @throws moodle_exception If one or more of the dates provided does not convert to a valid timestamp.
1413 public static function get_timestamps($datetimes) {
1414 $params = self
::validate_parameters(self
::get_timestamps_parameters(), ['data' => $datetimes]);
1416 $type = \core_calendar\type_factory
::get_calendar_instance();
1417 $timestamps = ['timestamps' => []];
1419 foreach ($params['data'] as $key => $datetime) {
1420 $hour = $datetime['hour'] ??
0;
1421 $minute = $datetime['minute'] ??
0;
1424 $timestamp = $type->convert_to_timestamp(
1425 $datetime['year'], $datetime['month'], $datetime['day'], $hour, $minute);
1427 $timestamps['timestamps'][] = [
1428 'key' => $datetime['key'] ??
$key,
1429 'timestamp' => $timestamp,
1432 } catch (Exception
$e) {
1433 throw new moodle_exception('One or more of the dates provided were invalid');
1441 * Describes the parameters for get_timestamps.
1443 * @return external_function_parameters
1445 public static function get_timestamps_parameters() {
1446 return new external_function_parameters ([
1447 'data' => new external_multiple_structure(
1448 new external_single_structure(
1450 'key' => new external_value(PARAM_ALPHANUMEXT
, 'key', VALUE_OPTIONAL
),
1451 'year' => new external_value(PARAM_INT
, 'year'),
1452 'month' => new external_value(PARAM_INT
, 'month'),
1453 'day' => new external_value(PARAM_INT
, 'day'),
1454 'hour' => new external_value(PARAM_INT
, 'hour', VALUE_OPTIONAL
),
1455 'minute' => new external_value(PARAM_INT
, 'minute', VALUE_OPTIONAL
),
1463 * Describes the timestamps return format.
1465 * @return external_single_structure
1467 public static function get_timestamps_returns() {
1468 return new external_single_structure(
1470 'timestamps' => new external_multiple_structure(
1471 new external_single_structure(
1473 'key' => new external_value(PARAM_ALPHANUMEXT
, 'Timestamp key'),
1474 'timestamp' => new external_value(PARAM_INT
, 'Unix timestamp'),