MDL-64641 calendar: New WS core_calendar_get_allowed_event_types
[moodle.git] / calendar / externallib.php
CommitLineData
01bea07d
AA
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
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/>.
16
17
18/**
19 * External calendar API
20 *
21 * @package core_calendar
22 * @category external
23 * @copyright 2012 Ankit Agarwal
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 * @since Moodle 2.5
26 */
27
28defined('MOODLE_INTERNAL') || die;
29
30require_once("$CFG->libdir/externallib.php");
2aad6b82 31require_once($CFG->dirroot . '/calendar/lib.php');
01bea07d 32
c0f877fa 33use \core_calendar\local\api as local_api;
aa091225
RW
34use \core_calendar\local\event\container as event_container;
35use \core_calendar\local\event\forms\create as create_event_form;
36use \core_calendar\local\event\forms\update as update_event_form;
37use \core_calendar\local\event\mappers\create_update_form_mapper;
38use \core_calendar\external\event_exporter;
c0f877fa 39use \core_calendar\external\events_exporter;
60774b28 40use \core_calendar\external\events_grouped_by_course_exporter;
c0f877fa
MN
41use \core_calendar\external\events_related_objects_cache;
42
01bea07d
AA
43/**
44 * Calendar external functions
45 *
46 * @package core_calendar
47 * @category external
48 * @copyright 2012 Ankit Agarwal
49 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
50 * @since Moodle 2.5
51 */
52class core_calendar_external extends external_api {
53
54
55 /**
56 * Returns description of method parameters
57 *
58 * @return external_function_parameters
59 * @since Moodle 2.5
60 */
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(
65 array(
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'
69 )
70 )
71 )
72 );
73 }
74
75 /**
76 * Delete Calendar events
77 *
78 * @param array $eventids A list of event ids with repeat flag to delete
79 * @return null
80 * @since Moodle 2.5
81 */
82 public static function delete_calendar_events($events) {
2aad6b82 83 global $DB;
01bea07d
AA
84
85 // Parameter validation.
86 $params = self::validate_parameters(self:: delete_calendar_events_parameters(), array('events' => $events));
87
88 $transaction = $DB->start_delegated_transaction();
89
90 foreach ($params['events'] as $event) {
e1cd93ce 91 $eventobj = calendar_event::load($event['eventid']);
01bea07d
AA
92
93 // Let's check if the user is allowed to delete an event.
436d39ba
SL
94 if (!calendar_delete_event_allowed($eventobj)) {
95 throw new moodle_exception('nopermissions', 'error', '', get_string('deleteevent', 'calendar'));
01bea07d
AA
96 }
97 // Time to do the magic.
98 $eventobj->delete($event['repeat']);
99 }
100
101 // Everything done smoothly, let's commit.
102 $transaction->allow_commit();
103
104 return null;
105 }
106
107 /**
108 * Returns description of method result value
109 *
110 * @return external_description
111 * @since Moodle 2.5
112 */
113 public static function delete_calendar_events_returns() {
114 return null;
115 }
475896bd
AA
116
117 /**
118 * Returns description of method parameters
119 *
120 * @return external_function_parameters
121 * @since Moodle 2.5
122 */
123 public static function get_calendar_events_parameters() {
124 return new external_function_parameters(
125 array('events' => new external_single_structure(
126 array(
127 'eventids' => new external_multiple_structure(
128 new external_value(PARAM_INT, 'event ids')
129 , 'List of event ids',
7e781cfc 130 VALUE_DEFAULT, array()),
475896bd
AA
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',
7e781cfc 134 VALUE_DEFAULT, array()),
475896bd
AA
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',
7e781cfc 138 VALUE_DEFAULT, array()),
10c17dcc
SL
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',
7e781cfc 142 VALUE_DEFAULT, array()),
475896bd
AA
143 ), 'Event details', VALUE_DEFAULT, array()),
144 'options' => new external_single_structure(
145 array(
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 global 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,
e07e04c1
DM
156 "Time to which the events should be returned. We treat 0 and null as no end",
157 VALUE_DEFAULT, 0, NULL_ALLOWED),
475896bd
AA
158 'ignorehidden' => new external_value(PARAM_BOOL,
159 "Ignore hidden events or not",
160 VALUE_DEFAULT, true, NULL_ALLOWED),
161
162 ), 'Options', VALUE_DEFAULT, array())
163 )
164 );
165 }
166
167 /**
168 * Get Calendar events
475896bd
AA
169 *
170 * @param array $events A list of events
e5adc5a1 171 * @param array $options various options
475896bd
AA
172 * @return array Array of event details
173 * @since Moodle 2.5
174 */
175 public static function get_calendar_events($events = array(), $options = array()) {
2aad6b82 176 global $SITE, $DB, $USER;
475896bd
AA
177
178 // Parameter validation.
e6a1f8c1 179 $params = self::validate_parameters(self::get_calendar_events_parameters(), array('events' => $events, 'options' => $options));
10c17dcc 180 $funcparam = array('courses' => array(), 'groups' => array(), 'categories' => array());
475896bd 181 $hassystemcap = has_capability('moodle/calendar:manageentries', context_system::instance());
e6a1f8c1 182 $warnings = array();
c4172077 183 $coursecategories = array();
475896bd 184
c4172077 185 // Let us find out courses and their categories that we can return events from.
475896bd 186 if (!$hassystemcap) {
c4172077
MG
187 $courseobjs = enrol_get_my_courses();
188 $courses = array_keys($courseobjs);
189
190 $coursecategories = array_flip(array_map(function($course) {
191 return $course->category;
192 }, $courseobjs));
193
e6a1f8c1 194 foreach ($params['events']['courseids'] as $id) {
76aea854
SL
195 try {
196 $context = context_course::instance($id);
197 self::validate_context($context);
e6a1f8c1 198 $funcparam['courses'][] = $id;
76aea854
SL
199 } catch (Exception $e) {
200 $warnings[] = array(
201 'item' => 'course',
202 'itemid' => $id,
203 'warningcode' => 'nopermissions',
204 'message' => 'No access rights in course context '.$e->getMessage().$e->getTraceAsString()
205 );
e6a1f8c1
AA
206 }
207 }
475896bd
AA
208 } else {
209 $courses = $params['events']['courseids'];
210 $funcparam['courses'] = $courses;
c4172077
MG
211
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')));
218 }
475896bd
AA
219 }
220
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);
e6a1f8c1
AA
225 foreach ($params['events']['groupids'] as $id) {
226 if (in_array($id, $groups)) {
227 $funcparam['groups'][] = $id;
228 } else {
38e4fa58 229 $warnings[] = array('item' => $id, 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to access this group');
e6a1f8c1
AA
230 }
231 }
475896bd
AA
232 } else {
233 $groups = $params['events']['groupids'];
234 $funcparam['groups'] = $groups;
235 }
236
10c17dcc 237 $categories = array();
44ae0838 238 if ($hassystemcap || !empty($courses)) {
c4172077
MG
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.
241 $categories = [];
242
243 if (!empty($params['events']['categoryids'])) {
442f12f8
MG
244 $catobjs = \core_course_category::get_many(
245 array_merge($params['events']['categoryids'], array_keys($coursecategories)));
c4172077
MG
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;
44ae0838 254 }
10c17dcc
SL
255 }
256 }
c4172077
MG
257 $funcparam['categories'] = array_keys($categories);
258 } else {
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);
268 } else {
269 $categories = [];
442f12f8 270 foreach (\core_course_category::get_all() as $category) {
c4172077
MG
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;
278 }
10c17dcc
SL
279 }
280 }
c4172077
MG
281 $funcparam['categories'] = array_keys($categories);
282 if (!$hassystemcap) {
283 $calcatcache->set('site', $funcparam['categories']);
284 }
10c17dcc
SL
285 }
286 }
10c17dcc
SL
287 }
288
475896bd
AA
289 // Do we need user events?
290 if (!empty($params['options']['userevents'])) {
291 $funcparam['users'] = array($USER->id);
292 } else {
293 $funcparam['users'] = false;
294 }
295
296 // Do we need site events?
297 if (!empty($params['options']['siteevents'])) {
298 $funcparam['courses'][] = $SITE->id;
299 }
300
e07e04c1
DM
301 // We treat 0 and null as no end.
302 if (empty($params['options']['timeend'])) {
303 $params['options']['timeend'] = PHP_INT_MAX;
304 }
305
39b85137 306 // Event list does not check visibility and permissions, we'll check that later.
22753c8c 307 $eventlist = calendar_get_legacy_events($params['options']['timestart'], $params['options']['timeend'],
10c17dcc
SL
308 $funcparam['users'], $funcparam['groups'], $funcparam['courses'], true,
309 $params['options']['ignorehidden'], $funcparam['categories']);
39b85137 310
7c30224a
AA
311 // WS expects arrays.
312 $events = array();
475896bd
AA
313
314 // We need to get events asked for eventids.
23a29de7 315 if ($eventsbyid = calendar_get_events_by_id($params['events']['eventids'])) {
39b85137
JL
316 $eventlist += $eventsbyid;
317 }
39b85137 318 foreach ($eventlist as $eventid => $eventobj) {
7c30224a 319 $event = (array) $eventobj;
871988b0 320 // Description formatting.
e1cd93ce 321 $calendareventobj = new calendar_event($event);
871988b0 322 list($event['description'], $event['format']) = $calendareventobj->format_external_text();
39b85137 323
475896bd
AA
324 if ($hassystemcap) {
325 // User can see everything, no further check is needed.
7c30224a
AA
326 $events[$eventid] = $event;
327 } else if (!empty($eventobj->modulename)) {
5900513f
MG
328 $courseid = $eventobj->courseid;
329 if (!$courseid) {
330 if (!$calendareventobj->context || !($context = $calendareventobj->context->get_course_context(false))) {
331 continue;
332 }
333 $courseid = $context->instanceid;
334 }
335 $instances = get_fast_modinfo($courseid)->get_instances_of($eventobj->modulename);
336 if (!empty($instances[$eventobj->instance]->uservisible)) {
7c30224a 337 $events[$eventid] = $event;
475896bd
AA
338 }
339 } else {
340 // Can the user actually see this event?
e1cd93ce 341 $eventobj = calendar_event::load($eventobj);
af25b8fc 342 if ((($eventobj->courseid == $SITE->id) && (empty($eventobj->categoryid))) ||
c4172077 343 (!empty($eventobj->categoryid) && isset($categories[$eventobj->categoryid])) ||
e6a1f8c1
AA
344 (!empty($eventobj->groupid) && in_array($eventobj->groupid, $groups)) ||
345 (!empty($eventobj->courseid) && in_array($eventobj->courseid, $courses)) ||
346 ($USER->id == $eventobj->userid) ||
86679cb1 347 (calendar_edit_event_allowed($eventobj))) {
7c30224a 348 $events[$eventid] = $event;
e6a1f8c1 349 } else {
38e4fa58 350 $warnings[] = array('item' => $eventid, 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to view this event');
475896bd
AA
351 }
352 }
353 }
e6a1f8c1 354 return array('events' => $events, 'warnings' => $warnings);
475896bd
AA
355 }
356
357 /**
358 * Returns description of method result value
359 *
360 * @return external_description
361 * @since Moodle 2.5
362 */
363 public static function get_calendar_events_returns() {
e6a1f8c1
AA
364 return new external_single_structure(array(
365 'events' => new external_multiple_structure( new external_single_structure(
475896bd
AA
366 array(
367 'id' => new external_value(PARAM_INT, 'event id'),
368 'name' => new external_value(PARAM_TEXT, 'event name'),
e6a1f8c1 369 'description' => new external_value(PARAM_RAW, 'Description', VALUE_OPTIONAL, null, NULL_ALLOWED),
475896bd
AA
370 'format' => new external_format_value('description'),
371 'courseid' => new external_value(PARAM_INT, 'course id'),
e3c04bd9
JL
372 'categoryid' => new external_value(PARAM_INT, 'Category id (only for category events).',
373 VALUE_OPTIONAL),
475896bd
AA
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'),
e6a1f8c1 377 'modulename' => new external_value(PARAM_TEXT, 'module name', VALUE_OPTIONAL, null, NULL_ALLOWED),
475896bd
AA
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'),
e6a1f8c1 383 'uuid' => new external_value(PARAM_TEXT, 'unique id of ical events', VALUE_OPTIONAL, null, NULL_NOT_ALLOWED),
475896bd
AA
384 'sequence' => new external_value(PARAM_INT, 'sequence'),
385 'timemodified' => new external_value(PARAM_INT, 'time modified'),
e6a1f8c1
AA
386 'subscriptionid' => new external_value(PARAM_INT, 'Subscription id', VALUE_OPTIONAL, null, NULL_ALLOWED),
387 ), 'event')
388 ),
389 'warnings' => new external_warnings()
475896bd
AA
390 )
391 );
392 }
494a6389 393
c0f877fa
MN
394 /**
395 * Returns description of method parameters.
396 *
397 * @since Moodle 3.3
398 * @return external_function_parameters
399 */
400 public static function get_calendar_action_events_by_timesort_parameters() {
401 return new external_function_parameters(
402 array(
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),
644ffbd3
AG
406 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 20),
407 'limittononsuspendedevents' => new external_value(PARAM_BOOL,
7af6528e
DM
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),
c0f877fa
MN
410 )
411 );
412 }
413
414 /**
415 * Get calendar action events based on the timesort value.
416 *
417 * @since Moodle 3.3
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
7af6528e 422 * @param null|int $userid The user id
c0f877fa
MN
423 * @return array
424 */
425 public static function get_calendar_action_events_by_timesort($timesortfrom = 0, $timesortto = null,
7af6528e
DM
426 $aftereventid = 0, $limitnum = 20, $limittononsuspendedevents = false,
427 $userid = null) {
2aad6b82 428 global $PAGE, $USER;
c0f877fa 429
c0f877fa
MN
430 $params = self::validate_parameters(
431 self::get_calendar_action_events_by_timesort_parameters(),
432 [
433 'timesortfrom' => $timesortfrom,
434 'timesortto' => $timesortto,
435 'aftereventid' => $aftereventid,
436 'limitnum' => $limitnum,
7af6528e
DM
437 'limittononsuspendedevents' => $limittononsuspendedevents,
438 'userid' => $userid,
c0f877fa
MN
439 ]
440 );
7af6528e
DM
441 if ($params['userid']) {
442 $user = \core_user::get_user($params['userid']);
443 } else {
444 $user = $USER;
445 }
446
447 $context = \context_user::instance($user->id);
c0f877fa
MN
448 self::validate_context($context);
449
450 if (empty($params['aftereventid'])) {
451 $params['aftereventid'] = null;
452 }
453
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'],
644ffbd3 459 $params['limitnum'],
7af6528e
DM
460 $params['limittononsuspendedevents'],
461 $user
c0f877fa
MN
462 );
463
464 $exportercache = new events_related_objects_cache($events);
465 $exporter = new events_exporter($events, ['cache' => $exportercache]);
466
467 return $exporter->export($renderer);
468 }
469
470 /**
471 * Returns description of method result value.
472 *
473 * @since Moodle 3.3
474 * @return external_description
475 */
476 public static function get_calendar_action_events_by_timesort_returns() {
477 return events_exporter::get_read_structure();
478 }
479
60774b28
RW
480 /**
481 * Returns description of method parameters.
482 *
483 * @return external_function_parameters
484 */
485 public static function get_calendar_action_events_by_course_parameters() {
486 return new external_function_parameters(
487 array(
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)
493 )
494 );
495 }
496
497 /**
498 * Get calendar action events for the given course.
499 *
500 * @since Moodle 3.3
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
506 * @return array
507 */
508 public static function get_calendar_action_events_by_course(
509 $courseid, $timesortfrom = null, $timesortto = null, $aftereventid = 0, $limitnum = 20) {
510
2aad6b82 511 global $PAGE, $USER;
60774b28
RW
512
513 $user = null;
514 $params = self::validate_parameters(
515 self::get_calendar_action_events_by_course_parameters(),
516 [
517 'courseid' => $courseid,
518 'timesortfrom' => $timesortfrom,
519 'timesortto' => $timesortto,
520 'aftereventid' => $aftereventid,
521 'limitnum' => $limitnum,
522 ]
523 );
524 $context = \context_user::instance($USER->id);
525 self::validate_context($context);
526
527 if (empty($params['aftereventid'])) {
528 $params['aftereventid'] = null;
529 }
530
04985346 531 $courses = enrol_get_my_courses('*', null, 0, [$courseid]);
60774b28
RW
532 $courses = array_values($courses);
533
534 if (empty($courses)) {
535 return [];
536 }
537
538 $course = $courses[0];
539 $renderer = $PAGE->get_renderer('core_calendar');
540 $events = local_api::get_action_events_by_course(
541 $course,
542 $params['timesortfrom'],
543 $params['timesortto'],
544 $params['aftereventid'],
545 $params['limitnum']
546 );
547
548 $exportercache = new events_related_objects_cache($events, $courses);
549 $exporter = new events_exporter($events, ['cache' => $exportercache]);
550
551 return $exporter->export($renderer);
552 }
553
554 /**
555 * Returns description of method result value.
556 *
557 * @return external_description
558 */
559 public static function get_calendar_action_events_by_course_returns() {
560 return events_exporter::get_read_structure();
561 }
562
9b8e5057
RW
563 /**
564 * Returns description of method parameters.
565 *
566 * @return external_function_parameters
567 */
568 public static function get_calendar_action_events_by_courses_parameters() {
569 return new external_function_parameters(
570 array(
571 'courseids' => new external_multiple_structure(
572 new external_value(PARAM_INT, 'Course id')
573 ),
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)
577 )
578 );
579 }
580
581 /**
582 * Get calendar action events for a given list of courses.
583 *
584 * @since Moodle 3.3
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
589 * @return array
590 */
591 public static function get_calendar_action_events_by_courses(
592 array $courseids, $timesortfrom = null, $timesortto = null, $limitnum = 10) {
593
2aad6b82 594 global $PAGE, $USER;
9b8e5057
RW
595
596 $user = null;
597 $params = self::validate_parameters(
598 self::get_calendar_action_events_by_courses_parameters(),
599 [
600 'courseids' => $courseids,
601 'timesortfrom' => $timesortfrom,
602 'timesortto' => $timesortto,
603 'limitnum' => $limitnum,
604 ]
605 );
606 $context = \context_user::instance($USER->id);
607 self::validate_context($context);
608
609 if (empty($params['courseids'])) {
610 return ['groupedbycourse' => []];
611 }
612
613 $renderer = $PAGE->get_renderer('core_calendar');
04985346 614 $courses = enrol_get_my_courses('*', null, 0, $params['courseids']);
9b8e5057
RW
615 $courses = array_values($courses);
616
617 if (empty($courses)) {
618 return ['groupedbycourse' => []];
619 }
620
621 $events = local_api::get_action_events_by_courses(
622 $courses,
623 $params['timesortfrom'],
624 $params['timesortto'],
625 $params['limitnum']
626 );
627
628 if (empty($events)) {
629 return ['groupedbycourse' => []];
630 }
631
632 $exportercache = new events_related_objects_cache($events, $courses);
633 $exporter = new events_grouped_by_course_exporter($events, ['cache' => $exportercache]);
634
635 return $exporter->export($renderer);
636 }
637
638 /**
639 * Returns description of method result value.
640 *
641 * @return external_description
642 */
643 public static function get_calendar_action_events_by_courses_returns() {
644 return events_grouped_by_course_exporter::get_read_structure();
645 }
646
494a6389
AA
647 /**
648 * Returns description of method parameters.
649 *
650 * @return external_function_parameters.
651 * @since Moodle 2.5
652 */
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(
660 array(
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),
672 ), 'event')
673 )
674 )
675 );
676 }
677
678 /**
679 * Delete Calendar events.
680 *
681 * @param array $events A list of events to create.
682 * @return array array of events created.
683 * @since Moodle 2.5
684 * @throws moodle_exception if user doesnt have the permission to create events.
685 */
686 public static function create_calendar_events($events) {
2aad6b82 687 global $DB, $USER;
494a6389
AA
688
689 // Parameter validation.
690 $params = self::validate_parameters(self::create_calendar_events_parameters(), array('events' => $events));
691
692 $transaction = $DB->start_delegated_transaction();
693 $return = array();
694 $warnings = array();
695
696 foreach ($params['events'] as $event) {
697
698 // Let us set some defaults.
699 $event['userid'] = $USER->id;
700 $event['modulename'] = '';
701 $event['instance'] = 0;
702 $event['subscriptionid'] = null;
703 $event['uuid']= '';
704 $event['format'] = external_validate_format($event['format']);
705 if ($event['repeats'] > 0) {
706 $event['repeat'] = 1;
707 } else {
708 $event['repeat'] = 0;
709 }
710
e1cd93ce 711 $eventobj = new calendar_event($event);
494a6389
AA
712
713 // Let's check if the user is allowed to delete an event.
23a29de7 714 if (!calendar_add_event_allowed($eventobj)) {
38e4fa58 715 $warnings [] = array('item' => $event['name'], 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to create this event');
494a6389
AA
716 continue;
717 }
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;
725 }
726 } else {
727 $return[] = $var;
728 }
729 }
730
731 // Everything done smoothly, let's commit.
732 $transaction->allow_commit();
733 return array('events' => $return, 'warnings' => $warnings);
734 }
735
736 /**
737 * Returns description of method result value.
738 *
739 * @return external_description.
740 * @since Moodle 2.5
741 */
742 public static function create_calendar_events_returns() {
743 return new external_single_structure(
744 array(
745 'events' => new external_multiple_structure( new external_single_structure(
746 array(
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),
765 ), 'event')
766 ),
767 'warnings' => new external_warnings()
768 )
769 );
770 }
5813d1b9
SL
771
772 /**
773 * Returns description of method parameters.
774 *
775 * @return external_function_parameters
776 */
777 public static function get_calendar_event_by_id_parameters() {
778 return new external_function_parameters(
779 array(
780 'eventid' => new external_value(PARAM_INT, 'The event id to be retrieved'),
781 )
782 );
783 }
695c5726 784
5813d1b9
SL
785 /**
786 * Get calendar event by id.
787 *
788 * @param int $eventid The calendar event id to be retrieved.
789 * @return array Array of event details
790 */
791 public static function get_calendar_event_by_id($eventid) {
2aad6b82 792 global $PAGE, $USER;
5813d1b9 793
e20752c4 794 $params = self::validate_parameters(self::get_calendar_event_by_id_parameters(), ['eventid' => $eventid]);
6fb75156 795 $context = \context_user::instance($USER->id);
5813d1b9 796
6fb75156 797 self::validate_context($context);
5813d1b9
SL
798 $warnings = array();
799
6fb75156 800 $legacyevent = calendar_event::load($eventid);
af25b8fc
DW
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', '');
807 }
808
6fb75156
SL
809 $legacyevent->count_repeats();
810
811 $eventmapper = event_container::get_event_mapper();
812 $event = $eventmapper->from_legacy_event_to_event($legacyevent);
813
814 $cache = new events_related_objects_cache([$event]);
815 $relatedobjects = [
816 'context' => $cache->get_context($event),
817 'course' => $cache->get_course($event),
818 ];
57d5b1b7 819
6fb75156
SL
820 $exporter = new event_exporter($event, $relatedobjects);
821 $renderer = $PAGE->get_renderer('core_calendar');
822
823 return array('event' => $exporter->export($renderer), 'warnings' => $warnings);
5813d1b9
SL
824 }
825
826 /**
827 * Returns description of method result value
828 *
829 * @return external_description
830 */
695c5726 831 public static function get_calendar_event_by_id_returns() {
6fb75156 832 $eventstructure = event_exporter::get_read_structure();
5813d1b9
SL
833
834 return new external_single_structure(array(
6fb75156 835 'event' => $eventstructure,
5813d1b9
SL
836 'warnings' => new external_warnings()
837 )
838 );
839 }
aa091225
RW
840
841 /**
842 * Returns description of method parameters.
843 *
844 * @return external_function_parameters.
845 */
846 public static function submit_create_update_form_parameters() {
847 return new external_function_parameters(
848 [
849 'formdata' => new external_value(PARAM_RAW, 'The data from the event form'),
850 ]
851 );
852 }
853
854 /**
855 * Handles the event form submission.
856 *
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
860 */
861 public static function submit_create_update_form($formdata) {
2aad6b82 862 global $USER, $PAGE, $CFG;
ea5f7707 863 require_once($CFG->libdir."/filelib.php");
aa091225
RW
864
865 // Parameter validation.
866 $params = self::validate_parameters(self::submit_create_update_form_parameters(), ['formdata' => $formdata]);
867 $context = \context_user::instance($USER->id);
868 $data = [];
869
870 self::validate_context($context);
871 parse_str($params['formdata'], $data);
872
dfc609e5
SL
873 $eventtype = isset($data['eventtype']) ? $data['eventtype'] : null;
874 $coursekey = ($eventtype == 'group') ? 'groupcourseid' : 'courseid';
875 $courseid = (!empty($data[$coursekey])) ? $data[$coursekey] : null;
876 $editoroptions = \core_calendar\local\event\forms\create::build_editor_options($context);
877 $formoptions = ['editoroptions' => $editoroptions, 'courseid' => $courseid];
878 if ($courseid) {
879 require_once($CFG->libdir . '/grouplib.php');
880 $groupcoursedata = groups_get_course_data($courseid);
881 if (!empty($groupcoursedata->groups)) {
882 $formoptions['groups'] = [];
883 foreach ($groupcoursedata->groups as $groupid => $groupdata) {
884 $formoptions['groups'][$groupid] = $groupdata->name;
885 }
886 }
887 }
888
aa091225
RW
889 if (!empty($data['id'])) {
890 $eventid = clean_param($data['id'], PARAM_INT);
891 $legacyevent = calendar_event::load($eventid);
892 $legacyevent->count_repeats();
dfc609e5 893 $formoptions['event'] = $legacyevent;
aa091225
RW
894 $mform = new update_event_form(null, $formoptions, 'post', '', null, true, $data);
895 } else {
896 $legacyevent = null;
dfc609e5 897 $mform = new create_event_form(null, $formoptions, 'post', '', null, true, $data);
aa091225
RW
898 }
899
900 if ($validateddata = $mform->get_data()) {
901 $formmapper = new create_update_form_mapper();
902 $properties = $formmapper->from_data_to_event_properties($validateddata);
903
904 if (is_null($legacyevent)) {
905 $legacyevent = new \calendar_event($properties);
6cb58071
RW
906 // Need to do this in order to initialise the description
907 // property which then triggers the update function below
908 // to set the appropriate default properties on the event.
909 $properties = $legacyevent->properties(true);
aa091225
RW
910 }
911
909d0858
RW
912 if (!calendar_edit_event_allowed($legacyevent, true)) {
913 print_error('nopermissiontoupdatecalendar');
914 }
915
aa091225 916 $legacyevent->update($properties);
ea5f7707
RW
917 $eventcontext = $legacyevent->context;
918
919 file_remove_editor_orphaned_files($validateddata->description);
920
921 // Take any files added to the description draft file area and
922 // convert them into the proper event description file area. Also
923 // parse the description text and replace the URLs to the draft files
924 // with the @@PLUGIN_FILE@@ placeholder to be persisted in the DB.
925 $description = file_save_draft_area_files(
926 $validateddata->description['itemid'],
927 $eventcontext->id,
928 'calendar',
929 'event_description',
930 $legacyevent->id,
931 create_event_form::build_editor_options($eventcontext),
932 $validateddata->description['text']
933 );
934
935 // If draft files were found then we need to save the new
936 // description value.
937 if ($description != $validateddata->description['text']) {
938 $properties->id = $legacyevent->id;
939 $properties->description = $description;
940 $legacyevent->update($properties);
941 }
aa091225
RW
942
943 $eventmapper = event_container::get_event_mapper();
944 $event = $eventmapper->from_legacy_event_to_event($legacyevent);
945 $cache = new events_related_objects_cache([$event]);
946 $relatedobjects = [
947 'context' => $cache->get_context($event),
948 'course' => $cache->get_course($event),
949 ];
950 $exporter = new event_exporter($event, $relatedobjects);
951 $renderer = $PAGE->get_renderer('core_calendar');
952
953 return [ 'event' => $exporter->export($renderer) ];
954 } else {
955 return [ 'validationerror' => true ];
956 }
957 }
958
959 /**
960 * Returns description of method result value.
961 *
962 * @return external_description.
963 */
964 public static function submit_create_update_form_returns() {
965 $eventstructure = event_exporter::get_read_structure();
966 $eventstructure->required = VALUE_OPTIONAL;
967
968 return new external_single_structure(
969 array(
970 'event' => $eventstructure,
971 'validationerror' => new external_value(PARAM_BOOL, 'Invalid form data', VALUE_DEFAULT, false),
972 )
973 );
974 }
695c5726
AN
975
976 /**
977 * Get data for the monthly calendar view.
978 *
f58424c7
AN
979 * @param int $year The year to be shown
980 * @param int $month The month to be shown
695c5726 981 * @param int $courseid The course to be included
d0e56d84 982 * @param int $categoryid The category to be included
fee025ec 983 * @param bool $includenavigation Whether to include navigation
60908b21 984 * @param bool $mini Whether to return the mini month view or not
695c5726
AN
985 * @return array
986 */
60908b21 987 public static function get_calendar_monthly_view($year, $month, $courseid, $categoryid, $includenavigation, $mini) {
2aad6b82 988 global $DB, $USER, $PAGE;
695c5726 989
695c5726
AN
990 // Parameter validation.
991 $params = self::validate_parameters(self::get_calendar_monthly_view_parameters(), [
f58424c7
AN
992 'year' => $year,
993 'month' => $month,
695c5726 994 'courseid' => $courseid,
d0e56d84 995 'categoryid' => $categoryid,
fee025ec 996 'includenavigation' => $includenavigation,
60908b21 997 'mini' => $mini,
695c5726
AN
998 ]);
999
d0e56d84
AN
1000 $context = \context_user::instance($USER->id);
1001 self::validate_context($context);
d097bfdd 1002 $PAGE->set_url('/calendar/');
d0e56d84 1003
f58424c7
AN
1004 $type = \core_calendar\type_factory::get_calendar_instance();
1005
6607c5ff
AN
1006 $time = $type->convert_to_timestamp($params['year'], $params['month'], 1);
1007 $calendar = \calendar_information::create($time, $params['courseid'], $params['categoryid']);
1008 self::validate_context($calendar->context);
695c5726 1009
60908b21
RW
1010 $view = $params['mini'] ? 'mini' : 'month';
1011 list($data, $template) = calendar_get_view($calendar, $view, $params['includenavigation']);
695c5726
AN
1012
1013 return $data;
1014 }
1015
1016 /**
1017 * Returns description of method parameters.
1018 *
1019 * @return external_function_parameters
1020 */
1021 public static function get_calendar_monthly_view_parameters() {
1022 return new external_function_parameters(
1023 [
f58424c7
AN
1024 'year' => new external_value(PARAM_INT, 'Month to be viewed', VALUE_REQUIRED),
1025 'month' => new external_value(PARAM_INT, 'Year to be viewed', VALUE_REQUIRED),
695c5726 1026 'courseid' => new external_value(PARAM_INT, 'Course being viewed', VALUE_DEFAULT, SITEID, NULL_ALLOWED),
d0e56d84 1027 'categoryid' => new external_value(PARAM_INT, 'Category being viewed', VALUE_DEFAULT, null, NULL_ALLOWED),
fee025ec
AN
1028 'includenavigation' => new external_value(
1029 PARAM_BOOL,
1030 'Whether to show course navigation',
1031 VALUE_DEFAULT,
1032 true,
1033 NULL_ALLOWED
1034 ),
60908b21
RW
1035 'mini' => new external_value(
1036 PARAM_BOOL,
1037 'Whether to return the mini month view or not',
1038 VALUE_DEFAULT,
1039 false,
1040 NULL_ALLOWED
1041 ),
695c5726
AN
1042 ]
1043 );
1044 }
1045
1046 /**
1047 * Returns description of method result value.
1048 *
1049 * @return external_description
1050 */
1051 public static function get_calendar_monthly_view_returns() {
1052 return \core_calendar\external\month_exporter::get_read_structure();
1053 }
c6fb9310 1054
3ea4f446
AN
1055 /**
1056 * Get data for the daily calendar view.
1057 *
1058 * @param int $year The year to be shown
1059 * @param int $month The month to be shown
1060 * @param int $day The day to be shown
1061 * @param int $courseid The course to be included
1062 * @return array
1063 */
1064 public static function get_calendar_day_view($year, $month, $day, $courseid, $categoryid) {
2aad6b82 1065 global $DB, $USER, $PAGE;
3ea4f446
AN
1066
1067 // Parameter validation.
1068 $params = self::validate_parameters(self::get_calendar_day_view_parameters(), [
1069 'year' => $year,
1070 'month' => $month,
1071 'day' => $day,
1072 'courseid' => $courseid,
1073 'categoryid' => $categoryid,
1074 ]);
1075
3ea4f446
AN
1076 $context = \context_user::instance($USER->id);
1077 self::validate_context($context);
1078
1079 $type = \core_calendar\type_factory::get_calendar_instance();
1080
6607c5ff
AN
1081 $time = $type->convert_to_timestamp($params['year'], $params['month'], $params['day']);
1082 $calendar = \calendar_information::create($time, $params['courseid'], $params['categoryid']);
1083 self::validate_context($calendar->context);
3ea4f446 1084
af25b8fc 1085 list($data, $template) = calendar_get_view($calendar, 'day');
3ea4f446
AN
1086
1087 return $data;
1088 }
1089
1090 /**
1091 * Returns description of method parameters.
1092 *
1093 * @return external_function_parameters
1094 */
1095 public static function get_calendar_day_view_parameters() {
1096 return new external_function_parameters(
1097 [
1098 'year' => new external_value(PARAM_INT, 'Year to be viewed', VALUE_REQUIRED),
1099 'month' => new external_value(PARAM_INT, 'Month to be viewed', VALUE_REQUIRED),
1100 'day' => new external_value(PARAM_INT, 'Day to be viewed', VALUE_REQUIRED),
1101 'courseid' => new external_value(PARAM_INT, 'Course being viewed', VALUE_DEFAULT, SITEID, NULL_ALLOWED),
1102 'categoryid' => new external_value(PARAM_INT, 'Category being viewed', VALUE_DEFAULT, null, NULL_ALLOWED),
1103 ]
1104 );
1105 }
1106
1107 /**
1108 * Returns description of method result value.
1109 *
1110 * @return external_description
1111 */
1112 public static function get_calendar_day_view_returns() {
1113 return \core_calendar\external\calendar_day_exporter::get_read_structure();
1114 }
1115
1116
c6fb9310
RW
1117 /**
1118 * Returns description of method parameters.
1119 *
1120 * @return external_function_parameters
1121 */
1122 public static function update_event_start_day_parameters() {
1123 return new external_function_parameters(
1124 [
96283892
RW
1125 'eventid' => new external_value(PARAM_INT, 'Id of event to be updated', VALUE_REQUIRED),
1126 'daytimestamp' => new external_value(PARAM_INT, 'Timestamp for the new start day', VALUE_REQUIRED),
c6fb9310
RW
1127 ]
1128 );
1129 }
1130
1131 /**
1132 * Change the start day for the given calendar event to the day that
1133 * corresponds with the provided timestamp.
1134 *
1135 * The timestamp only needs to be anytime within the desired day as only
1136 * the date data is extracted from it.
1137 *
1138 * The event's original time of day is maintained, only the date is shifted.
1139 *
96283892
RW
1140 * @param int $eventid Id of event to be updated
1141 * @param int $daytimestamp Timestamp for the new start day
c6fb9310
RW
1142 * @return array
1143 */
96283892 1144 public static function update_event_start_day($eventid, $daytimestamp) {
c6fb9310
RW
1145 global $USER, $PAGE;
1146
1147 // Parameter validation.
1148 $params = self::validate_parameters(self::update_event_start_day_parameters(), [
96283892
RW
1149 'eventid' => $eventid,
1150 'daytimestamp' => $daytimestamp,
c6fb9310
RW
1151 ]);
1152
c6fb9310 1153 $vault = event_container::get_event_vault();
909d0858 1154 $mapper = event_container::get_event_mapper();
96283892 1155 $event = $vault->get_event_by_id($eventid);
909d0858
RW
1156
1157 if (!$event) {
96283892 1158 throw new \moodle_exception('Unable to find event with id ' . $eventid);
909d0858
RW
1159 }
1160
1161 $legacyevent = $mapper->from_event_to_legacy_event($event);
1162
1163 if (!calendar_edit_event_allowed($legacyevent, true)) {
1164 print_error('nopermissiontoupdatecalendar');
1165 }
1166
ca518350
RW
1167 self::validate_context($legacyevent->context);
1168
96283892 1169 $newdate = usergetdate($daytimestamp);
c6fb9310
RW
1170 $startdatestring = implode('-', [$newdate['year'], $newdate['mon'], $newdate['mday']]);
1171 $startdate = new DateTimeImmutable($startdatestring);
1172 $event = local_api::update_event_start_day($event, $startdate);
1173 $cache = new events_related_objects_cache([$event]);
1174 $relatedobjects = [
1175 'context' => $cache->get_context($event),
1176 'course' => $cache->get_course($event),
1177 ];
1178 $exporter = new event_exporter($event, $relatedobjects);
1179 $renderer = $PAGE->get_renderer('core_calendar');
1180
1181 return array('event' => $exporter->export($renderer));
1182 }
1183
1184 /**
1185 * Returns description of method result value.
1186 *
1187 * @return external_description
1188 */
1189 public static function update_event_start_day_returns() {
1190 return new external_single_structure(
1191 array(
1192 'event' => event_exporter::get_read_structure()
1193 )
1194 );
1195 }
e8306438
SL
1196
1197 /**
1198 * Get data for the monthly calendar view.
1199 *
1200 * @param int $courseid The course to be included
7f14def2 1201 * @param int $categoryid The category to be included
e8306438
SL
1202 * @return array
1203 */
7f14def2 1204 public static function get_calendar_upcoming_view($courseid, $categoryid) {
2aad6b82 1205 global $DB, $USER, $PAGE;
e8306438
SL
1206
1207 // Parameter validation.
6607c5ff 1208 $params = self::validate_parameters(self::get_calendar_upcoming_view_parameters(), [
e8306438 1209 'courseid' => $courseid,
d523cbcb 1210 'categoryid' => $categoryid,
e8306438 1211 ]);
e8306438
SL
1212
1213 $context = \context_user::instance($USER->id);
1214 self::validate_context($context);
6607c5ff 1215 $PAGE->set_url('/calendar/');
e8306438 1216
6607c5ff
AN
1217 $calendar = \calendar_information::create(time(), $params['courseid'], $params['categoryid']);
1218 self::validate_context($calendar->context);
e8306438
SL
1219
1220 list($data, $template) = calendar_get_view($calendar, 'upcoming');
1221
1222 return $data;
1223 }
1224
1225 /**
1226 * Returns description of method parameters.
1227 *
1228 * @return external_function_parameters
1229 */
1230 public static function get_calendar_upcoming_view_parameters() {
1231 return new external_function_parameters(
1232 [
1233 'courseid' => new external_value(PARAM_INT, 'Course being viewed', VALUE_DEFAULT, SITEID, NULL_ALLOWED),
d523cbcb 1234 'categoryid' => new external_value(PARAM_INT, 'Category being viewed', VALUE_DEFAULT, null, NULL_ALLOWED),
e8306438
SL
1235 ]
1236 );
1237 }
1238
1239 /**
1240 * Returns description of method result value.
1241 *
1242 * @return external_description
1243 */
1244 public static function get_calendar_upcoming_view_returns() {
1245 return \core_calendar\external\calendar_upcoming_exporter::get_read_structure();
1246 }
a46980fa
JL
1247
1248
1249 /**
1250 * Returns description of method parameters.
1251 *
1252 * @return external_function_parameters.
1253 * @since Moodle 3.7
1254 */
1255 public static function get_calendar_access_information_parameters() {
1256 return new external_function_parameters(
1257 [
1258 'courseid' => new external_value(PARAM_INT, 'Course to check, empty for site calendar events.', VALUE_DEFAULT, 0),
1259 ]
1260 );
1261 }
1262
1263 /**
1264 * Convenience function to retrieve some permissions information for the given course calendar.
1265 *
1266 * @param int $courseid Course to check, empty for site.
1267 * @return array The access information
1268 * @throws moodle_exception
1269 * @since Moodle 3.7
1270 */
1271 public static function get_calendar_access_information($courseid = 0) {
1272
1273 $params = self::validate_parameters(self::get_calendar_access_information_parameters(), ['courseid' => $courseid]);
1274
1275 if (empty($params['courseid']) || $params['courseid'] == SITEID) {
1276 $context = \context_system::instance();
1277 } else {
1278 $context = \context_course::instance($params['courseid']);
1279 }
1280
1281 self::validate_context($context);
1282
1283 return [
1284 'canmanageentries' => has_capability('moodle/calendar:manageentries', $context),
1285 'canmanageownentries' => has_capability('moodle/calendar:manageownentries', $context),
1286 'canmanagegroupentries' => has_capability('moodle/calendar:managegroupentries', $context),
1287 'warnings' => [],
1288 ];
1289 }
1290
1291 /**
1292 * Returns description of method result value.
1293 *
1294 * @return external_description.
1295 * @since Moodle 3.7
1296 */
1297 public static function get_calendar_access_information_returns() {
1298
1299 return new external_single_structure(
1300 [
1301 'canmanageentries' => new external_value(PARAM_BOOL, 'Whether the user can manage entries.'),
1302 'canmanageownentries' => new external_value(PARAM_BOOL, 'Whether the user can manage its own entries.'),
1303 'canmanagegroupentries' => new external_value(PARAM_BOOL, 'Whether the user can manage group entries.'),
1304 'warnings' => new external_warnings(),
1305 ]
1306 );
1307 }
2aad6b82
JL
1308
1309 /**
1310 * Returns description of method parameters.
1311 *
1312 * @return external_function_parameters.
1313 * @since Moodle 3.7
1314 */
1315 public static function get_allowed_event_types_parameters() {
1316 return new external_function_parameters(
1317 [
1318 'courseid' => new external_value(PARAM_INT, 'Course to check, empty for site.', VALUE_DEFAULT, 0),
1319 ]
1320 );
1321 }
1322
1323 /**
1324 * Get the type of events a user can create in the given course.
1325 *
1326 * @param int $courseid Course to check, empty for site.
1327 * @return array The types allowed
1328 * @throws moodle_exception
1329 * @since Moodle 3.7
1330 */
1331 public static function get_allowed_event_types($courseid = 0) {
1332
1333 $params = self::validate_parameters(self::get_allowed_event_types_parameters(), ['courseid' => $courseid]);
1334
1335 if (empty($params['courseid']) || $params['courseid'] == SITEID) {
1336 $context = \context_system::instance();
1337 } else {
1338 $context = \context_course::instance($params['courseid']);
1339 }
1340
1341 self::validate_context($context);
1342
1343 $allowedeventtypes = array_filter(calendar_get_allowed_event_types($params['courseid']));
1344
1345 return [
1346 'allowedeventtypes' => array_keys($allowedeventtypes),
1347 'warnings' => [],
1348 ];
1349 }
1350
1351 /**
1352 * Returns description of method result value.
1353 *
1354 * @return external_description.
1355 * @since Moodle 3.7
1356 */
1357 public static function get_allowed_event_types_returns() {
1358
1359 return new external_single_structure(
1360 [
1361 'allowedeventtypes' => new external_multiple_structure(
1362 new external_value(PARAM_NOTAGS, 'Allowed event types to be created in the given course.')
1363 ),
1364 'warnings' => new external_warnings(),
1365 ]
1366 );
1367 }
01bea07d 1368}