MDL-65087 message: add button role to all the links that perfom actions
[moodle.git] / calendar / externallib.php
blobabf2c20108930b79d92dae22a6cbec7d5c6c5744
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * External calendar API
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
28 defined('MOODLE_INTERNAL') || die;
30 require_once("$CFG->libdir/externallib.php");
32 use \core_calendar\local\api as local_api;
33 use \core_calendar\local\event\container as event_container;
34 use \core_calendar\local\event\forms\create as create_event_form;
35 use \core_calendar\local\event\forms\update as update_event_form;
36 use \core_calendar\local\event\mappers\create_update_form_mapper;
37 use \core_calendar\external\event_exporter;
38 use \core_calendar\external\events_exporter;
39 use \core_calendar\external\events_grouped_by_course_exporter;
40 use \core_calendar\external\events_related_objects_cache;
42 /**
43 * Calendar external functions
45 * @package core_calendar
46 * @category external
47 * @copyright 2012 Ankit Agarwal
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 * @since Moodle 2.5
51 class core_calendar_external extends external_api {
54 /**
55 * Returns description of method parameters
57 * @return external_function_parameters
58 * @since Moodle 2.5
60 public static function delete_calendar_events_parameters() {
61 return new external_function_parameters(
62 array('events' => new external_multiple_structure(
63 new external_single_structure(
64 array(
65 'eventid' => new external_value(PARAM_INT, 'Event ID', VALUE_REQUIRED, '', NULL_NOT_ALLOWED),
66 'repeat' => new external_value(PARAM_BOOL, 'Delete comeplete series if repeated event')
67 ), 'List of events to delete'
74 /**
75 * Delete Calendar events
77 * @param array $eventids A list of event ids with repeat flag to delete
78 * @return null
79 * @since Moodle 2.5
81 public static function delete_calendar_events($events) {
82 global $CFG, $DB;
83 require_once($CFG->dirroot."/calendar/lib.php");
85 // Parameter validation.
86 $params = self::validate_parameters(self:: delete_calendar_events_parameters(), array('events' => $events));
88 $transaction = $DB->start_delegated_transaction();
90 foreach ($params['events'] as $event) {
91 $eventobj = calendar_event::load($event['eventid']);
93 // Let's check if the user is allowed to delete an event.
94 if (!calendar_delete_event_allowed($eventobj)) {
95 throw new moodle_exception('nopermissions', 'error', '', get_string('deleteevent', 'calendar'));
97 // Time to do the magic.
98 $eventobj->delete($event['repeat']);
101 // Everything done smoothly, let's commit.
102 $transaction->allow_commit();
104 return null;
108 * Returns description of method result value
110 * @return external_description
111 * @since Moodle 2.5
113 public static function delete_calendar_events_returns() {
114 return null;
118 * Returns description of method parameters
120 * @return external_function_parameters
121 * @since Moodle 2.5
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',
130 VALUE_DEFAULT, array()),
131 'courseids' => new external_multiple_structure(
132 new external_value(PARAM_INT, 'course ids')
133 , 'List of course ids for which events will be returned',
134 VALUE_DEFAULT, array()),
135 'groupids' => new external_multiple_structure(
136 new external_value(PARAM_INT, 'group ids')
137 , 'List of group ids for which events should be returned',
138 VALUE_DEFAULT, array()),
139 'categoryids' => new external_multiple_structure(
140 new external_value(PARAM_INT, 'Category ids'),
141 'List of category ids for which events will be returned',
142 VALUE_DEFAULT, array()),
143 ), 'Event details', VALUE_DEFAULT, array()),
144 'options' => new external_single_structure(
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,
156 "Time to which the events should be returned. We treat 0 and null as no end",
157 VALUE_DEFAULT, 0, NULL_ALLOWED),
158 'ignorehidden' => new external_value(PARAM_BOOL,
159 "Ignore hidden events or not",
160 VALUE_DEFAULT, true, NULL_ALLOWED),
162 ), 'Options', VALUE_DEFAULT, array())
168 * Get Calendar events
170 * @param array $events A list of events
171 * @param array $options various options
172 * @return array Array of event details
173 * @since Moodle 2.5
175 public static function get_calendar_events($events = array(), $options = array()) {
176 global $SITE, $DB, $USER, $CFG;
177 require_once($CFG->dirroot."/calendar/lib.php");
179 // Parameter validation.
180 $params = self::validate_parameters(self::get_calendar_events_parameters(), array('events' => $events, 'options' => $options));
181 $funcparam = array('courses' => array(), 'groups' => array(), 'categories' => array());
182 $hassystemcap = has_capability('moodle/calendar:manageentries', context_system::instance());
183 $warnings = array();
184 $coursecategories = array();
186 // Let us find out courses and their categories that we can return events from.
187 if (!$hassystemcap) {
188 $courseobjs = enrol_get_my_courses();
189 $courses = array_keys($courseobjs);
191 $coursecategories = array_flip(array_map(function($course) {
192 return $course->category;
193 }, $courseobjs));
195 foreach ($params['events']['courseids'] as $id) {
196 try {
197 $context = context_course::instance($id);
198 self::validate_context($context);
199 $funcparam['courses'][] = $id;
200 } catch (Exception $e) {
201 $warnings[] = array(
202 'item' => 'course',
203 'itemid' => $id,
204 'warningcode' => 'nopermissions',
205 'message' => 'No access rights in course context '.$e->getMessage().$e->getTraceAsString()
209 } else {
210 $courses = $params['events']['courseids'];
211 $funcparam['courses'] = $courses;
213 if (!empty($courses)) {
214 list($wheresql, $sqlparams) = $DB->get_in_or_equal($courses);
215 $wheresql = "id $wheresql";
216 $coursecategories = array_flip(array_map(function($course) {
217 return $course->category;
218 }, $DB->get_records_select('course', $wheresql, $sqlparams, '', 'category')));
222 // Let us findout groups that we can return events from.
223 if (!$hassystemcap) {
224 $groups = groups_get_my_groups();
225 $groups = array_keys($groups);
226 foreach ($params['events']['groupids'] as $id) {
227 if (in_array($id, $groups)) {
228 $funcparam['groups'][] = $id;
229 } else {
230 $warnings[] = array('item' => $id, 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to access this group');
233 } else {
234 $groups = $params['events']['groupids'];
235 $funcparam['groups'] = $groups;
238 $categories = array();
239 if ($hassystemcap || !empty($courses)) {
240 // Use the category id as the key in the following array. That way we do not have to remove duplicates and
241 // have a faster lookup later.
242 $categories = [];
244 if (!empty($params['events']['categoryids'])) {
245 $catobjs = \core_course_category::get_many(
246 array_merge($params['events']['categoryids'], array_keys($coursecategories)));
247 foreach ($catobjs as $catobj) {
248 if (isset($coursecategories[$catobj->id]) ||
249 has_capability('moodle/category:manage', $catobj->get_context())) {
250 // If the user has access to a course in this category or can manage the category,
251 // then they can see all parent categories too.
252 $categories[$catobj->id] = true;
253 foreach ($catobj->get_parents() as $catid) {
254 $categories[$catid] = true;
258 $funcparam['categories'] = array_keys($categories);
259 } else {
260 // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
261 $calcatcache = cache::make('core', 'calendar_categories');
262 // Do not use cache if the user has the system capability as $coursecategories might not represent the
263 // courses the user is enrolled in.
264 $categories = (!$hassystemcap) ? $calcatcache->get('site') : false;
265 if ($categories !== false) {
266 // The ids are stored in a list in the cache.
267 $funcparam['categories'] = $categories;
268 $categories = array_flip($categories);
269 } else {
270 $categories = [];
271 foreach (\core_course_category::get_all() as $category) {
272 if (isset($coursecategories[$category->id]) ||
273 has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
274 // If the user has access to a course in this category or can manage the category,
275 // then they can see all parent categories too.
276 $categories[$category->id] = true;
277 foreach ($category->get_parents() as $catid) {
278 $categories[$catid] = true;
282 $funcparam['categories'] = array_keys($categories);
283 if (!$hassystemcap) {
284 $calcatcache->set('site', $funcparam['categories']);
290 // Do we need user events?
291 if (!empty($params['options']['userevents'])) {
292 $funcparam['users'] = array($USER->id);
293 } else {
294 $funcparam['users'] = false;
297 // Do we need site events?
298 if (!empty($params['options']['siteevents'])) {
299 $funcparam['courses'][] = $SITE->id;
302 // We treat 0 and null as no end.
303 if (empty($params['options']['timeend'])) {
304 $params['options']['timeend'] = PHP_INT_MAX;
307 // Event list does not check visibility and permissions, we'll check that later.
308 $eventlist = calendar_get_legacy_events($params['options']['timestart'], $params['options']['timeend'],
309 $funcparam['users'], $funcparam['groups'], $funcparam['courses'], true,
310 $params['options']['ignorehidden'], $funcparam['categories']);
312 // WS expects arrays.
313 $events = array();
315 // We need to get events asked for eventids.
316 if ($eventsbyid = calendar_get_events_by_id($params['events']['eventids'])) {
317 $eventlist += $eventsbyid;
319 foreach ($eventlist as $eventid => $eventobj) {
320 $event = (array) $eventobj;
321 // Description formatting.
322 $calendareventobj = new calendar_event($event);
323 list($event['description'], $event['format']) = $calendareventobj->format_external_text();
325 if ($hassystemcap) {
326 // User can see everything, no further check is needed.
327 $events[$eventid] = $event;
328 } else if (!empty($eventobj->modulename)) {
329 $courseid = $eventobj->courseid;
330 if (!$courseid) {
331 if (!$calendareventobj->context || !($context = $calendareventobj->context->get_course_context(false))) {
332 continue;
334 $courseid = $context->instanceid;
336 $instances = get_fast_modinfo($courseid)->get_instances_of($eventobj->modulename);
337 if (!empty($instances[$eventobj->instance]->uservisible)) {
338 $events[$eventid] = $event;
340 } else {
341 // Can the user actually see this event?
342 $eventobj = calendar_event::load($eventobj);
343 if ((($eventobj->courseid == $SITE->id) && (empty($eventobj->categoryid))) ||
344 (!empty($eventobj->categoryid) && isset($categories[$eventobj->categoryid])) ||
345 (!empty($eventobj->groupid) && in_array($eventobj->groupid, $groups)) ||
346 (!empty($eventobj->courseid) && in_array($eventobj->courseid, $courses)) ||
347 ($USER->id == $eventobj->userid) ||
348 (calendar_edit_event_allowed($eventobj))) {
349 $events[$eventid] = $event;
350 } else {
351 $warnings[] = array('item' => $eventid, 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to view this event');
355 return array('events' => $events, 'warnings' => $warnings);
359 * Returns description of method result value
361 * @return external_description
362 * @since Moodle 2.5
364 public static function get_calendar_events_returns() {
365 return new external_single_structure(array(
366 'events' => new external_multiple_structure( new external_single_structure(
367 array(
368 'id' => new external_value(PARAM_INT, 'event id'),
369 'name' => new external_value(PARAM_TEXT, 'event name'),
370 'description' => new external_value(PARAM_RAW, 'Description', VALUE_OPTIONAL, null, NULL_ALLOWED),
371 'format' => new external_format_value('description'),
372 'courseid' => new external_value(PARAM_INT, 'course id'),
373 'categoryid' => new external_value(PARAM_INT, 'Category id (only for category events).',
374 VALUE_OPTIONAL),
375 'groupid' => new external_value(PARAM_INT, 'group id'),
376 'userid' => new external_value(PARAM_INT, 'user id'),
377 'repeatid' => new external_value(PARAM_INT, 'repeat id'),
378 'modulename' => new external_value(PARAM_TEXT, 'module name', VALUE_OPTIONAL, null, NULL_ALLOWED),
379 'instance' => new external_value(PARAM_INT, 'instance id'),
380 'eventtype' => new external_value(PARAM_TEXT, 'Event type'),
381 'timestart' => new external_value(PARAM_INT, 'timestart'),
382 'timeduration' => new external_value(PARAM_INT, 'time duration'),
383 'visible' => new external_value(PARAM_INT, 'visible'),
384 'uuid' => new external_value(PARAM_TEXT, 'unique id of ical events', VALUE_OPTIONAL, null, NULL_NOT_ALLOWED),
385 'sequence' => new external_value(PARAM_INT, 'sequence'),
386 'timemodified' => new external_value(PARAM_INT, 'time modified'),
387 'subscriptionid' => new external_value(PARAM_INT, 'Subscription id', VALUE_OPTIONAL, null, NULL_ALLOWED),
388 ), 'event')
390 'warnings' => new external_warnings()
396 * Returns description of method parameters.
398 * @since Moodle 3.3
399 * @return external_function_parameters
401 public static function get_calendar_action_events_by_timesort_parameters() {
402 return new external_function_parameters(
403 array(
404 'timesortfrom' => new external_value(PARAM_INT, 'Time sort from', VALUE_DEFAULT, 0),
405 'timesortto' => new external_value(PARAM_INT, 'Time sort to', VALUE_DEFAULT, null),
406 'aftereventid' => new external_value(PARAM_INT, 'The last seen event id', VALUE_DEFAULT, 0),
407 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 20),
408 'limittononsuspendedevents' => new external_value(PARAM_BOOL,
409 'Limit the events to courses the user is not suspended in', VALUE_DEFAULT, false)
415 * Get calendar action events based on the timesort value.
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
422 * @return array
424 public static function get_calendar_action_events_by_timesort($timesortfrom = 0, $timesortto = null,
425 $aftereventid = 0, $limitnum = 20, $limittononsuspendedevents = false) {
426 global $CFG, $PAGE, $USER;
428 require_once($CFG->dirroot . '/calendar/lib.php');
430 $user = null;
431 $params = self::validate_parameters(
432 self::get_calendar_action_events_by_timesort_parameters(),
434 'timesortfrom' => $timesortfrom,
435 'timesortto' => $timesortto,
436 'aftereventid' => $aftereventid,
437 'limitnum' => $limitnum,
438 'limittononsuspendedevents' => $limittononsuspendedevents
441 $context = \context_user::instance($USER->id);
442 self::validate_context($context);
444 if (empty($params['aftereventid'])) {
445 $params['aftereventid'] = null;
448 $renderer = $PAGE->get_renderer('core_calendar');
449 $events = local_api::get_action_events_by_timesort(
450 $params['timesortfrom'],
451 $params['timesortto'],
452 $params['aftereventid'],
453 $params['limitnum'],
454 $params['limittononsuspendedevents']
457 $exportercache = new events_related_objects_cache($events);
458 $exporter = new events_exporter($events, ['cache' => $exportercache]);
460 return $exporter->export($renderer);
464 * Returns description of method result value.
466 * @since Moodle 3.3
467 * @return external_description
469 public static function get_calendar_action_events_by_timesort_returns() {
470 return events_exporter::get_read_structure();
474 * Returns description of method parameters.
476 * @return external_function_parameters
478 public static function get_calendar_action_events_by_course_parameters() {
479 return new external_function_parameters(
480 array(
481 'courseid' => new external_value(PARAM_INT, 'Course id'),
482 'timesortfrom' => new external_value(PARAM_INT, 'Time sort from', VALUE_DEFAULT, null),
483 'timesortto' => new external_value(PARAM_INT, 'Time sort to', VALUE_DEFAULT, null),
484 'aftereventid' => new external_value(PARAM_INT, 'The last seen event id', VALUE_DEFAULT, 0),
485 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 20)
491 * Get calendar action events for the given course.
493 * @since Moodle 3.3
494 * @param int $courseid Only events in this course
495 * @param null|int $timesortfrom Events after this time (inclusive)
496 * @param null|int $timesortto Events before this time (inclusive)
497 * @param null|int $aftereventid Get events with ids greater than this one
498 * @param int $limitnum Limit the number of results to this value
499 * @return array
501 public static function get_calendar_action_events_by_course(
502 $courseid, $timesortfrom = null, $timesortto = null, $aftereventid = 0, $limitnum = 20) {
504 global $CFG, $PAGE, $USER;
506 require_once($CFG->dirroot . '/calendar/lib.php');
508 $user = null;
509 $params = self::validate_parameters(
510 self::get_calendar_action_events_by_course_parameters(),
512 'courseid' => $courseid,
513 'timesortfrom' => $timesortfrom,
514 'timesortto' => $timesortto,
515 'aftereventid' => $aftereventid,
516 'limitnum' => $limitnum,
519 $context = \context_user::instance($USER->id);
520 self::validate_context($context);
522 if (empty($params['aftereventid'])) {
523 $params['aftereventid'] = null;
526 $courses = enrol_get_my_courses('*', null, 0, [$courseid]);
527 $courses = array_values($courses);
529 if (empty($courses)) {
530 return [];
533 $course = $courses[0];
534 $renderer = $PAGE->get_renderer('core_calendar');
535 $events = local_api::get_action_events_by_course(
536 $course,
537 $params['timesortfrom'],
538 $params['timesortto'],
539 $params['aftereventid'],
540 $params['limitnum']
543 $exportercache = new events_related_objects_cache($events, $courses);
544 $exporter = new events_exporter($events, ['cache' => $exportercache]);
546 return $exporter->export($renderer);
550 * Returns description of method result value.
552 * @return external_description
554 public static function get_calendar_action_events_by_course_returns() {
555 return events_exporter::get_read_structure();
559 * Returns description of method parameters.
561 * @return external_function_parameters
563 public static function get_calendar_action_events_by_courses_parameters() {
564 return new external_function_parameters(
565 array(
566 'courseids' => new external_multiple_structure(
567 new external_value(PARAM_INT, 'Course id')
569 'timesortfrom' => new external_value(PARAM_INT, 'Time sort from', VALUE_DEFAULT, null),
570 'timesortto' => new external_value(PARAM_INT, 'Time sort to', VALUE_DEFAULT, null),
571 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 10)
577 * Get calendar action events for a given list of courses.
579 * @since Moodle 3.3
580 * @param array $courseids Only include events for these courses
581 * @param null|int $timesortfrom Events after this time (inclusive)
582 * @param null|int $timesortto Events before this time (inclusive)
583 * @param int $limitnum Limit the number of results per course to this value
584 * @return array
586 public static function get_calendar_action_events_by_courses(
587 array $courseids, $timesortfrom = null, $timesortto = null, $limitnum = 10) {
589 global $CFG, $PAGE, $USER;
591 require_once($CFG->dirroot . '/calendar/lib.php');
593 $user = null;
594 $params = self::validate_parameters(
595 self::get_calendar_action_events_by_courses_parameters(),
597 'courseids' => $courseids,
598 'timesortfrom' => $timesortfrom,
599 'timesortto' => $timesortto,
600 'limitnum' => $limitnum,
603 $context = \context_user::instance($USER->id);
604 self::validate_context($context);
606 if (empty($params['courseids'])) {
607 return ['groupedbycourse' => []];
610 $renderer = $PAGE->get_renderer('core_calendar');
611 $courses = enrol_get_my_courses('*', null, 0, $params['courseids']);
612 $courses = array_values($courses);
614 if (empty($courses)) {
615 return ['groupedbycourse' => []];
618 $events = local_api::get_action_events_by_courses(
619 $courses,
620 $params['timesortfrom'],
621 $params['timesortto'],
622 $params['limitnum']
625 if (empty($events)) {
626 return ['groupedbycourse' => []];
629 $exportercache = new events_related_objects_cache($events, $courses);
630 $exporter = new events_grouped_by_course_exporter($events, ['cache' => $exportercache]);
632 return $exporter->export($renderer);
636 * Returns description of method result value.
638 * @return external_description
640 public static function get_calendar_action_events_by_courses_returns() {
641 return events_grouped_by_course_exporter::get_read_structure();
645 * Returns description of method parameters.
647 * @return external_function_parameters.
648 * @since Moodle 2.5
650 public static function create_calendar_events_parameters() {
651 // Userid is always current user, so no need to get it from client.
652 // Module based calendar events are not allowed here. Hence no need of instance and modulename.
653 // subscription id and uuid is not allowed as this is not an ical api.
654 return new external_function_parameters(
655 array('events' => new external_multiple_structure(
656 new external_single_structure(
657 array(
658 'name' => new external_value(PARAM_TEXT, 'event name', VALUE_REQUIRED, '', NULL_NOT_ALLOWED),
659 'description' => new external_value(PARAM_RAW, 'Description', VALUE_DEFAULT, null, NULL_ALLOWED),
660 'format' => new external_format_value('description', VALUE_DEFAULT),
661 'courseid' => new external_value(PARAM_INT, 'course id', VALUE_DEFAULT, 0, NULL_NOT_ALLOWED),
662 'groupid' => new external_value(PARAM_INT, 'group id', VALUE_DEFAULT, 0, NULL_NOT_ALLOWED),
663 'repeats' => new external_value(PARAM_INT, 'number of repeats', VALUE_DEFAULT, 0, NULL_NOT_ALLOWED),
664 'eventtype' => new external_value(PARAM_TEXT, 'Event type', VALUE_DEFAULT, 'user', NULL_NOT_ALLOWED),
665 'timestart' => new external_value(PARAM_INT, 'timestart', VALUE_DEFAULT, time(), NULL_NOT_ALLOWED),
666 'timeduration' => new external_value(PARAM_INT, 'time duration', VALUE_DEFAULT, 0, NULL_NOT_ALLOWED),
667 'visible' => new external_value(PARAM_INT, 'visible', VALUE_DEFAULT, 1, NULL_NOT_ALLOWED),
668 'sequence' => new external_value(PARAM_INT, 'sequence', VALUE_DEFAULT, 1, NULL_NOT_ALLOWED),
669 ), 'event')
676 * Delete Calendar events.
678 * @param array $events A list of events to create.
679 * @return array array of events created.
680 * @since Moodle 2.5
681 * @throws moodle_exception if user doesnt have the permission to create events.
683 public static function create_calendar_events($events) {
684 global $CFG, $DB, $USER;
685 require_once($CFG->dirroot."/calendar/lib.php");
687 // Parameter validation.
688 $params = self::validate_parameters(self::create_calendar_events_parameters(), array('events' => $events));
690 $transaction = $DB->start_delegated_transaction();
691 $return = array();
692 $warnings = array();
694 foreach ($params['events'] as $event) {
696 // Let us set some defaults.
697 $event['userid'] = $USER->id;
698 $event['modulename'] = '';
699 $event['instance'] = 0;
700 $event['subscriptionid'] = null;
701 $event['uuid']= '';
702 $event['format'] = external_validate_format($event['format']);
703 if ($event['repeats'] > 0) {
704 $event['repeat'] = 1;
705 } else {
706 $event['repeat'] = 0;
709 $eventobj = new calendar_event($event);
711 // Let's check if the user is allowed to delete an event.
712 if (!calendar_add_event_allowed($eventobj)) {
713 $warnings [] = array('item' => $event['name'], 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to create this event');
714 continue;
716 // Let's create the event.
717 $var = $eventobj->create($event);
718 $var = (array)$var->properties();
719 if ($event['repeat']) {
720 $children = $DB->get_records('event', array('repeatid' => $var['id']));
721 foreach ($children as $child) {
722 $return[] = (array) $child;
724 } else {
725 $return[] = $var;
729 // Everything done smoothly, let's commit.
730 $transaction->allow_commit();
731 return array('events' => $return, 'warnings' => $warnings);
735 * Returns description of method result value.
737 * @return external_description.
738 * @since Moodle 2.5
740 public static function create_calendar_events_returns() {
741 return new external_single_structure(
742 array(
743 'events' => new external_multiple_structure( new external_single_structure(
744 array(
745 'id' => new external_value(PARAM_INT, 'event id'),
746 'name' => new external_value(PARAM_TEXT, 'event name'),
747 'description' => new external_value(PARAM_RAW, 'Description', VALUE_OPTIONAL),
748 'format' => new external_format_value('description'),
749 'courseid' => new external_value(PARAM_INT, 'course id'),
750 'groupid' => new external_value(PARAM_INT, 'group id'),
751 'userid' => new external_value(PARAM_INT, 'user id'),
752 'repeatid' => new external_value(PARAM_INT, 'repeat id', VALUE_OPTIONAL),
753 'modulename' => new external_value(PARAM_TEXT, 'module name', VALUE_OPTIONAL),
754 'instance' => new external_value(PARAM_INT, 'instance id'),
755 'eventtype' => new external_value(PARAM_TEXT, 'Event type'),
756 'timestart' => new external_value(PARAM_INT, 'timestart'),
757 'timeduration' => new external_value(PARAM_INT, 'time duration'),
758 'visible' => new external_value(PARAM_INT, 'visible'),
759 'uuid' => new external_value(PARAM_TEXT, 'unique id of ical events', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
760 'sequence' => new external_value(PARAM_INT, 'sequence'),
761 'timemodified' => new external_value(PARAM_INT, 'time modified'),
762 'subscriptionid' => new external_value(PARAM_INT, 'Subscription id', VALUE_OPTIONAL),
763 ), 'event')
765 'warnings' => new external_warnings()
771 * Returns description of method parameters.
773 * @return external_function_parameters
775 public static function get_calendar_event_by_id_parameters() {
776 return new external_function_parameters(
777 array(
778 'eventid' => new external_value(PARAM_INT, 'The event id to be retrieved'),
784 * Get calendar event by id.
786 * @param int $eventid The calendar event id to be retrieved.
787 * @return array Array of event details
789 public static function get_calendar_event_by_id($eventid) {
790 global $CFG, $PAGE, $USER;
791 require_once($CFG->dirroot."/calendar/lib.php");
793 $params = self::validate_parameters(self::get_calendar_event_by_id_parameters(), ['eventid' => $eventid]);
794 $context = \context_user::instance($USER->id);
796 self::validate_context($context);
797 $warnings = array();
799 $legacyevent = calendar_event::load($eventid);
800 // Must check we can see this event.
801 if (!calendar_view_event_allowed($legacyevent)) {
802 // We can't return a warning in this case because the event is not optional.
803 // We don't know the context for the event and it's not worth loading it.
804 $syscontext = context_system::instance();
805 throw new \required_capability_exception($syscontext, 'moodle/course:view', 'nopermission', '');
808 $legacyevent->count_repeats();
810 $eventmapper = event_container::get_event_mapper();
811 $event = $eventmapper->from_legacy_event_to_event($legacyevent);
813 $cache = new events_related_objects_cache([$event]);
814 $relatedobjects = [
815 'context' => $cache->get_context($event),
816 'course' => $cache->get_course($event),
819 $exporter = new event_exporter($event, $relatedobjects);
820 $renderer = $PAGE->get_renderer('core_calendar');
822 return array('event' => $exporter->export($renderer), 'warnings' => $warnings);
826 * Returns description of method result value
828 * @return external_description
830 public static function get_calendar_event_by_id_returns() {
831 $eventstructure = event_exporter::get_read_structure();
833 return new external_single_structure(array(
834 'event' => $eventstructure,
835 'warnings' => new external_warnings()
841 * Returns description of method parameters.
843 * @return external_function_parameters.
845 public static function submit_create_update_form_parameters() {
846 return new external_function_parameters(
848 'formdata' => new external_value(PARAM_RAW, 'The data from the event form'),
854 * Handles the event form submission.
856 * @param string $formdata The event form data in a URI encoded param string
857 * @return array The created or modified event
858 * @throws moodle_exception
860 public static function submit_create_update_form($formdata) {
861 global $CFG, $USER, $PAGE;
862 require_once($CFG->dirroot."/calendar/lib.php");
863 require_once($CFG->libdir."/filelib.php");
865 // Parameter validation.
866 $params = self::validate_parameters(self::submit_create_update_form_parameters(), ['formdata' => $formdata]);
867 $context = \context_user::instance($USER->id);
868 $data = [];
870 self::validate_context($context);
871 parse_str($params['formdata'], $data);
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;
889 if (!empty($data['id'])) {
890 $eventid = clean_param($data['id'], PARAM_INT);
891 $legacyevent = calendar_event::load($eventid);
892 $legacyevent->count_repeats();
893 $formoptions['event'] = $legacyevent;
894 $mform = new update_event_form(null, $formoptions, 'post', '', null, true, $data);
895 } else {
896 $legacyevent = null;
897 $mform = new create_event_form(null, $formoptions, 'post', '', null, true, $data);
900 if ($validateddata = $mform->get_data()) {
901 $formmapper = new create_update_form_mapper();
902 $properties = $formmapper->from_data_to_event_properties($validateddata);
904 if (is_null($legacyevent)) {
905 $legacyevent = new \calendar_event($properties);
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);
912 if (!calendar_edit_event_allowed($legacyevent, true)) {
913 print_error('nopermissiontoupdatecalendar');
916 $legacyevent->update($properties);
917 $eventcontext = $legacyevent->context;
919 file_remove_editor_orphaned_files($validateddata->description);
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']
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);
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),
950 $exporter = new event_exporter($event, $relatedobjects);
951 $renderer = $PAGE->get_renderer('core_calendar');
953 return [ 'event' => $exporter->export($renderer) ];
954 } else {
955 return [ 'validationerror' => true ];
960 * Returns description of method result value.
962 * @return external_description.
964 public static function submit_create_update_form_returns() {
965 $eventstructure = event_exporter::get_read_structure();
966 $eventstructure->required = VALUE_OPTIONAL;
968 return new external_single_structure(
969 array(
970 'event' => $eventstructure,
971 'validationerror' => new external_value(PARAM_BOOL, 'Invalid form data', VALUE_DEFAULT, false),
977 * Get data for the monthly calendar view.
979 * @param int $year The year to be shown
980 * @param int $month The month to be shown
981 * @param int $courseid The course to be included
982 * @param int $categoryid The category to be included
983 * @param bool $includenavigation Whether to include navigation
984 * @param bool $mini Whether to return the mini month view or not
985 * @return array
987 public static function get_calendar_monthly_view($year, $month, $courseid, $categoryid, $includenavigation, $mini) {
988 global $CFG, $DB, $USER, $PAGE;
989 require_once($CFG->dirroot."/calendar/lib.php");
991 // Parameter validation.
992 $params = self::validate_parameters(self::get_calendar_monthly_view_parameters(), [
993 'year' => $year,
994 'month' => $month,
995 'courseid' => $courseid,
996 'categoryid' => $categoryid,
997 'includenavigation' => $includenavigation,
998 'mini' => $mini,
1001 $context = \context_user::instance($USER->id);
1002 self::validate_context($context);
1003 $PAGE->set_url('/calendar/');
1005 $type = \core_calendar\type_factory::get_calendar_instance();
1007 $time = $type->convert_to_timestamp($params['year'], $params['month'], 1);
1008 $calendar = \calendar_information::create($time, $params['courseid'], $params['categoryid']);
1009 self::validate_context($calendar->context);
1011 $view = $params['mini'] ? 'mini' : 'month';
1012 list($data, $template) = calendar_get_view($calendar, $view, $params['includenavigation']);
1014 return $data;
1018 * Returns description of method parameters.
1020 * @return external_function_parameters
1022 public static function get_calendar_monthly_view_parameters() {
1023 return new external_function_parameters(
1025 'year' => new external_value(PARAM_INT, 'Month to be viewed', VALUE_REQUIRED),
1026 'month' => new external_value(PARAM_INT, 'Year to be viewed', VALUE_REQUIRED),
1027 'courseid' => new external_value(PARAM_INT, 'Course being viewed', VALUE_DEFAULT, SITEID, NULL_ALLOWED),
1028 'categoryid' => new external_value(PARAM_INT, 'Category being viewed', VALUE_DEFAULT, null, NULL_ALLOWED),
1029 'includenavigation' => new external_value(
1030 PARAM_BOOL,
1031 'Whether to show course navigation',
1032 VALUE_DEFAULT,
1033 true,
1034 NULL_ALLOWED
1036 'mini' => new external_value(
1037 PARAM_BOOL,
1038 'Whether to return the mini month view or not',
1039 VALUE_DEFAULT,
1040 false,
1041 NULL_ALLOWED
1048 * Returns description of method result value.
1050 * @return external_description
1052 public static function get_calendar_monthly_view_returns() {
1053 return \core_calendar\external\month_exporter::get_read_structure();
1057 * Get data for the daily calendar view.
1059 * @param int $year The year to be shown
1060 * @param int $month The month to be shown
1061 * @param int $day The day to be shown
1062 * @param int $courseid The course to be included
1063 * @return array
1065 public static function get_calendar_day_view($year, $month, $day, $courseid, $categoryid) {
1066 global $CFG, $DB, $USER, $PAGE;
1067 require_once($CFG->dirroot."/calendar/lib.php");
1069 // Parameter validation.
1070 $params = self::validate_parameters(self::get_calendar_day_view_parameters(), [
1071 'year' => $year,
1072 'month' => $month,
1073 'day' => $day,
1074 'courseid' => $courseid,
1075 'categoryid' => $categoryid,
1078 $context = \context_user::instance($USER->id);
1079 self::validate_context($context);
1081 $type = \core_calendar\type_factory::get_calendar_instance();
1083 $time = $type->convert_to_timestamp($params['year'], $params['month'], $params['day']);
1084 $calendar = \calendar_information::create($time, $params['courseid'], $params['categoryid']);
1085 self::validate_context($calendar->context);
1087 list($data, $template) = calendar_get_view($calendar, 'day');
1089 return $data;
1093 * Returns description of method parameters.
1095 * @return external_function_parameters
1097 public static function get_calendar_day_view_parameters() {
1098 return new external_function_parameters(
1100 'year' => new external_value(PARAM_INT, 'Year to be viewed', VALUE_REQUIRED),
1101 'month' => new external_value(PARAM_INT, 'Month to be viewed', VALUE_REQUIRED),
1102 'day' => new external_value(PARAM_INT, 'Day to be viewed', VALUE_REQUIRED),
1103 'courseid' => new external_value(PARAM_INT, 'Course being viewed', VALUE_DEFAULT, SITEID, NULL_ALLOWED),
1104 'categoryid' => new external_value(PARAM_INT, 'Category being viewed', VALUE_DEFAULT, null, NULL_ALLOWED),
1110 * Returns description of method result value.
1112 * @return external_description
1114 public static function get_calendar_day_view_returns() {
1115 return \core_calendar\external\calendar_day_exporter::get_read_structure();
1120 * Returns description of method parameters.
1122 * @return external_function_parameters
1124 public static function update_event_start_day_parameters() {
1125 return new external_function_parameters(
1127 'eventid' => new external_value(PARAM_INT, 'Id of event to be updated', VALUE_REQUIRED),
1128 'daytimestamp' => new external_value(PARAM_INT, 'Timestamp for the new start day', VALUE_REQUIRED),
1134 * Change the start day for the given calendar event to the day that
1135 * corresponds with the provided timestamp.
1137 * The timestamp only needs to be anytime within the desired day as only
1138 * the date data is extracted from it.
1140 * The event's original time of day is maintained, only the date is shifted.
1142 * @param int $eventid Id of event to be updated
1143 * @param int $daytimestamp Timestamp for the new start day
1144 * @return array
1146 public static function update_event_start_day($eventid, $daytimestamp) {
1147 global $USER, $PAGE;
1149 // Parameter validation.
1150 $params = self::validate_parameters(self::update_event_start_day_parameters(), [
1151 'eventid' => $eventid,
1152 'daytimestamp' => $daytimestamp,
1155 $vault = event_container::get_event_vault();
1156 $mapper = event_container::get_event_mapper();
1157 $event = $vault->get_event_by_id($eventid);
1159 if (!$event) {
1160 throw new \moodle_exception('Unable to find event with id ' . $eventid);
1163 $legacyevent = $mapper->from_event_to_legacy_event($event);
1165 if (!calendar_edit_event_allowed($legacyevent, true)) {
1166 print_error('nopermissiontoupdatecalendar');
1169 self::validate_context($legacyevent->context);
1171 $newdate = usergetdate($daytimestamp);
1172 $startdatestring = implode('-', [$newdate['year'], $newdate['mon'], $newdate['mday']]);
1173 $startdate = new DateTimeImmutable($startdatestring);
1174 $event = local_api::update_event_start_day($event, $startdate);
1175 $cache = new events_related_objects_cache([$event]);
1176 $relatedobjects = [
1177 'context' => $cache->get_context($event),
1178 'course' => $cache->get_course($event),
1180 $exporter = new event_exporter($event, $relatedobjects);
1181 $renderer = $PAGE->get_renderer('core_calendar');
1183 return array('event' => $exporter->export($renderer));
1187 * Returns description of method result value.
1189 * @return external_description
1191 public static function update_event_start_day_returns() {
1192 return new external_single_structure(
1193 array(
1194 'event' => event_exporter::get_read_structure()
1200 * Get data for the monthly calendar view.
1202 * @param int $courseid The course to be included
1203 * @param int $categoryid The category to be included
1204 * @return array
1206 public static function get_calendar_upcoming_view($courseid, $categoryid) {
1207 global $CFG, $DB, $USER, $PAGE;
1208 require_once($CFG->dirroot."/calendar/lib.php");
1210 // Parameter validation.
1211 $params = self::validate_parameters(self::get_calendar_upcoming_view_parameters(), [
1212 'courseid' => $courseid,
1213 'categoryid' => $categoryid,
1216 $context = \context_user::instance($USER->id);
1217 self::validate_context($context);
1218 $PAGE->set_url('/calendar/');
1220 $calendar = \calendar_information::create(time(), $params['courseid'], $params['categoryid']);
1221 self::validate_context($calendar->context);
1223 list($data, $template) = calendar_get_view($calendar, 'upcoming');
1225 return $data;
1229 * Returns description of method parameters.
1231 * @return external_function_parameters
1233 public static function get_calendar_upcoming_view_parameters() {
1234 return new external_function_parameters(
1236 'courseid' => new external_value(PARAM_INT, 'Course being viewed', VALUE_DEFAULT, SITEID, NULL_ALLOWED),
1237 'categoryid' => new external_value(PARAM_INT, 'Category being viewed', VALUE_DEFAULT, null, NULL_ALLOWED),
1243 * Returns description of method result value.
1245 * @return external_description
1247 public static function get_calendar_upcoming_view_returns() {
1248 return \core_calendar\external\calendar_upcoming_exporter::get_read_structure();