MDL-63086 block_rss_client: Move skip time calculation to task
[moodle.git] / calendar / externallib.php
blob80e60cd8667acbc714484adcc4d0b99e43357fd8
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 = \coursecat::get_many(array_merge($params['events']['categoryids'], array_keys($coursecategories)));
246 foreach ($catobjs as $catobj) {
247 if (isset($coursecategories[$catobj->id]) ||
248 has_capability('moodle/category:manage', $catobj->get_context())) {
249 // If the user has access to a course in this category or can manage the category,
250 // then they can see all parent categories too.
251 $categories[$catobj->id] = true;
252 foreach ($catobj->get_parents() as $catid) {
253 $categories[$catid] = true;
257 $funcparam['categories'] = array_keys($categories);
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 = [];
270 foreach (\coursecat::get_all() as $category) {
271 if (isset($coursecategories[$category->id]) ||
272 has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
273 // If the user has access to a course in this category or can manage the category,
274 // then they can see all parent categories too.
275 $categories[$category->id] = true;
276 foreach ($category->get_parents() as $catid) {
277 $categories[$catid] = true;
281 $funcparam['categories'] = array_keys($categories);
282 if (!$hassystemcap) {
283 $calcatcache->set('site', $funcparam['categories']);
289 // Do we need user events?
290 if (!empty($params['options']['userevents'])) {
291 $funcparam['users'] = array($USER->id);
292 } else {
293 $funcparam['users'] = false;
296 // Do we need site events?
297 if (!empty($params['options']['siteevents'])) {
298 $funcparam['courses'][] = $SITE->id;
301 // We treat 0 and null as no end.
302 if (empty($params['options']['timeend'])) {
303 $params['options']['timeend'] = PHP_INT_MAX;
306 // Event list does not check visibility and permissions, we'll check that later.
307 $eventlist = calendar_get_legacy_events($params['options']['timestart'], $params['options']['timeend'],
308 $funcparam['users'], $funcparam['groups'], $funcparam['courses'], true,
309 $params['options']['ignorehidden'], $funcparam['categories']);
311 // WS expects arrays.
312 $events = array();
314 // We need to get events asked for eventids.
315 if ($eventsbyid = calendar_get_events_by_id($params['events']['eventids'])) {
316 $eventlist += $eventsbyid;
318 foreach ($eventlist as $eventid => $eventobj) {
319 $event = (array) $eventobj;
320 // Description formatting.
321 $calendareventobj = new calendar_event($event);
322 list($event['description'], $event['format']) = $calendareventobj->format_external_text();
324 if ($hassystemcap) {
325 // User can see everything, no further check is needed.
326 $events[$eventid] = $event;
327 } else if (!empty($eventobj->modulename)) {
328 $courseid = $eventobj->courseid;
329 if (!$courseid) {
330 if (!$calendareventobj->context || !($context = $calendareventobj->context->get_course_context(false))) {
331 continue;
333 $courseid = $context->instanceid;
335 $instances = get_fast_modinfo($courseid)->get_instances_of($eventobj->modulename);
336 if (!empty($instances[$eventobj->instance]->uservisible)) {
337 $events[$eventid] = $event;
339 } else {
340 // Can the user actually see this event?
341 $eventobj = calendar_event::load($eventobj);
342 if ((($eventobj->courseid == $SITE->id) && (empty($eventobj->categoryid))) ||
343 (!empty($eventobj->categoryid) && isset($categories[$eventobj->categoryid])) ||
344 (!empty($eventobj->groupid) && in_array($eventobj->groupid, $groups)) ||
345 (!empty($eventobj->courseid) && in_array($eventobj->courseid, $courses)) ||
346 ($USER->id == $eventobj->userid) ||
347 (calendar_edit_event_allowed($eventobj))) {
348 $events[$eventid] = $event;
349 } else {
350 $warnings[] = array('item' => $eventid, 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to view this event');
354 return array('events' => $events, 'warnings' => $warnings);
358 * Returns description of method result value
360 * @return external_description
361 * @since Moodle 2.5
363 public static function get_calendar_events_returns() {
364 return new external_single_structure(array(
365 'events' => new external_multiple_structure( new external_single_structure(
366 array(
367 'id' => new external_value(PARAM_INT, 'event id'),
368 'name' => new external_value(PARAM_TEXT, 'event name'),
369 'description' => new external_value(PARAM_RAW, 'Description', VALUE_OPTIONAL, null, NULL_ALLOWED),
370 'format' => new external_format_value('description'),
371 'courseid' => new external_value(PARAM_INT, 'course id'),
372 'categoryid' => new external_value(PARAM_INT, 'Category id (only for category events).',
373 VALUE_OPTIONAL),
374 'groupid' => new external_value(PARAM_INT, 'group id'),
375 'userid' => new external_value(PARAM_INT, 'user id'),
376 'repeatid' => new external_value(PARAM_INT, 'repeat id'),
377 'modulename' => new external_value(PARAM_TEXT, 'module name', VALUE_OPTIONAL, null, NULL_ALLOWED),
378 'instance' => new external_value(PARAM_INT, 'instance id'),
379 'eventtype' => new external_value(PARAM_TEXT, 'Event type'),
380 'timestart' => new external_value(PARAM_INT, 'timestart'),
381 'timeduration' => new external_value(PARAM_INT, 'time duration'),
382 'visible' => new external_value(PARAM_INT, 'visible'),
383 'uuid' => new external_value(PARAM_TEXT, 'unique id of ical events', VALUE_OPTIONAL, null, NULL_NOT_ALLOWED),
384 'sequence' => new external_value(PARAM_INT, 'sequence'),
385 'timemodified' => new external_value(PARAM_INT, 'time modified'),
386 'subscriptionid' => new external_value(PARAM_INT, 'Subscription id', VALUE_OPTIONAL, null, NULL_ALLOWED),
387 ), 'event')
389 'warnings' => new external_warnings()
395 * Returns description of method parameters.
397 * @since Moodle 3.3
398 * @return external_function_parameters
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),
406 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 20)
412 * Get calendar action events based on the timesort value.
414 * @since Moodle 3.3
415 * @param null|int $timesortfrom Events after this time (inclusive)
416 * @param null|int $timesortto Events before this time (inclusive)
417 * @param null|int $aftereventid Get events with ids greater than this one
418 * @param int $limitnum Limit the number of results to this value
419 * @return array
421 public static function get_calendar_action_events_by_timesort($timesortfrom = 0, $timesortto = null,
422 $aftereventid = 0, $limitnum = 20) {
423 global $CFG, $PAGE, $USER;
425 require_once($CFG->dirroot . '/calendar/lib.php');
427 $user = null;
428 $params = self::validate_parameters(
429 self::get_calendar_action_events_by_timesort_parameters(),
431 'timesortfrom' => $timesortfrom,
432 'timesortto' => $timesortto,
433 'aftereventid' => $aftereventid,
434 'limitnum' => $limitnum,
437 $context = \context_user::instance($USER->id);
438 self::validate_context($context);
440 if (empty($params['aftereventid'])) {
441 $params['aftereventid'] = null;
444 $renderer = $PAGE->get_renderer('core_calendar');
445 $events = local_api::get_action_events_by_timesort(
446 $params['timesortfrom'],
447 $params['timesortto'],
448 $params['aftereventid'],
449 $params['limitnum']
452 $exportercache = new events_related_objects_cache($events);
453 $exporter = new events_exporter($events, ['cache' => $exportercache]);
455 return $exporter->export($renderer);
459 * Returns description of method result value.
461 * @since Moodle 3.3
462 * @return external_description
464 public static function get_calendar_action_events_by_timesort_returns() {
465 return events_exporter::get_read_structure();
469 * Returns description of method parameters.
471 * @return external_function_parameters
473 public static function get_calendar_action_events_by_course_parameters() {
474 return new external_function_parameters(
475 array(
476 'courseid' => new external_value(PARAM_INT, 'Course id'),
477 'timesortfrom' => new external_value(PARAM_INT, 'Time sort from', VALUE_DEFAULT, null),
478 'timesortto' => new external_value(PARAM_INT, 'Time sort to', VALUE_DEFAULT, null),
479 'aftereventid' => new external_value(PARAM_INT, 'The last seen event id', VALUE_DEFAULT, 0),
480 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 20)
486 * Get calendar action events for the given course.
488 * @since Moodle 3.3
489 * @param int $courseid Only events in this course
490 * @param null|int $timesortfrom Events after this time (inclusive)
491 * @param null|int $timesortto Events before this time (inclusive)
492 * @param null|int $aftereventid Get events with ids greater than this one
493 * @param int $limitnum Limit the number of results to this value
494 * @return array
496 public static function get_calendar_action_events_by_course(
497 $courseid, $timesortfrom = null, $timesortto = null, $aftereventid = 0, $limitnum = 20) {
499 global $CFG, $PAGE, $USER;
501 require_once($CFG->dirroot . '/calendar/lib.php');
503 $user = null;
504 $params = self::validate_parameters(
505 self::get_calendar_action_events_by_course_parameters(),
507 'courseid' => $courseid,
508 'timesortfrom' => $timesortfrom,
509 'timesortto' => $timesortto,
510 'aftereventid' => $aftereventid,
511 'limitnum' => $limitnum,
514 $context = \context_user::instance($USER->id);
515 self::validate_context($context);
517 if (empty($params['aftereventid'])) {
518 $params['aftereventid'] = null;
521 $courses = enrol_get_my_courses('*', null, 0, [$courseid]);
522 $courses = array_values($courses);
524 if (empty($courses)) {
525 return [];
528 $course = $courses[0];
529 $renderer = $PAGE->get_renderer('core_calendar');
530 $events = local_api::get_action_events_by_course(
531 $course,
532 $params['timesortfrom'],
533 $params['timesortto'],
534 $params['aftereventid'],
535 $params['limitnum']
538 $exportercache = new events_related_objects_cache($events, $courses);
539 $exporter = new events_exporter($events, ['cache' => $exportercache]);
541 return $exporter->export($renderer);
545 * Returns description of method result value.
547 * @return external_description
549 public static function get_calendar_action_events_by_course_returns() {
550 return events_exporter::get_read_structure();
554 * Returns description of method parameters.
556 * @return external_function_parameters
558 public static function get_calendar_action_events_by_courses_parameters() {
559 return new external_function_parameters(
560 array(
561 'courseids' => new external_multiple_structure(
562 new external_value(PARAM_INT, 'Course id')
564 'timesortfrom' => new external_value(PARAM_INT, 'Time sort from', VALUE_DEFAULT, null),
565 'timesortto' => new external_value(PARAM_INT, 'Time sort to', VALUE_DEFAULT, null),
566 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 10)
572 * Get calendar action events for a given list of courses.
574 * @since Moodle 3.3
575 * @param array $courseids Only include events for these courses
576 * @param null|int $timesortfrom Events after this time (inclusive)
577 * @param null|int $timesortto Events before this time (inclusive)
578 * @param int $limitnum Limit the number of results per course to this value
579 * @return array
581 public static function get_calendar_action_events_by_courses(
582 array $courseids, $timesortfrom = null, $timesortto = null, $limitnum = 10) {
584 global $CFG, $PAGE, $USER;
586 require_once($CFG->dirroot . '/calendar/lib.php');
588 $user = null;
589 $params = self::validate_parameters(
590 self::get_calendar_action_events_by_courses_parameters(),
592 'courseids' => $courseids,
593 'timesortfrom' => $timesortfrom,
594 'timesortto' => $timesortto,
595 'limitnum' => $limitnum,
598 $context = \context_user::instance($USER->id);
599 self::validate_context($context);
601 if (empty($params['courseids'])) {
602 return ['groupedbycourse' => []];
605 $renderer = $PAGE->get_renderer('core_calendar');
606 $courses = enrol_get_my_courses('*', null, 0, $params['courseids']);
607 $courses = array_values($courses);
609 if (empty($courses)) {
610 return ['groupedbycourse' => []];
613 $events = local_api::get_action_events_by_courses(
614 $courses,
615 $params['timesortfrom'],
616 $params['timesortto'],
617 $params['limitnum']
620 if (empty($events)) {
621 return ['groupedbycourse' => []];
624 $exportercache = new events_related_objects_cache($events, $courses);
625 $exporter = new events_grouped_by_course_exporter($events, ['cache' => $exportercache]);
627 return $exporter->export($renderer);
631 * Returns description of method result value.
633 * @return external_description
635 public static function get_calendar_action_events_by_courses_returns() {
636 return events_grouped_by_course_exporter::get_read_structure();
640 * Returns description of method parameters.
642 * @return external_function_parameters.
643 * @since Moodle 2.5
645 public static function create_calendar_events_parameters() {
646 // Userid is always current user, so no need to get it from client.
647 // Module based calendar events are not allowed here. Hence no need of instance and modulename.
648 // subscription id and uuid is not allowed as this is not an ical api.
649 return new external_function_parameters(
650 array('events' => new external_multiple_structure(
651 new external_single_structure(
652 array(
653 'name' => new external_value(PARAM_TEXT, 'event name', VALUE_REQUIRED, '', NULL_NOT_ALLOWED),
654 'description' => new external_value(PARAM_RAW, 'Description', VALUE_DEFAULT, null, NULL_ALLOWED),
655 'format' => new external_format_value('description', VALUE_DEFAULT),
656 'courseid' => new external_value(PARAM_INT, 'course id', VALUE_DEFAULT, 0, NULL_NOT_ALLOWED),
657 'groupid' => new external_value(PARAM_INT, 'group id', VALUE_DEFAULT, 0, NULL_NOT_ALLOWED),
658 'repeats' => new external_value(PARAM_INT, 'number of repeats', VALUE_DEFAULT, 0, NULL_NOT_ALLOWED),
659 'eventtype' => new external_value(PARAM_TEXT, 'Event type', VALUE_DEFAULT, 'user', NULL_NOT_ALLOWED),
660 'timestart' => new external_value(PARAM_INT, 'timestart', VALUE_DEFAULT, time(), NULL_NOT_ALLOWED),
661 'timeduration' => new external_value(PARAM_INT, 'time duration', VALUE_DEFAULT, 0, NULL_NOT_ALLOWED),
662 'visible' => new external_value(PARAM_INT, 'visible', VALUE_DEFAULT, 1, NULL_NOT_ALLOWED),
663 'sequence' => new external_value(PARAM_INT, 'sequence', VALUE_DEFAULT, 1, NULL_NOT_ALLOWED),
664 ), 'event')
671 * Delete Calendar events.
673 * @param array $events A list of events to create.
674 * @return array array of events created.
675 * @since Moodle 2.5
676 * @throws moodle_exception if user doesnt have the permission to create events.
678 public static function create_calendar_events($events) {
679 global $CFG, $DB, $USER;
680 require_once($CFG->dirroot."/calendar/lib.php");
682 // Parameter validation.
683 $params = self::validate_parameters(self::create_calendar_events_parameters(), array('events' => $events));
685 $transaction = $DB->start_delegated_transaction();
686 $return = array();
687 $warnings = array();
689 foreach ($params['events'] as $event) {
691 // Let us set some defaults.
692 $event['userid'] = $USER->id;
693 $event['modulename'] = '';
694 $event['instance'] = 0;
695 $event['subscriptionid'] = null;
696 $event['uuid']= '';
697 $event['format'] = external_validate_format($event['format']);
698 if ($event['repeats'] > 0) {
699 $event['repeat'] = 1;
700 } else {
701 $event['repeat'] = 0;
704 $eventobj = new calendar_event($event);
706 // Let's check if the user is allowed to delete an event.
707 if (!calendar_add_event_allowed($eventobj)) {
708 $warnings [] = array('item' => $event['name'], 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to create this event');
709 continue;
711 // Let's create the event.
712 $var = $eventobj->create($event);
713 $var = (array)$var->properties();
714 if ($event['repeat']) {
715 $children = $DB->get_records('event', array('repeatid' => $var['id']));
716 foreach ($children as $child) {
717 $return[] = (array) $child;
719 } else {
720 $return[] = $var;
724 // Everything done smoothly, let's commit.
725 $transaction->allow_commit();
726 return array('events' => $return, 'warnings' => $warnings);
730 * Returns description of method result value.
732 * @return external_description.
733 * @since Moodle 2.5
735 public static function create_calendar_events_returns() {
736 return new external_single_structure(
737 array(
738 'events' => new external_multiple_structure( new external_single_structure(
739 array(
740 'id' => new external_value(PARAM_INT, 'event id'),
741 'name' => new external_value(PARAM_TEXT, 'event name'),
742 'description' => new external_value(PARAM_RAW, 'Description', VALUE_OPTIONAL),
743 'format' => new external_format_value('description'),
744 'courseid' => new external_value(PARAM_INT, 'course id'),
745 'groupid' => new external_value(PARAM_INT, 'group id'),
746 'userid' => new external_value(PARAM_INT, 'user id'),
747 'repeatid' => new external_value(PARAM_INT, 'repeat id', VALUE_OPTIONAL),
748 'modulename' => new external_value(PARAM_TEXT, 'module name', VALUE_OPTIONAL),
749 'instance' => new external_value(PARAM_INT, 'instance id'),
750 'eventtype' => new external_value(PARAM_TEXT, 'Event type'),
751 'timestart' => new external_value(PARAM_INT, 'timestart'),
752 'timeduration' => new external_value(PARAM_INT, 'time duration'),
753 'visible' => new external_value(PARAM_INT, 'visible'),
754 'uuid' => new external_value(PARAM_TEXT, 'unique id of ical events', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
755 'sequence' => new external_value(PARAM_INT, 'sequence'),
756 'timemodified' => new external_value(PARAM_INT, 'time modified'),
757 'subscriptionid' => new external_value(PARAM_INT, 'Subscription id', VALUE_OPTIONAL),
758 ), 'event')
760 'warnings' => new external_warnings()
766 * Returns description of method parameters.
768 * @return external_function_parameters
770 public static function get_calendar_event_by_id_parameters() {
771 return new external_function_parameters(
772 array(
773 'eventid' => new external_value(PARAM_INT, 'The event id to be retrieved'),
779 * Get calendar event by id.
781 * @param int $eventid The calendar event id to be retrieved.
782 * @return array Array of event details
784 public static function get_calendar_event_by_id($eventid) {
785 global $CFG, $PAGE, $USER;
786 require_once($CFG->dirroot."/calendar/lib.php");
788 $params = self::validate_parameters(self::get_calendar_event_by_id_parameters(), ['eventid' => $eventid]);
789 $context = \context_user::instance($USER->id);
791 self::validate_context($context);
792 $warnings = array();
794 $legacyevent = calendar_event::load($eventid);
795 // Must check we can see this event.
796 if (!calendar_view_event_allowed($legacyevent)) {
797 // We can't return a warning in this case because the event is not optional.
798 // We don't know the context for the event and it's not worth loading it.
799 $syscontext = context_system::instance();
800 throw new \required_capability_exception($syscontext, 'moodle/course:view', 'nopermission', '');
803 $legacyevent->count_repeats();
805 $eventmapper = event_container::get_event_mapper();
806 $event = $eventmapper->from_legacy_event_to_event($legacyevent);
808 $cache = new events_related_objects_cache([$event]);
809 $relatedobjects = [
810 'context' => $cache->get_context($event),
811 'course' => $cache->get_course($event),
814 $exporter = new event_exporter($event, $relatedobjects);
815 $renderer = $PAGE->get_renderer('core_calendar');
817 return array('event' => $exporter->export($renderer), 'warnings' => $warnings);
821 * Returns description of method result value
823 * @return external_description
825 public static function get_calendar_event_by_id_returns() {
826 $eventstructure = event_exporter::get_read_structure();
828 return new external_single_structure(array(
829 'event' => $eventstructure,
830 'warnings' => new external_warnings()
836 * Returns description of method parameters.
838 * @return external_function_parameters.
840 public static function submit_create_update_form_parameters() {
841 return new external_function_parameters(
843 'formdata' => new external_value(PARAM_RAW, 'The data from the event form'),
849 * Handles the event form submission.
851 * @param string $formdata The event form data in a URI encoded param string
852 * @return array The created or modified event
853 * @throws moodle_exception
855 public static function submit_create_update_form($formdata) {
856 global $CFG, $USER, $PAGE;
857 require_once($CFG->dirroot."/calendar/lib.php");
858 require_once($CFG->libdir."/filelib.php");
860 // Parameter validation.
861 $params = self::validate_parameters(self::submit_create_update_form_parameters(), ['formdata' => $formdata]);
862 $context = \context_user::instance($USER->id);
863 $data = [];
865 self::validate_context($context);
866 parse_str($params['formdata'], $data);
868 $eventtype = isset($data['eventtype']) ? $data['eventtype'] : null;
869 $coursekey = ($eventtype == 'group') ? 'groupcourseid' : 'courseid';
870 $courseid = (!empty($data[$coursekey])) ? $data[$coursekey] : null;
871 $editoroptions = \core_calendar\local\event\forms\create::build_editor_options($context);
872 $formoptions = ['editoroptions' => $editoroptions, 'courseid' => $courseid];
873 if ($courseid) {
874 require_once($CFG->libdir . '/grouplib.php');
875 $groupcoursedata = groups_get_course_data($courseid);
876 if (!empty($groupcoursedata->groups)) {
877 $formoptions['groups'] = [];
878 foreach ($groupcoursedata->groups as $groupid => $groupdata) {
879 $formoptions['groups'][$groupid] = $groupdata->name;
884 if (!empty($data['id'])) {
885 $eventid = clean_param($data['id'], PARAM_INT);
886 $legacyevent = calendar_event::load($eventid);
887 $legacyevent->count_repeats();
888 $formoptions['event'] = $legacyevent;
889 $mform = new update_event_form(null, $formoptions, 'post', '', null, true, $data);
890 } else {
891 $legacyevent = null;
892 $mform = new create_event_form(null, $formoptions, 'post', '', null, true, $data);
895 if ($validateddata = $mform->get_data()) {
896 $formmapper = new create_update_form_mapper();
897 $properties = $formmapper->from_data_to_event_properties($validateddata);
899 if (is_null($legacyevent)) {
900 $legacyevent = new \calendar_event($properties);
901 // Need to do this in order to initialise the description
902 // property which then triggers the update function below
903 // to set the appropriate default properties on the event.
904 $properties = $legacyevent->properties(true);
907 if (!calendar_edit_event_allowed($legacyevent, true)) {
908 print_error('nopermissiontoupdatecalendar');
911 $legacyevent->update($properties);
912 $eventcontext = $legacyevent->context;
914 file_remove_editor_orphaned_files($validateddata->description);
916 // Take any files added to the description draft file area and
917 // convert them into the proper event description file area. Also
918 // parse the description text and replace the URLs to the draft files
919 // with the @@PLUGIN_FILE@@ placeholder to be persisted in the DB.
920 $description = file_save_draft_area_files(
921 $validateddata->description['itemid'],
922 $eventcontext->id,
923 'calendar',
924 'event_description',
925 $legacyevent->id,
926 create_event_form::build_editor_options($eventcontext),
927 $validateddata->description['text']
930 // If draft files were found then we need to save the new
931 // description value.
932 if ($description != $validateddata->description['text']) {
933 $properties->id = $legacyevent->id;
934 $properties->description = $description;
935 $legacyevent->update($properties);
938 $eventmapper = event_container::get_event_mapper();
939 $event = $eventmapper->from_legacy_event_to_event($legacyevent);
940 $cache = new events_related_objects_cache([$event]);
941 $relatedobjects = [
942 'context' => $cache->get_context($event),
943 'course' => $cache->get_course($event),
945 $exporter = new event_exporter($event, $relatedobjects);
946 $renderer = $PAGE->get_renderer('core_calendar');
948 return [ 'event' => $exporter->export($renderer) ];
949 } else {
950 return [ 'validationerror' => true ];
955 * Returns description of method result value.
957 * @return external_description.
959 public static function submit_create_update_form_returns() {
960 $eventstructure = event_exporter::get_read_structure();
961 $eventstructure->required = VALUE_OPTIONAL;
963 return new external_single_structure(
964 array(
965 'event' => $eventstructure,
966 'validationerror' => new external_value(PARAM_BOOL, 'Invalid form data', VALUE_DEFAULT, false),
972 * Get data for the monthly calendar view.
974 * @param int $year The year to be shown
975 * @param int $month The month to be shown
976 * @param int $courseid The course to be included
977 * @param int $categoryid The category to be included
978 * @param bool $includenavigation Whether to include navigation
979 * @param bool $mini Whether to return the mini month view or not
980 * @return array
982 public static function get_calendar_monthly_view($year, $month, $courseid, $categoryid, $includenavigation, $mini) {
983 global $CFG, $DB, $USER, $PAGE;
984 require_once($CFG->dirroot."/calendar/lib.php");
986 // Parameter validation.
987 $params = self::validate_parameters(self::get_calendar_monthly_view_parameters(), [
988 'year' => $year,
989 'month' => $month,
990 'courseid' => $courseid,
991 'categoryid' => $categoryid,
992 'includenavigation' => $includenavigation,
993 'mini' => $mini,
996 $context = \context_user::instance($USER->id);
997 self::validate_context($context);
998 $PAGE->set_url('/calendar/');
1000 $type = \core_calendar\type_factory::get_calendar_instance();
1002 $time = $type->convert_to_timestamp($params['year'], $params['month'], 1);
1003 $calendar = \calendar_information::create($time, $params['courseid'], $params['categoryid']);
1004 self::validate_context($calendar->context);
1006 $view = $params['mini'] ? 'mini' : 'month';
1007 list($data, $template) = calendar_get_view($calendar, $view, $params['includenavigation']);
1009 return $data;
1013 * Returns description of method parameters.
1015 * @return external_function_parameters
1017 public static function get_calendar_monthly_view_parameters() {
1018 return new external_function_parameters(
1020 'year' => new external_value(PARAM_INT, 'Month to be viewed', VALUE_REQUIRED),
1021 'month' => new external_value(PARAM_INT, 'Year to be viewed', VALUE_REQUIRED),
1022 'courseid' => new external_value(PARAM_INT, 'Course being viewed', VALUE_DEFAULT, SITEID, NULL_ALLOWED),
1023 'categoryid' => new external_value(PARAM_INT, 'Category being viewed', VALUE_DEFAULT, null, NULL_ALLOWED),
1024 'includenavigation' => new external_value(
1025 PARAM_BOOL,
1026 'Whether to show course navigation',
1027 VALUE_DEFAULT,
1028 true,
1029 NULL_ALLOWED
1031 'mini' => new external_value(
1032 PARAM_BOOL,
1033 'Whether to return the mini month view or not',
1034 VALUE_DEFAULT,
1035 false,
1036 NULL_ALLOWED
1043 * Returns description of method result value.
1045 * @return external_description
1047 public static function get_calendar_monthly_view_returns() {
1048 return \core_calendar\external\month_exporter::get_read_structure();
1052 * Get data for the daily calendar view.
1054 * @param int $year The year to be shown
1055 * @param int $month The month to be shown
1056 * @param int $day The day to be shown
1057 * @param int $courseid The course to be included
1058 * @return array
1060 public static function get_calendar_day_view($year, $month, $day, $courseid, $categoryid) {
1061 global $CFG, $DB, $USER, $PAGE;
1062 require_once($CFG->dirroot."/calendar/lib.php");
1064 // Parameter validation.
1065 $params = self::validate_parameters(self::get_calendar_day_view_parameters(), [
1066 'year' => $year,
1067 'month' => $month,
1068 'day' => $day,
1069 'courseid' => $courseid,
1070 'categoryid' => $categoryid,
1073 $context = \context_user::instance($USER->id);
1074 self::validate_context($context);
1076 $type = \core_calendar\type_factory::get_calendar_instance();
1078 $time = $type->convert_to_timestamp($params['year'], $params['month'], $params['day']);
1079 $calendar = \calendar_information::create($time, $params['courseid'], $params['categoryid']);
1080 self::validate_context($calendar->context);
1082 list($data, $template) = calendar_get_view($calendar, 'day');
1084 return $data;
1088 * Returns description of method parameters.
1090 * @return external_function_parameters
1092 public static function get_calendar_day_view_parameters() {
1093 return new external_function_parameters(
1095 'year' => new external_value(PARAM_INT, 'Year to be viewed', VALUE_REQUIRED),
1096 'month' => new external_value(PARAM_INT, 'Month to be viewed', VALUE_REQUIRED),
1097 'day' => new external_value(PARAM_INT, 'Day to be viewed', VALUE_REQUIRED),
1098 'courseid' => new external_value(PARAM_INT, 'Course being viewed', VALUE_DEFAULT, SITEID, NULL_ALLOWED),
1099 'categoryid' => new external_value(PARAM_INT, 'Category being viewed', VALUE_DEFAULT, null, NULL_ALLOWED),
1105 * Returns description of method result value.
1107 * @return external_description
1109 public static function get_calendar_day_view_returns() {
1110 return \core_calendar\external\calendar_day_exporter::get_read_structure();
1115 * Returns description of method parameters.
1117 * @return external_function_parameters
1119 public static function update_event_start_day_parameters() {
1120 return new external_function_parameters(
1122 'eventid' => new external_value(PARAM_INT, 'Id of event to be updated', VALUE_REQUIRED),
1123 'daytimestamp' => new external_value(PARAM_INT, 'Timestamp for the new start day', VALUE_REQUIRED),
1129 * Change the start day for the given calendar event to the day that
1130 * corresponds with the provided timestamp.
1132 * The timestamp only needs to be anytime within the desired day as only
1133 * the date data is extracted from it.
1135 * The event's original time of day is maintained, only the date is shifted.
1137 * @param int $eventid Id of event to be updated
1138 * @param int $daytimestamp Timestamp for the new start day
1139 * @return array
1141 public static function update_event_start_day($eventid, $daytimestamp) {
1142 global $USER, $PAGE;
1144 // Parameter validation.
1145 $params = self::validate_parameters(self::update_event_start_day_parameters(), [
1146 'eventid' => $eventid,
1147 'daytimestamp' => $daytimestamp,
1150 $vault = event_container::get_event_vault();
1151 $mapper = event_container::get_event_mapper();
1152 $event = $vault->get_event_by_id($eventid);
1154 if (!$event) {
1155 throw new \moodle_exception('Unable to find event with id ' . $eventid);
1158 $legacyevent = $mapper->from_event_to_legacy_event($event);
1160 if (!calendar_edit_event_allowed($legacyevent, true)) {
1161 print_error('nopermissiontoupdatecalendar');
1164 self::validate_context($legacyevent->context);
1166 $newdate = usergetdate($daytimestamp);
1167 $startdatestring = implode('-', [$newdate['year'], $newdate['mon'], $newdate['mday']]);
1168 $startdate = new DateTimeImmutable($startdatestring);
1169 $event = local_api::update_event_start_day($event, $startdate);
1170 $cache = new events_related_objects_cache([$event]);
1171 $relatedobjects = [
1172 'context' => $cache->get_context($event),
1173 'course' => $cache->get_course($event),
1175 $exporter = new event_exporter($event, $relatedobjects);
1176 $renderer = $PAGE->get_renderer('core_calendar');
1178 return array('event' => $exporter->export($renderer));
1182 * Returns description of method result value.
1184 * @return external_description
1186 public static function update_event_start_day_returns() {
1187 return new external_single_structure(
1188 array(
1189 'event' => event_exporter::get_read_structure()
1195 * Get data for the monthly calendar view.
1197 * @param int $courseid The course to be included
1198 * @param int $categoryid The category to be included
1199 * @return array
1201 public static function get_calendar_upcoming_view($courseid, $categoryid) {
1202 global $CFG, $DB, $USER, $PAGE;
1203 require_once($CFG->dirroot."/calendar/lib.php");
1205 // Parameter validation.
1206 $params = self::validate_parameters(self::get_calendar_upcoming_view_parameters(), [
1207 'courseid' => $courseid,
1208 'categoryid' => $categoryid,
1211 $context = \context_user::instance($USER->id);
1212 self::validate_context($context);
1213 $PAGE->set_url('/calendar/');
1215 $calendar = \calendar_information::create(time(), $params['courseid'], $params['categoryid']);
1216 self::validate_context($calendar->context);
1218 list($data, $template) = calendar_get_view($calendar, 'upcoming');
1220 return $data;
1224 * Returns description of method parameters.
1226 * @return external_function_parameters
1228 public static function get_calendar_upcoming_view_parameters() {
1229 return new external_function_parameters(
1231 'courseid' => new external_value(PARAM_INT, 'Course being viewed', VALUE_DEFAULT, SITEID, NULL_ALLOWED),
1232 'categoryid' => new external_value(PARAM_INT, 'Category being viewed', VALUE_DEFAULT, null, NULL_ALLOWED),
1238 * Returns description of method result value.
1240 * @return external_description
1242 public static function get_calendar_upcoming_view_returns() {
1243 return \core_calendar\external\calendar_upcoming_exporter::get_read_structure();