MDL-51177 core: Ignore built files in stylelint
[moodle.git] / calendar / externallib.php
bloba7d784000c65af8236d34782b1df1914968a2b03
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)
413 * Get calendar action events based on the timesort value.
415 * @since Moodle 3.3
416 * @param null|int $timesortfrom Events after this time (inclusive)
417 * @param null|int $timesortto Events before this time (inclusive)
418 * @param null|int $aftereventid Get events with ids greater than this one
419 * @param int $limitnum Limit the number of results to this value
420 * @return array
422 public static function get_calendar_action_events_by_timesort($timesortfrom = 0, $timesortto = null,
423 $aftereventid = 0, $limitnum = 20) {
424 global $CFG, $PAGE, $USER;
426 require_once($CFG->dirroot . '/calendar/lib.php');
428 $user = null;
429 $params = self::validate_parameters(
430 self::get_calendar_action_events_by_timesort_parameters(),
432 'timesortfrom' => $timesortfrom,
433 'timesortto' => $timesortto,
434 'aftereventid' => $aftereventid,
435 'limitnum' => $limitnum,
438 $context = \context_user::instance($USER->id);
439 self::validate_context($context);
441 if (empty($params['aftereventid'])) {
442 $params['aftereventid'] = null;
445 $renderer = $PAGE->get_renderer('core_calendar');
446 $events = local_api::get_action_events_by_timesort(
447 $params['timesortfrom'],
448 $params['timesortto'],
449 $params['aftereventid'],
450 $params['limitnum']
453 $exportercache = new events_related_objects_cache($events);
454 $exporter = new events_exporter($events, ['cache' => $exportercache]);
456 return $exporter->export($renderer);
460 * Returns description of method result value.
462 * @since Moodle 3.3
463 * @return external_description
465 public static function get_calendar_action_events_by_timesort_returns() {
466 return events_exporter::get_read_structure();
470 * Returns description of method parameters.
472 * @return external_function_parameters
474 public static function get_calendar_action_events_by_course_parameters() {
475 return new external_function_parameters(
476 array(
477 'courseid' => new external_value(PARAM_INT, 'Course id'),
478 'timesortfrom' => new external_value(PARAM_INT, 'Time sort from', VALUE_DEFAULT, null),
479 'timesortto' => new external_value(PARAM_INT, 'Time sort to', VALUE_DEFAULT, null),
480 'aftereventid' => new external_value(PARAM_INT, 'The last seen event id', VALUE_DEFAULT, 0),
481 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 20)
487 * Get calendar action events for the given course.
489 * @since Moodle 3.3
490 * @param int $courseid Only events in this course
491 * @param null|int $timesortfrom Events after this time (inclusive)
492 * @param null|int $timesortto Events before this time (inclusive)
493 * @param null|int $aftereventid Get events with ids greater than this one
494 * @param int $limitnum Limit the number of results to this value
495 * @return array
497 public static function get_calendar_action_events_by_course(
498 $courseid, $timesortfrom = null, $timesortto = null, $aftereventid = 0, $limitnum = 20) {
500 global $CFG, $PAGE, $USER;
502 require_once($CFG->dirroot . '/calendar/lib.php');
504 $user = null;
505 $params = self::validate_parameters(
506 self::get_calendar_action_events_by_course_parameters(),
508 'courseid' => $courseid,
509 'timesortfrom' => $timesortfrom,
510 'timesortto' => $timesortto,
511 'aftereventid' => $aftereventid,
512 'limitnum' => $limitnum,
515 $context = \context_user::instance($USER->id);
516 self::validate_context($context);
518 if (empty($params['aftereventid'])) {
519 $params['aftereventid'] = null;
522 $courses = enrol_get_my_courses('*', null, 0, [$courseid]);
523 $courses = array_values($courses);
525 if (empty($courses)) {
526 return [];
529 $course = $courses[0];
530 $renderer = $PAGE->get_renderer('core_calendar');
531 $events = local_api::get_action_events_by_course(
532 $course,
533 $params['timesortfrom'],
534 $params['timesortto'],
535 $params['aftereventid'],
536 $params['limitnum']
539 $exportercache = new events_related_objects_cache($events, $courses);
540 $exporter = new events_exporter($events, ['cache' => $exportercache]);
542 return $exporter->export($renderer);
546 * Returns description of method result value.
548 * @return external_description
550 public static function get_calendar_action_events_by_course_returns() {
551 return events_exporter::get_read_structure();
555 * Returns description of method parameters.
557 * @return external_function_parameters
559 public static function get_calendar_action_events_by_courses_parameters() {
560 return new external_function_parameters(
561 array(
562 'courseids' => new external_multiple_structure(
563 new external_value(PARAM_INT, 'Course id')
565 'timesortfrom' => new external_value(PARAM_INT, 'Time sort from', VALUE_DEFAULT, null),
566 'timesortto' => new external_value(PARAM_INT, 'Time sort to', VALUE_DEFAULT, null),
567 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 10)
573 * Get calendar action events for a given list of courses.
575 * @since Moodle 3.3
576 * @param array $courseids Only include events for these courses
577 * @param null|int $timesortfrom Events after this time (inclusive)
578 * @param null|int $timesortto Events before this time (inclusive)
579 * @param int $limitnum Limit the number of results per course to this value
580 * @return array
582 public static function get_calendar_action_events_by_courses(
583 array $courseids, $timesortfrom = null, $timesortto = null, $limitnum = 10) {
585 global $CFG, $PAGE, $USER;
587 require_once($CFG->dirroot . '/calendar/lib.php');
589 $user = null;
590 $params = self::validate_parameters(
591 self::get_calendar_action_events_by_courses_parameters(),
593 'courseids' => $courseids,
594 'timesortfrom' => $timesortfrom,
595 'timesortto' => $timesortto,
596 'limitnum' => $limitnum,
599 $context = \context_user::instance($USER->id);
600 self::validate_context($context);
602 if (empty($params['courseids'])) {
603 return ['groupedbycourse' => []];
606 $renderer = $PAGE->get_renderer('core_calendar');
607 $courses = enrol_get_my_courses('*', null, 0, $params['courseids']);
608 $courses = array_values($courses);
610 if (empty($courses)) {
611 return ['groupedbycourse' => []];
614 $events = local_api::get_action_events_by_courses(
615 $courses,
616 $params['timesortfrom'],
617 $params['timesortto'],
618 $params['limitnum']
621 if (empty($events)) {
622 return ['groupedbycourse' => []];
625 $exportercache = new events_related_objects_cache($events, $courses);
626 $exporter = new events_grouped_by_course_exporter($events, ['cache' => $exportercache]);
628 return $exporter->export($renderer);
632 * Returns description of method result value.
634 * @return external_description
636 public static function get_calendar_action_events_by_courses_returns() {
637 return events_grouped_by_course_exporter::get_read_structure();
641 * Returns description of method parameters.
643 * @return external_function_parameters.
644 * @since Moodle 2.5
646 public static function create_calendar_events_parameters() {
647 // Userid is always current user, so no need to get it from client.
648 // Module based calendar events are not allowed here. Hence no need of instance and modulename.
649 // subscription id and uuid is not allowed as this is not an ical api.
650 return new external_function_parameters(
651 array('events' => new external_multiple_structure(
652 new external_single_structure(
653 array(
654 'name' => new external_value(PARAM_TEXT, 'event name', VALUE_REQUIRED, '', NULL_NOT_ALLOWED),
655 'description' => new external_value(PARAM_RAW, 'Description', VALUE_DEFAULT, null, NULL_ALLOWED),
656 'format' => new external_format_value('description', VALUE_DEFAULT),
657 'courseid' => new external_value(PARAM_INT, 'course id', VALUE_DEFAULT, 0, NULL_NOT_ALLOWED),
658 'groupid' => new external_value(PARAM_INT, 'group id', VALUE_DEFAULT, 0, NULL_NOT_ALLOWED),
659 'repeats' => new external_value(PARAM_INT, 'number of repeats', VALUE_DEFAULT, 0, NULL_NOT_ALLOWED),
660 'eventtype' => new external_value(PARAM_TEXT, 'Event type', VALUE_DEFAULT, 'user', NULL_NOT_ALLOWED),
661 'timestart' => new external_value(PARAM_INT, 'timestart', VALUE_DEFAULT, time(), NULL_NOT_ALLOWED),
662 'timeduration' => new external_value(PARAM_INT, 'time duration', VALUE_DEFAULT, 0, NULL_NOT_ALLOWED),
663 'visible' => new external_value(PARAM_INT, 'visible', VALUE_DEFAULT, 1, NULL_NOT_ALLOWED),
664 'sequence' => new external_value(PARAM_INT, 'sequence', VALUE_DEFAULT, 1, NULL_NOT_ALLOWED),
665 ), 'event')
672 * Delete Calendar events.
674 * @param array $events A list of events to create.
675 * @return array array of events created.
676 * @since Moodle 2.5
677 * @throws moodle_exception if user doesnt have the permission to create events.
679 public static function create_calendar_events($events) {
680 global $CFG, $DB, $USER;
681 require_once($CFG->dirroot."/calendar/lib.php");
683 // Parameter validation.
684 $params = self::validate_parameters(self::create_calendar_events_parameters(), array('events' => $events));
686 $transaction = $DB->start_delegated_transaction();
687 $return = array();
688 $warnings = array();
690 foreach ($params['events'] as $event) {
692 // Let us set some defaults.
693 $event['userid'] = $USER->id;
694 $event['modulename'] = '';
695 $event['instance'] = 0;
696 $event['subscriptionid'] = null;
697 $event['uuid']= '';
698 $event['format'] = external_validate_format($event['format']);
699 if ($event['repeats'] > 0) {
700 $event['repeat'] = 1;
701 } else {
702 $event['repeat'] = 0;
705 $eventobj = new calendar_event($event);
707 // Let's check if the user is allowed to delete an event.
708 if (!calendar_add_event_allowed($eventobj)) {
709 $warnings [] = array('item' => $event['name'], 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to create this event');
710 continue;
712 // Let's create the event.
713 $var = $eventobj->create($event);
714 $var = (array)$var->properties();
715 if ($event['repeat']) {
716 $children = $DB->get_records('event', array('repeatid' => $var['id']));
717 foreach ($children as $child) {
718 $return[] = (array) $child;
720 } else {
721 $return[] = $var;
725 // Everything done smoothly, let's commit.
726 $transaction->allow_commit();
727 return array('events' => $return, 'warnings' => $warnings);
731 * Returns description of method result value.
733 * @return external_description.
734 * @since Moodle 2.5
736 public static function create_calendar_events_returns() {
737 return new external_single_structure(
738 array(
739 'events' => new external_multiple_structure( new external_single_structure(
740 array(
741 'id' => new external_value(PARAM_INT, 'event id'),
742 'name' => new external_value(PARAM_TEXT, 'event name'),
743 'description' => new external_value(PARAM_RAW, 'Description', VALUE_OPTIONAL),
744 'format' => new external_format_value('description'),
745 'courseid' => new external_value(PARAM_INT, 'course id'),
746 'groupid' => new external_value(PARAM_INT, 'group id'),
747 'userid' => new external_value(PARAM_INT, 'user id'),
748 'repeatid' => new external_value(PARAM_INT, 'repeat id', VALUE_OPTIONAL),
749 'modulename' => new external_value(PARAM_TEXT, 'module name', VALUE_OPTIONAL),
750 'instance' => new external_value(PARAM_INT, 'instance id'),
751 'eventtype' => new external_value(PARAM_TEXT, 'Event type'),
752 'timestart' => new external_value(PARAM_INT, 'timestart'),
753 'timeduration' => new external_value(PARAM_INT, 'time duration'),
754 'visible' => new external_value(PARAM_INT, 'visible'),
755 'uuid' => new external_value(PARAM_TEXT, 'unique id of ical events', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
756 'sequence' => new external_value(PARAM_INT, 'sequence'),
757 'timemodified' => new external_value(PARAM_INT, 'time modified'),
758 'subscriptionid' => new external_value(PARAM_INT, 'Subscription id', VALUE_OPTIONAL),
759 ), 'event')
761 'warnings' => new external_warnings()
767 * Returns description of method parameters.
769 * @return external_function_parameters
771 public static function get_calendar_event_by_id_parameters() {
772 return new external_function_parameters(
773 array(
774 'eventid' => new external_value(PARAM_INT, 'The event id to be retrieved'),
780 * Get calendar event by id.
782 * @param int $eventid The calendar event id to be retrieved.
783 * @return array Array of event details
785 public static function get_calendar_event_by_id($eventid) {
786 global $CFG, $PAGE, $USER;
787 require_once($CFG->dirroot."/calendar/lib.php");
789 $params = self::validate_parameters(self::get_calendar_event_by_id_parameters(), ['eventid' => $eventid]);
790 $context = \context_user::instance($USER->id);
792 self::validate_context($context);
793 $warnings = array();
795 $legacyevent = calendar_event::load($eventid);
796 // Must check we can see this event.
797 if (!calendar_view_event_allowed($legacyevent)) {
798 // We can't return a warning in this case because the event is not optional.
799 // We don't know the context for the event and it's not worth loading it.
800 $syscontext = context_system::instance();
801 throw new \required_capability_exception($syscontext, 'moodle/course:view', 'nopermission', '');
804 $legacyevent->count_repeats();
806 $eventmapper = event_container::get_event_mapper();
807 $event = $eventmapper->from_legacy_event_to_event($legacyevent);
809 $cache = new events_related_objects_cache([$event]);
810 $relatedobjects = [
811 'context' => $cache->get_context($event),
812 'course' => $cache->get_course($event),
815 $exporter = new event_exporter($event, $relatedobjects);
816 $renderer = $PAGE->get_renderer('core_calendar');
818 return array('event' => $exporter->export($renderer), 'warnings' => $warnings);
822 * Returns description of method result value
824 * @return external_description
826 public static function get_calendar_event_by_id_returns() {
827 $eventstructure = event_exporter::get_read_structure();
829 return new external_single_structure(array(
830 'event' => $eventstructure,
831 'warnings' => new external_warnings()
837 * Returns description of method parameters.
839 * @return external_function_parameters.
841 public static function submit_create_update_form_parameters() {
842 return new external_function_parameters(
844 'formdata' => new external_value(PARAM_RAW, 'The data from the event form'),
850 * Handles the event form submission.
852 * @param string $formdata The event form data in a URI encoded param string
853 * @return array The created or modified event
854 * @throws moodle_exception
856 public static function submit_create_update_form($formdata) {
857 global $CFG, $USER, $PAGE;
858 require_once($CFG->dirroot."/calendar/lib.php");
859 require_once($CFG->libdir."/filelib.php");
861 // Parameter validation.
862 $params = self::validate_parameters(self::submit_create_update_form_parameters(), ['formdata' => $formdata]);
863 $context = \context_user::instance($USER->id);
864 $data = [];
866 self::validate_context($context);
867 parse_str($params['formdata'], $data);
869 $eventtype = isset($data['eventtype']) ? $data['eventtype'] : null;
870 $coursekey = ($eventtype == 'group') ? 'groupcourseid' : 'courseid';
871 $courseid = (!empty($data[$coursekey])) ? $data[$coursekey] : null;
872 $editoroptions = \core_calendar\local\event\forms\create::build_editor_options($context);
873 $formoptions = ['editoroptions' => $editoroptions, 'courseid' => $courseid];
874 if ($courseid) {
875 require_once($CFG->libdir . '/grouplib.php');
876 $groupcoursedata = groups_get_course_data($courseid);
877 if (!empty($groupcoursedata->groups)) {
878 $formoptions['groups'] = [];
879 foreach ($groupcoursedata->groups as $groupid => $groupdata) {
880 $formoptions['groups'][$groupid] = $groupdata->name;
885 if (!empty($data['id'])) {
886 $eventid = clean_param($data['id'], PARAM_INT);
887 $legacyevent = calendar_event::load($eventid);
888 $legacyevent->count_repeats();
889 $formoptions['event'] = $legacyevent;
890 $mform = new update_event_form(null, $formoptions, 'post', '', null, true, $data);
891 } else {
892 $legacyevent = null;
893 $mform = new create_event_form(null, $formoptions, 'post', '', null, true, $data);
896 if ($validateddata = $mform->get_data()) {
897 $formmapper = new create_update_form_mapper();
898 $properties = $formmapper->from_data_to_event_properties($validateddata);
900 if (is_null($legacyevent)) {
901 $legacyevent = new \calendar_event($properties);
902 // Need to do this in order to initialise the description
903 // property which then triggers the update function below
904 // to set the appropriate default properties on the event.
905 $properties = $legacyevent->properties(true);
908 if (!calendar_edit_event_allowed($legacyevent, true)) {
909 print_error('nopermissiontoupdatecalendar');
912 $legacyevent->update($properties);
913 $eventcontext = $legacyevent->context;
915 file_remove_editor_orphaned_files($validateddata->description);
917 // Take any files added to the description draft file area and
918 // convert them into the proper event description file area. Also
919 // parse the description text and replace the URLs to the draft files
920 // with the @@PLUGIN_FILE@@ placeholder to be persisted in the DB.
921 $description = file_save_draft_area_files(
922 $validateddata->description['itemid'],
923 $eventcontext->id,
924 'calendar',
925 'event_description',
926 $legacyevent->id,
927 create_event_form::build_editor_options($eventcontext),
928 $validateddata->description['text']
931 // If draft files were found then we need to save the new
932 // description value.
933 if ($description != $validateddata->description['text']) {
934 $properties->id = $legacyevent->id;
935 $properties->description = $description;
936 $legacyevent->update($properties);
939 $eventmapper = event_container::get_event_mapper();
940 $event = $eventmapper->from_legacy_event_to_event($legacyevent);
941 $cache = new events_related_objects_cache([$event]);
942 $relatedobjects = [
943 'context' => $cache->get_context($event),
944 'course' => $cache->get_course($event),
946 $exporter = new event_exporter($event, $relatedobjects);
947 $renderer = $PAGE->get_renderer('core_calendar');
949 return [ 'event' => $exporter->export($renderer) ];
950 } else {
951 return [ 'validationerror' => true ];
956 * Returns description of method result value.
958 * @return external_description.
960 public static function submit_create_update_form_returns() {
961 $eventstructure = event_exporter::get_read_structure();
962 $eventstructure->required = VALUE_OPTIONAL;
964 return new external_single_structure(
965 array(
966 'event' => $eventstructure,
967 'validationerror' => new external_value(PARAM_BOOL, 'Invalid form data', VALUE_DEFAULT, false),
973 * Get data for the monthly calendar view.
975 * @param int $year The year to be shown
976 * @param int $month The month to be shown
977 * @param int $courseid The course to be included
978 * @param int $categoryid The category to be included
979 * @param bool $includenavigation Whether to include navigation
980 * @param bool $mini Whether to return the mini month view or not
981 * @return array
983 public static function get_calendar_monthly_view($year, $month, $courseid, $categoryid, $includenavigation, $mini) {
984 global $CFG, $DB, $USER, $PAGE;
985 require_once($CFG->dirroot."/calendar/lib.php");
987 // Parameter validation.
988 $params = self::validate_parameters(self::get_calendar_monthly_view_parameters(), [
989 'year' => $year,
990 'month' => $month,
991 'courseid' => $courseid,
992 'categoryid' => $categoryid,
993 'includenavigation' => $includenavigation,
994 'mini' => $mini,
997 $context = \context_user::instance($USER->id);
998 self::validate_context($context);
999 $PAGE->set_url('/calendar/');
1001 $type = \core_calendar\type_factory::get_calendar_instance();
1003 $time = $type->convert_to_timestamp($params['year'], $params['month'], 1);
1004 $calendar = \calendar_information::create($time, $params['courseid'], $params['categoryid']);
1005 self::validate_context($calendar->context);
1007 $view = $params['mini'] ? 'mini' : 'month';
1008 list($data, $template) = calendar_get_view($calendar, $view, $params['includenavigation']);
1010 return $data;
1014 * Returns description of method parameters.
1016 * @return external_function_parameters
1018 public static function get_calendar_monthly_view_parameters() {
1019 return new external_function_parameters(
1021 'year' => new external_value(PARAM_INT, 'Month to be viewed', VALUE_REQUIRED),
1022 'month' => new external_value(PARAM_INT, 'Year to be viewed', VALUE_REQUIRED),
1023 'courseid' => new external_value(PARAM_INT, 'Course being viewed', VALUE_DEFAULT, SITEID, NULL_ALLOWED),
1024 'categoryid' => new external_value(PARAM_INT, 'Category being viewed', VALUE_DEFAULT, null, NULL_ALLOWED),
1025 'includenavigation' => new external_value(
1026 PARAM_BOOL,
1027 'Whether to show course navigation',
1028 VALUE_DEFAULT,
1029 true,
1030 NULL_ALLOWED
1032 'mini' => new external_value(
1033 PARAM_BOOL,
1034 'Whether to return the mini month view or not',
1035 VALUE_DEFAULT,
1036 false,
1037 NULL_ALLOWED
1044 * Returns description of method result value.
1046 * @return external_description
1048 public static function get_calendar_monthly_view_returns() {
1049 return \core_calendar\external\month_exporter::get_read_structure();
1053 * Get data for the daily calendar view.
1055 * @param int $year The year to be shown
1056 * @param int $month The month to be shown
1057 * @param int $day The day to be shown
1058 * @param int $courseid The course to be included
1059 * @return array
1061 public static function get_calendar_day_view($year, $month, $day, $courseid, $categoryid) {
1062 global $CFG, $DB, $USER, $PAGE;
1063 require_once($CFG->dirroot."/calendar/lib.php");
1065 // Parameter validation.
1066 $params = self::validate_parameters(self::get_calendar_day_view_parameters(), [
1067 'year' => $year,
1068 'month' => $month,
1069 'day' => $day,
1070 'courseid' => $courseid,
1071 'categoryid' => $categoryid,
1074 $context = \context_user::instance($USER->id);
1075 self::validate_context($context);
1077 $type = \core_calendar\type_factory::get_calendar_instance();
1079 $time = $type->convert_to_timestamp($params['year'], $params['month'], $params['day']);
1080 $calendar = \calendar_information::create($time, $params['courseid'], $params['categoryid']);
1081 self::validate_context($calendar->context);
1083 list($data, $template) = calendar_get_view($calendar, 'day');
1085 return $data;
1089 * Returns description of method parameters.
1091 * @return external_function_parameters
1093 public static function get_calendar_day_view_parameters() {
1094 return new external_function_parameters(
1096 'year' => new external_value(PARAM_INT, 'Year to be viewed', VALUE_REQUIRED),
1097 'month' => new external_value(PARAM_INT, 'Month to be viewed', VALUE_REQUIRED),
1098 'day' => new external_value(PARAM_INT, 'Day to be viewed', VALUE_REQUIRED),
1099 'courseid' => new external_value(PARAM_INT, 'Course being viewed', VALUE_DEFAULT, SITEID, NULL_ALLOWED),
1100 'categoryid' => new external_value(PARAM_INT, 'Category being viewed', VALUE_DEFAULT, null, NULL_ALLOWED),
1106 * Returns description of method result value.
1108 * @return external_description
1110 public static function get_calendar_day_view_returns() {
1111 return \core_calendar\external\calendar_day_exporter::get_read_structure();
1116 * Returns description of method parameters.
1118 * @return external_function_parameters
1120 public static function update_event_start_day_parameters() {
1121 return new external_function_parameters(
1123 'eventid' => new external_value(PARAM_INT, 'Id of event to be updated', VALUE_REQUIRED),
1124 'daytimestamp' => new external_value(PARAM_INT, 'Timestamp for the new start day', VALUE_REQUIRED),
1130 * Change the start day for the given calendar event to the day that
1131 * corresponds with the provided timestamp.
1133 * The timestamp only needs to be anytime within the desired day as only
1134 * the date data is extracted from it.
1136 * The event's original time of day is maintained, only the date is shifted.
1138 * @param int $eventid Id of event to be updated
1139 * @param int $daytimestamp Timestamp for the new start day
1140 * @return array
1142 public static function update_event_start_day($eventid, $daytimestamp) {
1143 global $USER, $PAGE;
1145 // Parameter validation.
1146 $params = self::validate_parameters(self::update_event_start_day_parameters(), [
1147 'eventid' => $eventid,
1148 'daytimestamp' => $daytimestamp,
1151 $vault = event_container::get_event_vault();
1152 $mapper = event_container::get_event_mapper();
1153 $event = $vault->get_event_by_id($eventid);
1155 if (!$event) {
1156 throw new \moodle_exception('Unable to find event with id ' . $eventid);
1159 $legacyevent = $mapper->from_event_to_legacy_event($event);
1161 if (!calendar_edit_event_allowed($legacyevent, true)) {
1162 print_error('nopermissiontoupdatecalendar');
1165 self::validate_context($legacyevent->context);
1167 $newdate = usergetdate($daytimestamp);
1168 $startdatestring = implode('-', [$newdate['year'], $newdate['mon'], $newdate['mday']]);
1169 $startdate = new DateTimeImmutable($startdatestring);
1170 $event = local_api::update_event_start_day($event, $startdate);
1171 $cache = new events_related_objects_cache([$event]);
1172 $relatedobjects = [
1173 'context' => $cache->get_context($event),
1174 'course' => $cache->get_course($event),
1176 $exporter = new event_exporter($event, $relatedobjects);
1177 $renderer = $PAGE->get_renderer('core_calendar');
1179 return array('event' => $exporter->export($renderer));
1183 * Returns description of method result value.
1185 * @return external_description
1187 public static function update_event_start_day_returns() {
1188 return new external_single_structure(
1189 array(
1190 'event' => event_exporter::get_read_structure()
1196 * Get data for the monthly calendar view.
1198 * @param int $courseid The course to be included
1199 * @param int $categoryid The category to be included
1200 * @return array
1202 public static function get_calendar_upcoming_view($courseid, $categoryid) {
1203 global $CFG, $DB, $USER, $PAGE;
1204 require_once($CFG->dirroot."/calendar/lib.php");
1206 // Parameter validation.
1207 $params = self::validate_parameters(self::get_calendar_upcoming_view_parameters(), [
1208 'courseid' => $courseid,
1209 'categoryid' => $categoryid,
1212 $context = \context_user::instance($USER->id);
1213 self::validate_context($context);
1214 $PAGE->set_url('/calendar/');
1216 $calendar = \calendar_information::create(time(), $params['courseid'], $params['categoryid']);
1217 self::validate_context($calendar->context);
1219 list($data, $template) = calendar_get_view($calendar, 'upcoming');
1221 return $data;
1225 * Returns description of method parameters.
1227 * @return external_function_parameters
1229 public static function get_calendar_upcoming_view_parameters() {
1230 return new external_function_parameters(
1232 'courseid' => new external_value(PARAM_INT, 'Course being viewed', VALUE_DEFAULT, SITEID, NULL_ALLOWED),
1233 'categoryid' => new external_value(PARAM_INT, 'Category being viewed', VALUE_DEFAULT, null, NULL_ALLOWED),
1239 * Returns description of method result value.
1241 * @return external_description
1243 public static function get_calendar_upcoming_view_returns() {
1244 return \core_calendar\external\calendar_upcoming_exporter::get_read_structure();