ed623d0cd80fc1f3aa117c5327d81b98dc294a79
[moodle.git] / calendar / tests / externallib_test.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * External calendar functions unit tests
19  *
20  * @package    core_calendar
21  * @category   external
22  * @copyright  2012 Ankit Agarwal
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 defined('MOODLE_INTERNAL') || die();
28 global $CFG;
30 require_once($CFG->dirroot . '/webservice/tests/helpers.php');
32 /**
33  * External course functions unit tests
34  *
35  * @package    core_calendar
36  * @category   external
37  * @copyright  2012 Ankit Agarwal
38  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39  * @since Moodle 2.5
40  */
41 class core_calendar_externallib_testcase extends externallib_advanced_testcase {
43     /**
44      * Tests set up
45      */
46     protected function setUp() {
47         global $CFG;
48         require_once($CFG->dirroot . '/calendar/externallib.php');
49     }
51     /** Create calendar events or update them
52      * Set $prop->id, if you want to do an update instead of creating an new event
53      *
54      * @param string $name        Event title
55      * @param int    $userid      User id
56      * @param string $type        Event type
57      * @param int    $repeats     Number of repeated events to create
58      * @param int    $timestart   Time stamp of the event start
59      * @param mixed  $prop        List of event properties as array or object
60      * @return mixed              Event object or false;
61      * @since Moodle 2.5
62      */
64     public static function create_calendar_event($name, $userid = 0, $type = 'user', $repeats = 0, $timestart  = null, $prop = null) {
65         global $CFG, $DB, $SITE;
67         require_once("$CFG->dirroot/calendar/lib.php");
68         if (!empty($prop)) {
69             if (is_array($prop)) {
70                 $prop = (object)$prop;
71             }
72         } else {
73             $prop = new stdClass();
74         }
75         $prop->name = $name;
76         if (empty($prop->eventtype)) {
77             $prop->eventtype = $type;
78         }
79         if (empty($prop->repeats)) {
80             $prop->repeats = $repeats;
81         }
82         if (empty($prop->timestart)) {
83             $prop->timestart = time();
84         }
85         if (empty($prop->timeduration)) {
86             $prop->timeduration = 0;
87         }
88         if (empty($prop->timesort)) {
89             $prop->timesort = 0;
90         }
91         if (empty($prop->type)) {
92             $prop->type = CALENDAR_EVENT_TYPE_STANDARD;
93         }
94         if (empty($prop->repeats)) {
95             $prop->repeat = 0;
96         } else {
97             $prop->repeat = 1;
98         }
99         if (empty($prop->userid)) {
100             if (!empty($userid)) {
101                 $prop->userid = $userid;
102             } else {
103                 $prop->userid = 0;
104             }
105         }
106         if (!isset($prop->courseid)) {
107             $prop->courseid = $SITE->id;
108         }
110         // Determine event priority.
111         if ($prop->courseid == 0 && isset($prop->groupid) && $prop->groupid == 0 && !empty($prop->userid)) {
112             // User override event.
113             $prop->priority = CALENDAR_EVENT_USER_OVERRIDE_PRIORITY;
114         } else if ($prop->courseid != $SITE->id && !empty($prop->groupid)) {
115             // Group override event.
116             $priorityparams = ['courseid' => $prop->courseid, 'groupid' => $prop->groupid];
117             // Group override event with the highest priority.
118             $groupevents = $DB->get_records('event', $priorityparams, 'priority DESC', 'id, priority', 0, 1);
119             $priority = 1;
120             if (!empty($groupevents)) {
121                 $event = reset($groupevents);
122                 if (!empty($event->priority)) {
123                     $priority = $event->priority + 1;
124                 }
125             }
126             $prop->priority = $priority;
127         }
129         $event = new calendar_event($prop);
130         return $event->create($prop);
131     }
133     public function test_create_calendar_events () {
134         global $DB, $USER;
136         $this->setAdminUser();
137         $this->resetAfterTest();
138         $prevcount = count($DB->get_records("event"));
140         // Create a few events and do asserts.
141         $this->create_calendar_event('test', $USER->id);
142         $where = $DB->sql_compare_text('name') ." = ?";
143         $count = count($DB->get_records_select("event", $where, array('test')));
144         $this->assertEquals(1, $count);
145         $aftercount = count($DB->get_records("event"));
146         $this->assertEquals($prevcount + 1, $aftercount);
148         $this->create_calendar_event('user', $USER->id, 'user', 3);
149         $where = $DB->sql_compare_text('name') ." = ?";
150         $count = count($DB->get_records_select("event", $where, array('user')));
152         $this->assertEquals(3, $count);
153         $aftercount = count($DB->get_records("event"));
154         $this->assertEquals($prevcount + 4, $aftercount);
156     }
158     /**
159      * Test delete_calendar_events
160      *
161      * @expectedException moodle_exception
162      */
163     public function test_delete_calendar_events() {
164         global $DB, $USER;
166         $this->resetAfterTest(true);
167         $this->setAdminUser();
169         // Create a few stuff to test with.
170         $user = $this->getDataGenerator()->create_user();
171         $course = $this->getDataGenerator()->create_course();
172         $record = new stdClass();
173         $record->courseid = $course->id;
174         $group = $this->getDataGenerator()->create_group($record);
176         $notdeletedcount = $DB->count_records('event');
178         // Let's create a few events.
179         $siteevent = $this->create_calendar_event('site', $USER->id, 'site');
180         $record = new stdClass();
181         $record->courseid = $course->id;
182         $courseevent = $this->create_calendar_event('course', $USER->id, 'course', 2, time(), $record);
183         $userevent = $this->create_calendar_event('user', $USER->id);
184         $record = new stdClass();
185         $record->courseid = $course->id;
186         $record->groupid = $group->id;
187         $groupevent = $this->create_calendar_event('group', $USER->id, 'group', 0, time(), $record);
189         // Now lets try to delete stuff with proper rights.
190         $events = array(
191                 array('eventid' => $siteevent->id, 'repeat' => 0),
192                 array('eventid' => $courseevent->id, 'repeat' => 1),
193                 array('eventid' => $userevent->id, 'repeat' => 0),
194                 array('eventid' => $groupevent->id, 'repeat' => 0)
195                 );
196         core_calendar_external::delete_calendar_events($events);
198         // Check to see if things were deleted properly.
199         $deletedcount = $DB->count_records('event');
200         $this->assertEquals($notdeletedcount, $deletedcount);
202         // Let's create a few events.
203         $siteevent = $this->create_calendar_event('site', $USER->id, 'site');
204         $record = new stdClass();
205         $record->courseid = $course->id;
206         $courseevent = $this->create_calendar_event('course', $USER->id, 'course', 3, time(), $record);
207         $userevent = $this->create_calendar_event('user', $USER->id);
208         $record = new stdClass();
209         $record->courseid = $course->id;
210         $record->groupid = $group->id;
211         $groupevent = $this->create_calendar_event('group', $USER->id, 'group', 0, time(), $record);
213         $this->setuser($user);
214         $sitecontext = context_system::instance();
215         $coursecontext = context_course::instance($course->id);
216         $usercontext = context_user::instance($user->id);
217         $role = $DB->get_record('role', array('shortname' => 'student'));
218         $this->getDataGenerator()->enrol_user($user->id, $course->id, $role->id);
220         // Remove all caps.
221         $this->unassignUserCapability('moodle/calendar:manageentries', $sitecontext->id, $role->id);
222         $this->unassignUserCapability('moodle/calendar:manageentries', $coursecontext->id, $role->id);
223         $this->unassignUserCapability('moodle/calendar:managegroupentries', $coursecontext->id, $role->id);
224         $this->unassignUserCapability('moodle/calendar:manageownentries', $usercontext->id, $role->id);
226         // Assign proper caps and attempt delete.
227          $this->assignUserCapability('moodle/calendar:manageentries', $sitecontext->id, $role->id);
228          $events = array(
229                 array('eventid' => $siteevent->id, 'repeat' => 0),
230                 );
231         core_calendar_external::delete_calendar_events($events);
232         $deletedcount = $DB->count_records('event');
233         $count = $notdeletedcount+5;
234         $this->assertEquals($count, $deletedcount);
236          $this->assignUserCapability('moodle/calendar:manageentries', $sitecontext->id, $role->id);
237          $events = array(
238                 array('eventid' => $courseevent->id, 'repeat' => 0),
239                 );
240         core_calendar_external::delete_calendar_events($events);
241         $deletedcount = $DB->count_records('event');
242         $count = $notdeletedcount+4;
243         $this->assertEquals($count, $deletedcount);
245          $this->assignUserCapability('moodle/calendar:manageownentries', $usercontext->id, $role->id);
246          $events = array(
247                 array('eventid' => $userevent->id, 'repeat' => 0),
248                 );
249         core_calendar_external::delete_calendar_events($events);
250         $deletedcount = $DB->count_records('event');
251         $count = $notdeletedcount+3;
252         $this->assertEquals($count, $deletedcount);
254          $this->assignUserCapability('moodle/calendar:managegroupentries', $coursecontext->id, $role->id);
255          $events = array(
256                 array('eventid' => $groupevent->id, 'repeat' => 0),
257                 );
258         core_calendar_external::delete_calendar_events($events);
259         $deletedcount = $DB->count_records('event');
260         $count = $notdeletedcount+2;
261         $this->assertEquals($count, $deletedcount);
263         $notdeletedcount = $deletedcount;
265         // Let us try deleting without caps.
267         $siteevent = $this->create_calendar_event('site', $USER->id, 'site');
268         $record = new stdClass();
269         $record->courseid = $course->id;
270         $courseevent = $this->create_calendar_event('course', $USER->id, 'course', 3, time(), $record);
271         $userevent = $this->create_calendar_event('user', $USER->id);
272         $record = new stdClass();
273         $record->courseid = $course->id;
274         $record->groupid = $group->id;
275         $groupevent = $this->create_calendar_event('group', $USER->id, 'group', 0, time(), $record);
277         $this->setGuestUser();
279         $events = array(
280             array('eventid' => $siteevent->id, 'repeat' => 0),
281             array('eventid' => $courseevent->id, 'repeat' => 0),
282             array('eventid' => $userevent->id, 'repeat' => 0),
283             array('eventid' => $groupevent->id, 'repeat' => 0)
284         );
285         core_calendar_external::delete_calendar_events($events);
286     }
288     /**
289      * Test get_calendar_events
290      */
291     public function test_get_calendar_events() {
292         global $DB, $USER;
294         $this->resetAfterTest(true);
295         set_config('calendar_adminseesall', 1);
296         $this->setAdminUser();
298         // Create a few stuff to test with.
299         $user = $this->getDataGenerator()->create_user();
300         $user2 = $this->getDataGenerator()->create_user();
301         $course = $this->getDataGenerator()->create_course();
303         $category = $this->getDataGenerator()->create_category();
305         $category2 = $this->getDataGenerator()->create_category();
306         $category2b = $this->getDataGenerator()->create_category(['parent' => $category2->id]);
307         $course3 = $this->getDataGenerator()->create_course(['category' => $category2b->id]);
309         $role = $DB->get_record('role', array('shortname' => 'student'));
310         $this->getDataGenerator()->enrol_user($user2->id, $course3->id, $role->id);
312         $record = new stdClass();
313         $record->courseid = $course->id;
314         $group = $this->getDataGenerator()->create_group($record);
316         $beforecount = $DB->count_records('event');
318         // Let's create a few events.
319         $siteevent = $this->create_calendar_event('site', $USER->id, 'site');
321         // This event will have description with an inline fake image.
322         $draftidfile = file_get_unused_draft_itemid();
323         $usercontext = context_course::instance($course->id);
324         $filerecord = array(
325             'contextid' => $usercontext->id,
326             'component' => 'user',
327             'filearea'  => 'draft',
328             'itemid'    => $draftidfile,
329             'filepath'  => '/',
330             'filename'  => 'fakeimage.png',
331         );
332         $fs = get_file_storage();
333         $fs->create_file_from_string($filerecord, 'img contents');
335         $record = new stdClass();
336         $record->courseid = $course->id;
337         $record->groupid = 0;
338         $record->description = array(
339             'format' => FORMAT_HTML,
340             'text' => 'Text with img <img src="@@PLUGINFILE@@/fakeimage.png">',
341             'itemid' => $draftidfile
342         );
343         $courseevent = $this->create_calendar_event('course', $USER->id, 'course', 2, time(), $record);
345         $record = new stdClass();
346         $record->courseid = 0;
347         $record->groupid = 0;
348         $userevent = $this->create_calendar_event('user', $USER->id, 'user', 0, time(), $record);
350         $record = new stdClass();
351         $record->courseid = $course->id;
352         $record->groupid = $group->id;
353         $groupevent = $this->create_calendar_event('group', $USER->id, 'group', 0, time(), $record);
355         $paramevents = array ('eventids' => array($siteevent->id), 'courseids' => array($course->id),
356                 'groupids' => array($group->id), 'categoryids' => array($category->id));
358         $options = array ('siteevents' => true, 'userevents' => true);
359         $events = core_calendar_external::get_calendar_events($paramevents, $options);
360         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
362         // Check to see if we got all events.
363         $this->assertEquals(5, count($events['events']));
364         $this->assertEquals(0, count($events['warnings']));
365         $options = array ('siteevents' => true, 'userevents' => true, 'timeend' => time() + 7*WEEKSECS);
366         $events = core_calendar_external::get_calendar_events($paramevents, $options);
367         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
368         $this->assertEquals(5, count($events['events']));
369         $this->assertEquals(0, count($events['warnings']));
371         // Expect the same URL in the description of two different events (because they are repeated).
372         $coursecontext = context_course::instance($course->id);
373         $expectedurl = "webservice/pluginfile.php/$coursecontext->id/calendar/event_description/$courseevent->id/fakeimage.png";
374         $withdescription = 0;
375         foreach ($events['events'] as $event) {
376             if (!empty($event['description'])) {
377                 $withdescription++;
378                 $this->assertContains($expectedurl, $event['description']);
379             }
380         }
381         $this->assertEquals(2, $withdescription);
383         // Let's play around with caps.
385         // Create user event for the user $user.
386         $record = new stdClass();
387         $record->courseid = 0;
388         $record->groupid = 0;
389         $this->create_calendar_event('user', $user->id, 'user', 0, time(), $record);
391         $this->setUser($user);
392         $events = core_calendar_external::get_calendar_events($paramevents, $options);
393         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
394         $this->assertEquals(2, count($events['events'])); // site, user.
395         $this->assertEquals(2, count($events['warnings'])); // course, group.
397         $role = $DB->get_record('role', array('shortname' => 'student'));
398         $this->getDataGenerator()->enrol_user($user->id, $course->id, $role->id);
399         $events = core_calendar_external::get_calendar_events($paramevents, $options);
400         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
401         $this->assertEquals(4, count($events['events'])); // site, user, both course events.
402         $this->assertEquals(1, count($events['warnings'])); // group.
404         $options = array ('siteevents' => true, 'userevents' => true, 'timeend' => time() + HOURSECS);
405         $events = core_calendar_external::get_calendar_events($paramevents, $options);
406         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
407         $this->assertEquals(3, count($events['events'])); // site, user, one course event.
408         $this->assertEquals(1, count($events['warnings'])); // group.
410         groups_add_member($group, $user);
411         $events = core_calendar_external::get_calendar_events($paramevents, $options);
412         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
413         $this->assertEquals(4, count($events['events'])); // site, user, group, one course event.
414         $this->assertEquals(0, count($events['warnings']));
416         $paramevents = array ('courseids' => array($course->id), 'groupids' => array($group->id));
417         $events = core_calendar_external::get_calendar_events($paramevents, $options);
418         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
419         $this->assertEquals(4, count($events['events'])); // site, user, group, one course event.
420         $this->assertEquals(0, count($events['warnings']));
422         $paramevents = array ('groupids' => array($group->id, 23));
423         $events = core_calendar_external::get_calendar_events($paramevents, $options);
424         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
425         $this->assertEquals(3, count($events['events'])); // site, user, group.
426         $this->assertEquals(1, count($events['warnings']));
428         $paramevents = array ('courseids' => array(23));
429         $events = core_calendar_external::get_calendar_events($paramevents, $options);
430         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
431         $this->assertEquals(2, count($events['events'])); // site, user.
432         $this->assertEquals(1, count($events['warnings']));
434         $paramevents = array ();
435         $options = array ('siteevents' => false, 'userevents' => false, 'timeend' => time() + 7*WEEKSECS);
436         $events = core_calendar_external::get_calendar_events($paramevents, $options);
437         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
438         $this->assertEquals(0, count($events['events'])); // nothing returned.
439         $this->assertEquals(0, count($events['warnings']));
441         $paramevents = array ('eventids' => array($siteevent->id, $groupevent->id));
442         $options = array ('siteevents' => false, 'userevents' => false, 'timeend' => time() + 7*WEEKSECS);
443         $events = core_calendar_external::get_calendar_events($paramevents, $options);
444         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
445         $this->assertEquals(2, count($events['events'])); // site, group.
446         $this->assertEquals(0, count($events['warnings']));
448         $paramevents = array ('eventids' => array($siteevent->id));
449         $events = core_calendar_external::get_calendar_events($paramevents, $options);
450         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
451         $this->assertEquals(1, count($events['events'])); // site.
452         $this->assertEquals(0, count($events['warnings']));
454         // Try getting a course event by its id.
455         $paramevents = array ('eventids' => array($courseevent->id));
456         $events = core_calendar_external::get_calendar_events($paramevents, $options);
457         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
458         $this->assertEquals(1, count($events['events']));
459         $this->assertEquals(0, count($events['warnings']));
461         // Now, create an activity event.
462         $this->setAdminUser();
463         $nexttime = time() + DAYSECS;
464         $assign = $this->getDataGenerator()->create_module('assign', array('course' => $course->id, 'duedate' => $nexttime));
466         $this->setUser($user);
467         $paramevents = array ('courseids' => array($course->id));
468         $options = array ('siteevents' => true, 'userevents' => true, 'timeend' => time() + WEEKSECS);
469         $events = core_calendar_external::get_calendar_events($paramevents, $options);
470         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
472         $this->assertCount(5, $events['events']);
474         // Hide the assignment.
475         set_coursemodule_visible($assign->cmid, 0);
476         // Empty all the caches that may be affected  by this change.
477         accesslib_clear_all_caches_for_unit_testing();
478         course_modinfo::clear_instance_cache();
480         $events = core_calendar_external::get_calendar_events($paramevents, $options);
481         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
482         // Expect one less.
483         $this->assertCount(4, $events['events']);
485         // Create some category events.
486         $this->setAdminUser();
487         $record = new stdClass();
488         $record->courseid = 0;
489         $record->categoryid = $category->id;
490         $record->timestart = time() - DAYSECS;
491         $catevent1 = $this->create_calendar_event('category a', $USER->id, 'category', 0, time(), $record);
493         $record = new stdClass();
494         $record->courseid = 0;
495         $record->categoryid = $category2->id;
496         $record->timestart = time() + DAYSECS;
497         $catevent2 = $this->create_calendar_event('category b', $USER->id, 'category', 0, time(), $record);
499         // Now as student, make sure we get the events of the courses I am enrolled.
500         $this->setUser($user2);
501         $paramevents = array('categoryids' => array($category2b->id));
502         $options = array('timeend' => time() + 7 * WEEKSECS, 'userevents' => false, 'siteevents' => false);
503         $events = core_calendar_external::get_calendar_events($paramevents, $options);
504         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
506         // Should be just one, since there's just one category event of the course I am enrolled (course3 - cat2b).
507         $this->assertEquals(1, count($events['events']));
508         $this->assertEquals($catevent2->id, $events['events'][0]['id']);
509         $this->assertEquals($category2->id, $events['events'][0]['categoryid']);
510         $this->assertEquals(0, count($events['warnings']));
512         // Now get category events but by course (there aren't course events in the course).
513         $paramevents = array('courseids' => array($course3->id));
514         $options = array('timeend' => time() + 7 * WEEKSECS, 'userevents' => false, 'siteevents' => false);
515         $events = core_calendar_external::get_calendar_events($paramevents, $options);
516         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
517         $this->assertEquals(1, count($events['events']));
518         $this->assertEquals($catevent2->id, $events['events'][0]['id']);
519         $this->assertEquals(0, count($events['warnings']));
521         // Empty events in one where I'm not enrolled and one parent category
522         // (parent of a category where this is a course where the user is enrolled).
523         $paramevents = array('categoryids' => array($category2->id, $category->id));
524         $options = array('timeend' => time() + 7 * WEEKSECS, 'userevents' => false, 'siteevents' => false);
525         $events = core_calendar_external::get_calendar_events($paramevents, $options);
526         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
527         $this->assertEquals(1, count($events['events']));
528         $this->assertEquals($catevent2->id, $events['events'][0]['id']);
529         $this->assertEquals(0, count($events['warnings']));
531         // Admin can see all category events.
532         $this->setAdminUser();
533         $paramevents = array('categoryids' => array($category->id, $category2->id, $category2b->id));
534         $options = array('timeend' => time() + 7 * WEEKSECS, 'userevents' => false, 'siteevents' => false);
535         $events = core_calendar_external::get_calendar_events($paramevents, $options);
536         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
537         $this->assertEquals(2, count($events['events']));
538         $this->assertEquals(0, count($events['warnings']));
539         $this->assertEquals($catevent1->id, $events['events'][0]['id']);
540         $this->assertEquals($category->id, $events['events'][0]['categoryid']);
541         $this->assertEquals($catevent2->id, $events['events'][1]['id']);
542         $this->assertEquals($category2->id, $events['events'][1]['categoryid']);
543     }
545     /**
546      * Test core_calendar_external::create_calendar_events
547      */
548     public function test_core_create_calendar_events() {
549         global $DB, $USER, $SITE;
551         $this->resetAfterTest(true);
552         $this->setAdminUser();
554         // Create a few stuff to test with.
555         $user = $this->getDataGenerator()->create_user();
556         $course = $this->getDataGenerator()->create_course();
557         $record = new stdClass();
558         $record->courseid = $course->id;
559         $group = $this->getDataGenerator()->create_group($record);
561         $prevcount = $DB->count_records('event');
563         // Let's create a few events.
564         $events = array (
565                 array('name' => 'site', 'courseid' => $SITE->id, 'eventtype' => 'site'),
566                 array('name' => 'course', 'courseid' => $course->id, 'eventtype' => 'course', 'repeats' => 2),
567                 array('name' => 'group', 'courseid' => $course->id, 'groupid' => $group->id, 'eventtype' => 'group'),
568                 array('name' => 'user')
569                 );
570         $eventsret = core_calendar_external::create_calendar_events($events);
571         $eventsret = external_api::clean_returnvalue(core_calendar_external::create_calendar_events_returns(), $eventsret);
573         // Check to see if things were created properly.
574         $aftercount = $DB->count_records('event');
575         $this->assertEquals($prevcount + 5, $aftercount);
576         $this->assertEquals(5, count($eventsret['events']));
577         $this->assertEquals(0, count($eventsret['warnings']));
579         $sitecontext = context_system::instance();
580         $coursecontext = context_course::instance($course->id);
582         $this->setUser($user);
583         $prevcount = $aftercount;
584         $events = array (
585                 array('name' => 'course', 'courseid' => $course->id, 'eventtype' => 'course', 'repeats' => 2),
586                 array('name' => 'group', 'courseid' => $course->id, 'groupid' => $group->id, 'eventtype' => 'group'),
587                 array('name' => 'user')
588         );
589         $role = $DB->get_record('role', array('shortname' => 'student'));
590         $this->getDataGenerator()->enrol_user($user->id, $course->id, $role->id);
591         groups_add_member($group, $user);
592         $this->assignUserCapability('moodle/calendar:manageentries', $coursecontext->id, $role->id);
593         $this->assignUserCapability('moodle/calendar:managegroupentries', $coursecontext->id, $role->id);
594         $eventsret = core_calendar_external::create_calendar_events($events);
595         $eventsret = external_api::clean_returnvalue(core_calendar_external::create_calendar_events_returns(), $eventsret);
596         // Check to see if things were created properly.
597         $aftercount = $DB->count_records('event');
598         $this->assertEquals($prevcount + 4, $aftercount);
599         $this->assertEquals(4, count($eventsret['events']));
600         $this->assertEquals(0, count($eventsret['warnings']));
602         // Check to see nothing was created without proper permission.
603         $this->setGuestUser();
604         $prevcount = $DB->count_records('event');
605         $eventsret = core_calendar_external::create_calendar_events($events);
606         $eventsret = external_api::clean_returnvalue(core_calendar_external::create_calendar_events_returns(), $eventsret);
607         $aftercount = $DB->count_records('event');
608         $this->assertEquals($prevcount, $aftercount);
609         $this->assertEquals(0, count($eventsret['events']));
610         $this->assertEquals(3, count($eventsret['warnings']));
612         $this->setUser($user);
613         $this->unassignUserCapability('moodle/calendar:manageentries', $coursecontext->id, $role->id);
614         $this->unassignUserCapability('moodle/calendar:managegroupentries', $coursecontext->id, $role->id);
615         $prevcount = $DB->count_records('event');
616         $eventsret = core_calendar_external::create_calendar_events($events);
617         $eventsret = external_api::clean_returnvalue(core_calendar_external::create_calendar_events_returns(), $eventsret);
618         $aftercount = $DB->count_records('event');
619         $this->assertEquals($prevcount + 1, $aftercount); // User event.
620         $this->assertEquals(1, count($eventsret['events']));
621         $this->assertEquals(2, count($eventsret['warnings']));
622     }
624     /**
625      * Requesting calendar events from a given time should return all events with a sort
626      * time at or after the requested time. All events prior to that time should not
627      * be return.
628      *
629      * If there are no events on or after the given time then an empty result set should
630      * be returned.
631      */
632     public function test_get_calendar_action_events_by_timesort_after_time() {
633         $user = $this->getDataGenerator()->create_user();
634         $course = $this->getDataGenerator()->create_course();
635         $generator = $this->getDataGenerator()->get_plugin_generator('mod_assign');
636         $moduleinstance = $generator->create_instance(['course' => $course->id]);
638         $this->getDataGenerator()->enrol_user($user->id, $course->id);
639         $this->resetAfterTest(true);
640         $this->setUser($user);
642         $params = [
643             'type' => CALENDAR_EVENT_TYPE_ACTION,
644             'modulename' => 'assign',
645             'instance' => $moduleinstance->id,
646             'courseid' => $course->id,
647         ];
649         $event1 = $this->create_calendar_event('Event 1', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 1]));
650         $event2 = $this->create_calendar_event('Event 2', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 2]));
651         $event3 = $this->create_calendar_event('Event 3', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 3]));
652         $event4 = $this->create_calendar_event('Event 4', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 4]));
653         $event5 = $this->create_calendar_event('Event 5', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 5]));
654         $event6 = $this->create_calendar_event('Event 6', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 6]));
655         $event7 = $this->create_calendar_event('Event 7', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 7]));
656         $event8 = $this->create_calendar_event('Event 8', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 8]));
658         $result = core_calendar_external::get_calendar_action_events_by_timesort(5);
659         $result = external_api::clean_returnvalue(
660             core_calendar_external::get_calendar_action_events_by_timesort_returns(),
661             $result
662         );
663         $events = $result['events'];
665         $this->assertCount(4, $events);
666         $this->assertEquals('Event 5', $events[0]['name']);
667         $this->assertEquals('Event 6', $events[1]['name']);
668         $this->assertEquals('Event 7', $events[2]['name']);
669         $this->assertEquals('Event 8', $events[3]['name']);
670         $this->assertEquals($event5->id, $result['firstid']);
671         $this->assertEquals($event8->id, $result['lastid']);
673         $result = core_calendar_external::get_calendar_action_events_by_timesort(9);
674         $result = external_api::clean_returnvalue(
675             core_calendar_external::get_calendar_action_events_by_timesort_returns(),
676             $result
677         );
679         $this->assertEmpty($result['events']);
680         $this->assertNull($result['firstid']);
681         $this->assertNull($result['lastid']);
682     }
684     /**
685      * Requesting calendar events before a given time should return all events with a sort
686      * time at or before the requested time (inclusive). All events after that time
687      * should not be returned.
688      *
689      * If there are no events before the given time then an empty result set should be
690      * returned.
691      */
692     public function test_get_calendar_action_events_by_timesort_before_time() {
693         $user = $this->getDataGenerator()->create_user();
694         $course = $this->getDataGenerator()->create_course();
695         $generator = $this->getDataGenerator()->get_plugin_generator('mod_assign');
696         $moduleinstance = $generator->create_instance(['course' => $course->id]);
698         $this->getDataGenerator()->enrol_user($user->id, $course->id);
699         $this->resetAfterTest(true);
700         $this->setUser($user);
702         $params = [
703             'type' => CALENDAR_EVENT_TYPE_ACTION,
704             'modulename' => 'assign',
705             'instance' => $moduleinstance->id,
706             'courseid' => $course->id,
707         ];
709         $event1 = $this->create_calendar_event('Event 1', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 2]));
710         $event2 = $this->create_calendar_event('Event 2', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 3]));
711         $event3 = $this->create_calendar_event('Event 3', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 4]));
712         $event4 = $this->create_calendar_event('Event 4', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 5]));
713         $event5 = $this->create_calendar_event('Event 5', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 6]));
714         $event6 = $this->create_calendar_event('Event 6', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 7]));
715         $event7 = $this->create_calendar_event('Event 7', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 8]));
716         $event8 = $this->create_calendar_event('Event 8', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 9]));
718         $result = core_calendar_external::get_calendar_action_events_by_timesort(null, 5);
719         $result = external_api::clean_returnvalue(
720             core_calendar_external::get_calendar_action_events_by_timesort_returns(),
721             $result
722         );
723         $events = $result['events'];
725         $this->assertCount(4, $events);
726         $this->assertEquals('Event 1', $events[0]['name']);
727         $this->assertEquals('Event 2', $events[1]['name']);
728         $this->assertEquals('Event 3', $events[2]['name']);
729         $this->assertEquals('Event 4', $events[3]['name']);
730         $this->assertEquals($event1->id, $result['firstid']);
731         $this->assertEquals($event4->id, $result['lastid']);
733         $result = core_calendar_external::get_calendar_action_events_by_timesort(null, 1);
734         $result = external_api::clean_returnvalue(
735             core_calendar_external::get_calendar_action_events_by_timesort_returns(),
736             $result
737         );
739         $this->assertEmpty($result['events']);
740         $this->assertNull($result['firstid']);
741         $this->assertNull($result['lastid']);
742     }
744     /**
745      * Test retrieving event that was overridden for a user
746      */
747     public function test_get_calendar_events_override() {
748         $user = $this->getDataGenerator()->create_user();
749         $user2 = $this->getDataGenerator()->create_user();
750         $teacher = $this->getDataGenerator()->create_user();
751         $anotheruser = $this->getDataGenerator()->create_user();
752         $course = $this->getDataGenerator()->create_course();
753         $generator = $this->getDataGenerator()->get_plugin_generator('mod_assign');
754         $moduleinstance = $generator->create_instance(['course' => $course->id]);
756         $this->getDataGenerator()->enrol_user($user->id, $course->id, 'student');
757         $this->getDataGenerator()->enrol_user($user2->id, $course->id, 'student');
758         $this->getDataGenerator()->enrol_user($teacher->id, $course->id, 'editingteacher');
759         $this->resetAfterTest(true);
760         $this->setAdminUser();
762         $params = [
763             'type' => CALENDAR_EVENT_TYPE_ACTION,
764             'modulename' => 'assign',
765             'instance' => $moduleinstance->id,
766         ];
768         $now = time();
769         // Create two events - one for everybody in the course and one only for the first student.
770         $event1 = $this->create_calendar_event('Base event', 0, 'due', 0, $now + DAYSECS, $params + ['courseid' => $course->id]);
771         $event2 = $this->create_calendar_event('User event', $user->id, 'due', 0, $now + 2*DAYSECS, $params + ['courseid' => 0]);
773         // Retrieve course events for the second student - only one "Base event" is returned.
774         $this->setUser($user2);
775         $paramevents = array('courseids' => array($course->id));
776         $options = array ('siteevents' => true, 'userevents' => true);
777         $events = core_calendar_external::get_calendar_events($paramevents, $options);
778         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
779         $this->assertEquals(1, count($events['events']));
780         $this->assertEquals(0, count($events['warnings']));
781         $this->assertEquals('Base event', $events['events'][0]['name']);
783         // Retrieve events for the first student - both events are returned.
784         $this->setUser($user);
785         $events = core_calendar_external::get_calendar_events($paramevents, $options);
786         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
787         $this->assertEquals(2, count($events['events']));
788         $this->assertEquals(0, count($events['warnings']));
789         $this->assertEquals('Base event', $events['events'][0]['name']);
790         $this->assertEquals('User event', $events['events'][1]['name']);
792         // Retrieve events by id as a teacher, 'User event' should be returned since teacher has access to this course.
793         $this->setUser($teacher);
794         $paramevents = ['eventids' => [$event2->id]];
795         $events = core_calendar_external::get_calendar_events($paramevents, $options);
796         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
797         $this->assertEquals(1, count($events['events']));
798         $this->assertEquals(0, count($events['warnings']));
799         $this->assertEquals('User event', $events['events'][0]['name']);
801         // Retrieve events by id as another user, nothing should be returned.
802         $this->setUser($anotheruser);
803         $paramevents = ['eventids' => [$event2->id, $event1->id]];
804         $events = core_calendar_external::get_calendar_events($paramevents, $options);
805         $events = external_api::clean_returnvalue(core_calendar_external::get_calendar_events_returns(), $events);
806         $this->assertEquals(0, count($events['events']));
807         $this->assertEquals(0, count($events['warnings']));
808     }
810     /**
811      * Requesting calendar events within a given time range should return all events with
812      * a sort time between the lower and upper time bound (inclusive).
813      *
814      * If there are no events in the given time range then an empty result set should be
815      * returned.
816      */
817     public function test_get_calendar_action_events_by_timesort_time_range() {
818         $user = $this->getDataGenerator()->create_user();
819         $course = $this->getDataGenerator()->create_course();
820         $generator = $this->getDataGenerator()->get_plugin_generator('mod_assign');
821         $moduleinstance = $generator->create_instance(['course' => $course->id]);
823         $this->getDataGenerator()->enrol_user($user->id, $course->id);
824         $this->resetAfterTest(true);
825         $this->setUser($user);
827         $params = [
828             'type' => CALENDAR_EVENT_TYPE_ACTION,
829             'modulename' => 'assign',
830             'instance' => $moduleinstance->id,
831             'courseid' => $course->id,
832         ];
834         $event1 = $this->create_calendar_event('Event 1', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 1]));
835         $event2 = $this->create_calendar_event('Event 2', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 2]));
836         $event3 = $this->create_calendar_event('Event 3', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 3]));
837         $event4 = $this->create_calendar_event('Event 4', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 4]));
838         $event5 = $this->create_calendar_event('Event 5', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 5]));
839         $event6 = $this->create_calendar_event('Event 6', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 6]));
840         $event7 = $this->create_calendar_event('Event 7', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 7]));
841         $event8 = $this->create_calendar_event('Event 8', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 8]));
843         $result = core_calendar_external::get_calendar_action_events_by_timesort(3, 6);
844         $result = external_api::clean_returnvalue(
845             core_calendar_external::get_calendar_action_events_by_timesort_returns(),
846             $result
847         );
848         $events = $result['events'];
850         $this->assertCount(4, $events);
851         $this->assertEquals('Event 3', $events[0]['name']);
852         $this->assertEquals('Event 4', $events[1]['name']);
853         $this->assertEquals('Event 5', $events[2]['name']);
854         $this->assertEquals('Event 6', $events[3]['name']);
855         $this->assertEquals($event3->id, $result['firstid']);
856         $this->assertEquals($event6->id, $result['lastid']);
858         $result = core_calendar_external::get_calendar_action_events_by_timesort(10, 15);
859         $result = external_api::clean_returnvalue(
860             core_calendar_external::get_calendar_action_events_by_timesort_returns(),
861             $result
862         );
864         $this->assertEmpty($result['events']);
865         $this->assertNull($result['firstid']);
866         $this->assertNull($result['lastid']);
867     }
869     /**
870      * Requesting calendar events within a given time range and a limit and offset should return
871      * the number of events up to the given limit value that have a sort time between the lower
872      * and uppper time bound (inclusive) where the result set is shifted by the offset value.
873      *
874      * If there are no events in the given time range then an empty result set should be
875      * returned.
876      */
877     public function test_get_calendar_action_events_by_timesort_time_limit_offset() {
878         $user = $this->getDataGenerator()->create_user();
879         $course = $this->getDataGenerator()->create_course();
880         $generator = $this->getDataGenerator()->get_plugin_generator('mod_assign');
881         $moduleinstance = $generator->create_instance(['course' => $course->id]);
883         $this->getDataGenerator()->enrol_user($user->id, $course->id);
884         $this->resetAfterTest(true);
885         $this->setUser($user);
887         $params = [
888             'type' => CALENDAR_EVENT_TYPE_ACTION,
889             'modulename' => 'assign',
890             'instance' => $moduleinstance->id,
891             'courseid' => $course->id,
892         ];
894         $event1 = $this->create_calendar_event('Event 1', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 1]));
895         $event2 = $this->create_calendar_event('Event 2', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 2]));
896         $event3 = $this->create_calendar_event('Event 3', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 3]));
897         $event4 = $this->create_calendar_event('Event 4', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 4]));
898         $event5 = $this->create_calendar_event('Event 5', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 5]));
899         $event6 = $this->create_calendar_event('Event 6', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 6]));
900         $event7 = $this->create_calendar_event('Event 7', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 7]));
901         $event8 = $this->create_calendar_event('Event 8', $user->id, 'user', 0, 1, array_merge($params, ['timesort' => 8]));
903         $result = core_calendar_external::get_calendar_action_events_by_timesort(2, 7, $event3->id, 2);
904         $result = external_api::clean_returnvalue(
905             core_calendar_external::get_calendar_action_events_by_timesort_returns(),
906             $result
907         );
908         $events = $result['events'];
910         $this->assertCount(2, $events);
911         $this->assertEquals('Event 4', $events[0]['name']);
912         $this->assertEquals('Event 5', $events[1]['name']);
913         $this->assertEquals($event4->id, $result['firstid']);
914         $this->assertEquals($event5->id, $result['lastid']);
916         $result = core_calendar_external::get_calendar_action_events_by_timesort(2, 7, $event5->id, 2);
917         $result = external_api::clean_returnvalue(
918             core_calendar_external::get_calendar_action_events_by_timesort_returns(),
919             $result
920         );
921         $events = $result['events'];
923         $this->assertCount(2, $events);
924         $this->assertEquals('Event 6', $events[0]['name']);
925         $this->assertEquals('Event 7', $events[1]['name']);
926         $this->assertEquals($event6->id, $result['firstid']);
927         $this->assertEquals($event7->id, $result['lastid']);
929         $result = core_calendar_external::get_calendar_action_events_by_timesort(2, 7, $event7->id, 2);
930         $result = external_api::clean_returnvalue(
931             core_calendar_external::get_calendar_action_events_by_timesort_returns(),
932             $result
933         );
935         $this->assertEmpty($result['events']);
936         $this->assertNull($result['firstid']);
937         $this->assertNull($result['lastid']);
938     }
940     /**
941      * Requesting calendar events from a given course and time should return all
942      * events with a sort time at or after the requested time. All events prior
943      * to that time should not be return.
944      *
945      * If there are no events on or after the given time then an empty result set should
946      * be returned.
947      */
948     public function test_get_calendar_action_events_by_course_after_time() {
949         $user = $this->getDataGenerator()->create_user();
950         $course1 = $this->getDataGenerator()->create_course();
951         $course2 = $this->getDataGenerator()->create_course();
952         $generator = $this->getDataGenerator()->get_plugin_generator('mod_assign');
953         $instance1 = $generator->create_instance(['course' => $course1->id]);
954         $instance2 = $generator->create_instance(['course' => $course2->id]);
955         $records = [];
957         $this->getDataGenerator()->enrol_user($user->id, $course1->id);
958         $this->getDataGenerator()->enrol_user($user->id, $course2->id);
959         $this->resetAfterTest(true);
960         $this->setUser($user);
962         for ($i = 1; $i < 19; $i++) {
963             $courseid = ($i < 9) ? $course1->id : $course2->id;
964             $instance = ($i < 9) ? $instance1->id : $instance2->id;
965             $records[] = $this->create_calendar_event(
966                 sprintf('Event %d', $i),
967                 $user->id,
968                 'user',
969                 0,
970                 1,
971                 [
972                     'type' => CALENDAR_EVENT_TYPE_ACTION,
973                     'courseid' => $courseid,
974                     'timesort' => $i,
975                     'modulename' => 'assign',
976                     'instance' => $instance,
977                 ]
978             );
979         }
981         $result = core_calendar_external::get_calendar_action_events_by_course($course1->id, 5);
982         $result = external_api::clean_returnvalue(
983             core_calendar_external::get_calendar_action_events_by_course_returns(),
984             $result
985         );
986         $result = $result['events'];
988         $this->assertCount(4, $result);
989         $this->assertEquals('Event 5', $result[0]['name']);
990         $this->assertEquals('Event 6', $result[1]['name']);
991         $this->assertEquals('Event 7', $result[2]['name']);
992         $this->assertEquals('Event 8', $result[3]['name']);
994         $result = core_calendar_external::get_calendar_action_events_by_course($course1->id, 9);
995         $result = external_api::clean_returnvalue(
996             core_calendar_external::get_calendar_action_events_by_course_returns(),
997             $result
998         );
999         $result = $result['events'];
1001         $this->assertEmpty($result);
1002     }
1004     /**
1005      * Requesting calendar events for a course and before a given time should return
1006      * all events with a sort time at or before the requested time (inclusive). All
1007      * events after that time should not be returned.
1008      *
1009      * If there are no events before the given time then an empty result set should be
1010      * returned.
1011      */
1012     public function test_get_calendar_action_events_by_course_before_time() {
1013         $user = $this->getDataGenerator()->create_user();
1014         $course1 = $this->getDataGenerator()->create_course();
1015         $course2 = $this->getDataGenerator()->create_course();
1016         $generator = $this->getDataGenerator()->get_plugin_generator('mod_assign');
1017         $instance1 = $generator->create_instance(['course' => $course1->id]);
1018         $instance2 = $generator->create_instance(['course' => $course2->id]);
1019         $records = [];
1021         $this->getDataGenerator()->enrol_user($user->id, $course1->id);
1022         $this->getDataGenerator()->enrol_user($user->id, $course2->id);
1023         $this->resetAfterTest(true);
1024         $this->setUser($user);
1026         for ($i = 1; $i < 19; $i++) {
1027             $courseid = ($i < 9) ? $course1->id : $course2->id;
1028             $instance = ($i < 9) ? $instance1->id : $instance2->id;
1029             $records[] = $this->create_calendar_event(
1030                 sprintf('Event %d', $i),
1031                 $user->id,
1032                 'user',
1033                 0,
1034                 1,
1035                 [
1036                     'type' => CALENDAR_EVENT_TYPE_ACTION,
1037                     'courseid' => $courseid,
1038                     'timesort' => $i + 1,
1039                     'modulename' => 'assign',
1040                     'instance' => $instance,
1041                 ]
1042             );
1043         }
1045         $result = core_calendar_external::get_calendar_action_events_by_course($course1->id, null, 5);
1046         $result = external_api::clean_returnvalue(
1047             core_calendar_external::get_calendar_action_events_by_course_returns(),
1048             $result
1049         );
1050         $result = $result['events'];
1052         $this->assertCount(4, $result);
1053         $this->assertEquals('Event 1', $result[0]['name']);
1054         $this->assertEquals('Event 2', $result[1]['name']);
1055         $this->assertEquals('Event 3', $result[2]['name']);
1056         $this->assertEquals('Event 4', $result[3]['name']);
1058         $result = core_calendar_external::get_calendar_action_events_by_course($course1->id, null, 1);
1059         $result = external_api::clean_returnvalue(
1060             core_calendar_external::get_calendar_action_events_by_course_returns(),
1061             $result
1062         );
1063         $result = $result['events'];
1065         $this->assertEmpty($result);
1066     }
1068     /**
1069      * Requesting calendar events for a course and within a given time range should
1070      * return all events with a sort time between the lower and upper time bound
1071      * (inclusive).
1072      *
1073      * If there are no events in the given time range then an empty result set should be
1074      * returned.
1075      */
1076     public function test_get_calendar_action_events_by_course_time_range() {
1077         $user = $this->getDataGenerator()->create_user();
1078         $course1 = $this->getDataGenerator()->create_course();
1079         $course2 = $this->getDataGenerator()->create_course();
1080         $generator = $this->getDataGenerator()->get_plugin_generator('mod_assign');
1081         $instance1 = $generator->create_instance(['course' => $course1->id]);
1082         $instance2 = $generator->create_instance(['course' => $course2->id]);
1083         $records = [];
1085         $this->getDataGenerator()->enrol_user($user->id, $course1->id);
1086         $this->getDataGenerator()->enrol_user($user->id, $course2->id);
1087         $this->resetAfterTest(true);
1088         $this->setUser($user);
1090         for ($i = 1; $i < 19; $i++) {
1091             $courseid = ($i < 9) ? $course1->id : $course2->id;
1092             $instance = ($i < 9) ? $instance1->id : $instance2->id;
1093             $records[] = $this->create_calendar_event(
1094                 sprintf('Event %d', $i),
1095                 $user->id,
1096                 'user',
1097                 0,
1098                 1,
1099                 [
1100                     'type' => CALENDAR_EVENT_TYPE_ACTION,
1101                     'courseid' => $courseid,
1102                     'timesort' => $i,
1103                     'modulename' => 'assign',
1104                     'instance' => $instance,
1105                 ]
1106             );
1107         }
1109         $result = core_calendar_external::get_calendar_action_events_by_course($course1->id, 3, 6);
1110         $result = external_api::clean_returnvalue(
1111             core_calendar_external::get_calendar_action_events_by_course_returns(),
1112             $result
1113         );
1114         $result = $result['events'];
1116         $this->assertCount(4, $result);
1117         $this->assertEquals('Event 3', $result[0]['name']);
1118         $this->assertEquals('Event 4', $result[1]['name']);
1119         $this->assertEquals('Event 5', $result[2]['name']);
1120         $this->assertEquals('Event 6', $result[3]['name']);
1122         $result = core_calendar_external::get_calendar_action_events_by_course($course1->id, 10, 15);
1123         $result = external_api::clean_returnvalue(
1124             core_calendar_external::get_calendar_action_events_by_course_returns(),
1125             $result
1126         );
1127         $result = $result['events'];
1129         $this->assertEmpty($result);
1130     }
1132     /**
1133      * Requesting calendar events for a course and within a given time range and a limit
1134      * and offset should return the number of events up to the given limit value that have
1135      * a sort time between the lower and uppper time bound (inclusive) where the result
1136      * set is shifted by the offset value.
1137      *
1138      * If there are no events in the given time range then an empty result set should be
1139      * returned.
1140      */
1141     public function test_get_calendar_action_events_by_course_time_limit_offset() {
1142         $user = $this->getDataGenerator()->create_user();
1143         $course1 = $this->getDataGenerator()->create_course();
1144         $course2 = $this->getDataGenerator()->create_course();
1145         $generator = $this->getDataGenerator()->get_plugin_generator('mod_assign');
1146         $instance1 = $generator->create_instance(['course' => $course1->id]);
1147         $instance2 = $generator->create_instance(['course' => $course2->id]);
1148         $records = [];
1150         $this->getDataGenerator()->enrol_user($user->id, $course1->id);
1151         $this->getDataGenerator()->enrol_user($user->id, $course2->id);
1152         $this->resetAfterTest(true);
1153         $this->setUser($user);
1155         for ($i = 1; $i < 19; $i++) {
1156             $courseid = ($i < 9) ? $course1->id : $course2->id;
1157             $instance = ($i < 9) ? $instance1->id : $instance2->id;
1158             $records[] = $this->create_calendar_event(
1159                 sprintf('Event %d', $i),
1160                 $user->id,
1161                 'user',
1162                 0,
1163                 1,
1164                 [
1165                     'type' => CALENDAR_EVENT_TYPE_ACTION,
1166                     'courseid' => $courseid,
1167                     'timesort' => $i,
1168                     'modulename' => 'assign',
1169                     'instance' => $instance,
1170                 ]
1171             );
1172         }
1174         $result = core_calendar_external::get_calendar_action_events_by_course(
1175             $course1->id, 2, 7, $records[2]->id, 2);
1176         $result = external_api::clean_returnvalue(
1177             core_calendar_external::get_calendar_action_events_by_course_returns(),
1178             $result
1179         );
1180         $result = $result['events'];
1182         $this->assertCount(2, $result);
1183         $this->assertEquals('Event 4', $result[0]['name']);
1184         $this->assertEquals('Event 5', $result[1]['name']);
1186         $result = core_calendar_external::get_calendar_action_events_by_course(
1187             $course1->id, 2, 7, $records[4]->id, 2);
1188         $result = external_api::clean_returnvalue(
1189             core_calendar_external::get_calendar_action_events_by_course_returns(),
1190             $result
1191         );
1192         $result = $result['events'];
1194         $this->assertCount(2, $result);
1195         $this->assertEquals('Event 6', $result[0]['name']);
1196         $this->assertEquals('Event 7', $result[1]['name']);
1198         $result = core_calendar_external::get_calendar_action_events_by_course(
1199             $course1->id, 2, 7, $records[6]->id, 2);
1200         $result = external_api::clean_returnvalue(
1201             core_calendar_external::get_calendar_action_events_by_course_returns(),
1202             $result
1203         );
1204         $result = $result['events'];
1206         $this->assertEmpty($result);
1207     }
1209     /**
1210      * Test that get_action_events_by_courses will return a list of events for each
1211      * course you provided as long as the user is enrolled in the course.
1212      */
1213     public function test_get_action_events_by_courses() {
1214         $user = $this->getDataGenerator()->create_user();
1215         $course1 = $this->getDataGenerator()->create_course();
1216         $course2 = $this->getDataGenerator()->create_course();
1217         $course3 = $this->getDataGenerator()->create_course();
1218         $generator = $this->getDataGenerator()->get_plugin_generator('mod_assign');
1219         $instance1 = $generator->create_instance(['course' => $course1->id]);
1220         $instance2 = $generator->create_instance(['course' => $course2->id]);
1221         $instance3 = $generator->create_instance(['course' => $course3->id]);
1222         $records = [];
1223         $mapresult = function($result) {
1224             $groupedbycourse = [];
1225             foreach ($result['groupedbycourse'] as $group) {
1226                 $events = $group['events'];
1227                 $courseid = $group['courseid'];
1228                 $groupedbycourse[$courseid] = $events;
1229             }
1231             return $groupedbycourse;
1232         };
1234         $this->getDataGenerator()->enrol_user($user->id, $course1->id);
1235         $this->getDataGenerator()->enrol_user($user->id, $course2->id);
1236         $this->resetAfterTest(true);
1237         $this->setUser($user);
1239         for ($i = 1; $i < 10; $i++) {
1240             if ($i < 3) {
1241                 $courseid = $course1->id;
1242                 $instance = $instance1->id;
1243             } else if ($i < 6) {
1244                 $courseid = $course2->id;
1245                 $instance = $instance2->id;
1246             } else {
1247                 $courseid = $course3->id;
1248                 $instance = $instance3->id;
1249             }
1251             $records[] = $this->create_calendar_event(
1252                 sprintf('Event %d', $i),
1253                 $user->id,
1254                 'user',
1255                 0,
1256                 1,
1257                 [
1258                     'type' => CALENDAR_EVENT_TYPE_ACTION,
1259                     'courseid' => $courseid,
1260                     'timesort' => $i,
1261                     'modulename' => 'assign',
1262                     'instance' => $instance,
1263                 ]
1264             );
1265         }
1267         $result = core_calendar_external::get_calendar_action_events_by_courses([], 1);
1268         $result = external_api::clean_returnvalue(
1269             core_calendar_external::get_calendar_action_events_by_courses_returns(),
1270             $result
1271         );
1272         $result = $result['groupedbycourse'];
1274         $this->assertEmpty($result);
1276         $result = core_calendar_external::get_calendar_action_events_by_courses([$course1->id], 3);
1277         $result = external_api::clean_returnvalue(
1278             core_calendar_external::get_calendar_action_events_by_courses_returns(),
1279             $result
1280         );
1282         $groupedbycourse = $mapresult($result);
1284         $this->assertEmpty($groupedbycourse[$course1->id]);
1286         $result = core_calendar_external::get_calendar_action_events_by_courses([$course1->id], 1);
1287         $result = external_api::clean_returnvalue(
1288             core_calendar_external::get_calendar_action_events_by_courses_returns(),
1289             $result
1290         );
1291         $groupedbycourse = $mapresult($result);
1293         $this->assertCount(2, $groupedbycourse[$course1->id]);
1294         $this->assertEquals('Event 1', $groupedbycourse[$course1->id][0]['name']);
1295         $this->assertEquals('Event 2', $groupedbycourse[$course1->id][1]['name']);
1297         $result = core_calendar_external::get_calendar_action_events_by_courses(
1298             [$course1->id, $course2->id], 1);
1299         $result = external_api::clean_returnvalue(
1300             core_calendar_external::get_calendar_action_events_by_courses_returns(),
1301             $result
1302         );
1303         $groupedbycourse = $mapresult($result);
1305         $this->assertCount(2, $groupedbycourse[$course1->id]);
1306         $this->assertEquals('Event 1', $groupedbycourse[$course1->id][0]['name']);
1307         $this->assertEquals('Event 2', $groupedbycourse[$course1->id][1]['name']);
1308         $this->assertCount(3, $groupedbycourse[$course2->id]);
1309         $this->assertEquals('Event 3', $groupedbycourse[$course2->id][0]['name']);
1310         $this->assertEquals('Event 4', $groupedbycourse[$course2->id][1]['name']);
1311         $this->assertEquals('Event 5', $groupedbycourse[$course2->id][2]['name']);
1313         $result = core_calendar_external::get_calendar_action_events_by_courses(
1314             [$course1->id, $course2->id], 2, 4);
1315         $result = external_api::clean_returnvalue(
1316             core_calendar_external::get_calendar_action_events_by_courses_returns(),
1317             $result
1318         );
1319         $groupedbycourse = $mapresult($result);
1321         $this->assertCount(2, $groupedbycourse);
1322         $this->assertCount(1, $groupedbycourse[$course1->id]);
1323         $this->assertEquals('Event 2', $groupedbycourse[$course1->id][0]['name']);
1324         $this->assertCount(2, $groupedbycourse[$course2->id]);
1325         $this->assertEquals('Event 3', $groupedbycourse[$course2->id][0]['name']);
1326         $this->assertEquals('Event 4', $groupedbycourse[$course2->id][1]['name']);
1328         $result = core_calendar_external::get_calendar_action_events_by_courses(
1329             [$course1->id, $course2->id], 1, null, 1);
1330         $result = external_api::clean_returnvalue(
1331             core_calendar_external::get_calendar_action_events_by_courses_returns(),
1332             $result
1333         );
1334         $groupedbycourse = $mapresult($result);
1336         $this->assertCount(2, $groupedbycourse);
1337         $this->assertCount(1, $groupedbycourse[$course1->id]);
1338         $this->assertEquals('Event 1', $groupedbycourse[$course1->id][0]['name']);
1339         $this->assertCount(1, $groupedbycourse[$course2->id]);
1340         $this->assertEquals('Event 3', $groupedbycourse[$course2->id][0]['name']);
1341     }
1343     /**
1344      * Test for deleting module events.
1345      */
1346     public function test_delete_calendar_events_for_modules() {
1347         $this->resetAfterTest();
1348         $this->setAdminUser();
1349         $course = $this->getDataGenerator()->create_course();
1350         $nexttime = time() + DAYSECS;
1351         $this->getDataGenerator()->create_module('assign', ['course' => $course->id, 'duedate' => $nexttime]);
1352         $events = calendar_get_events(time(), $nexttime, true, true, true);
1353         $this->assertCount(1, $events);
1354         $params = [];
1355         foreach ($events as $event) {
1356             $params[] = [
1357                 'eventid' => $event->id,
1358                 'repeat' => false
1359             ];
1360         }
1362         $this->expectException('moodle_exception');
1363         core_calendar_external::delete_calendar_events($params);
1364     }
1366     /**
1367      * Updating the event start day should change the date value but leave
1368      * the time of day unchanged.
1369      */
1370     public function test_update_event_start_day() {
1371         $generator = $this->getDataGenerator();
1372         $user = $generator->create_user();
1373         $roleid = $generator->create_role();
1374         $context = \context_system::instance();
1375         $originalstarttime = new DateTimeImmutable('2017-01-1T15:00:00+08:00');
1376         $newstartdate = new DateTimeImmutable('2018-02-2T10:00:00+08:00');
1377         $expected = new DateTimeImmutable('2018-02-2T15:00:00+08:00');
1379         $generator->role_assign($roleid, $user->id, $context->id);
1380         assign_capability('moodle/calendar:manageownentries', CAP_ALLOW, $roleid, $context, true);
1382         $this->setUser($user);
1383         $this->resetAfterTest(true);
1385         $event = $this->create_calendar_event(
1386             'Test event',
1387             $user->id,
1388             'user',
1389             0,
1390             null,
1391             [
1392                 'courseid' => 0,
1393                 'timestart' => $originalstarttime->getTimestamp()
1394             ]
1395         );
1397         $result = core_calendar_external::update_event_start_day($event->id, $newstartdate->getTimestamp());
1398         $result = external_api::clean_returnvalue(
1399             core_calendar_external::update_event_start_day_returns(),
1400             $result
1401         );
1403         $this->assertEquals($expected->getTimestamp(), $result['event']['timestart']);
1404     }
1406     /**
1407      * A user should not be able to edit an event that they don't have
1408      * capabilities for.
1409      */
1410     public function test_update_event_start_day_no_permission() {
1411         $generator = $this->getDataGenerator();
1412         $user = $generator->create_user();
1413         $roleid = $generator->create_role();
1414         $context = \context_system::instance();
1415         $originalstarttime = new DateTimeImmutable('2017-01-1T15:00:00+08:00');
1416         $newstartdate = new DateTimeImmutable('2018-02-2T10:00:00+08:00');
1417         $expected = new DateTimeImmutable('2018-02-2T15:00:00+08:00');
1419         $generator->role_assign($roleid, $user->id, $context->id);
1420         assign_capability('moodle/calendar:manageownentries', CAP_ALLOW, $roleid, $context, true);
1422         $this->setUser($user);
1423         $this->resetAfterTest(true);
1425         $event = $this->create_calendar_event(
1426             'Test event',
1427             $user->id,
1428             'user',
1429             0,
1430             null,
1431             [
1432                 'courseid' => 0,
1433                 'timestart' => $originalstarttime->getTimestamp()
1434             ]
1435         );
1437         assign_capability('moodle/calendar:manageownentries', CAP_PROHIBIT, $roleid, $context, true);
1438         $this->expectException('moodle_exception');
1439         $result = core_calendar_external::update_event_start_day($event->id, $newstartdate->getTimestamp());
1440         $result = external_api::clean_returnvalue(
1441             core_calendar_external::update_event_start_day_returns(),
1442             $result
1443         );
1444     }
1446     /**
1447      * A user should not be able to update a module event.
1448      */
1449     public function test_update_event_start_day_module_event() {
1450         $generator = $this->getDataGenerator();
1451         $user = $generator->create_user();
1452         $course = $generator->create_course();
1453         $plugingenerator = $generator->get_plugin_generator('mod_assign');
1454         $moduleinstance = $plugingenerator->create_instance(['course' => $course->id]);
1455         $roleid = $generator->create_role();
1456         $context = \context_course::instance($course->id);
1457         $originalstarttime = new DateTimeImmutable('2017-01-1T15:00:00+08:00');
1458         $newstartdate = new DateTimeImmutable('2018-02-2T10:00:00+08:00');
1459         $expected = new DateTimeImmutable('2018-02-2T15:00:00+08:00');
1461         $generator->role_assign($roleid, $user->id, $context->id);
1462         $generator->enrol_user($user->id, $course->id);
1464         $this->setUser($user);
1465         $this->resetAfterTest(true);
1467         $event = $this->create_calendar_event(
1468             'Test event',
1469             $user->id,
1470             'user',
1471             0,
1472             null,
1473             [
1474                 'modulename' => 'assign',
1475                 'instance' => $moduleinstance->id,
1476                 'courseid' => $course->id,
1477                 'timestart' => $originalstarttime->getTimestamp()
1478             ]
1479         );
1481         assign_capability('moodle/calendar:manageentries', CAP_ALLOW, $roleid, $context, true);
1482         $this->expectException('moodle_exception');
1483         $result = core_calendar_external::update_event_start_day($event->id, $newstartdate->getTimestamp());
1484         $result = external_api::clean_returnvalue(
1485             core_calendar_external::update_event_start_day_returns(),
1486             $result
1487         );
1488     }
1490     /**
1491      * Submit a request where the time duration until is earlier than the time
1492      * start in order to get a validation error from the server.
1493      */
1494     public function test_submit_create_update_form_validation_error() {
1495         $user = $this->getDataGenerator()->create_user();
1496         $timestart = new DateTime();
1497         $interval = new DateInterval("P1D"); // One day.
1498         $timedurationuntil = new DateTime();
1499         $timedurationuntil->sub($interval);
1500         $formdata = [
1501             'id' => 0,
1502             'userid' => $user->id,
1503             'modulename' => '',
1504             'instance' => 0,
1505             'visible' => 1,
1506             'name' => 'Test',
1507             'timestart' => [
1508                 'day' => $timestart->format('j'),
1509                 'month' => $timestart->format('n'),
1510                 'year' => $timestart->format('Y'),
1511                 'hour' => $timestart->format('G'),
1512                 'minute' => 0,
1513             ],
1514             'eventtype' => 'user',
1515             'description' => [
1516                 'text' => '',
1517                 'format' => 1,
1518             ],
1519             'location' => 'Test',
1520             'duration' => 1,
1521             'timedurationuntil' => [
1522                 'day' => $timedurationuntil->format('j'),
1523                 'month' => $timedurationuntil->format('n'),
1524                 'year' => $timedurationuntil->format('Y'),
1525                 'hour' => $timedurationuntil->format('G'),
1526                 'minute' => 0,
1527             ]
1528         ];
1530         $formdata = \core_calendar\local\event\forms\create::mock_generate_submit_keys($formdata);
1532         $querystring = http_build_query($formdata, '', '&amp;');
1534         $this->resetAfterTest(true);
1535         $this->setUser($user);
1537         $result = external_api::clean_returnvalue(
1538             core_calendar_external::submit_create_update_form_returns(),
1539             core_calendar_external::submit_create_update_form($querystring)
1540         );
1542         $this->assertTrue($result['validationerror']);
1543     }
1545     /**
1546      * A user with the moodle/calendar:manageownentries capability at the
1547      * system context should be able to create a user event.
1548      */
1549     public function test_submit_create_update_form_create_user_event() {
1550         $generator = $this->getDataGenerator();
1551         $user = $generator->create_user();
1552         $roleid = $generator->create_role();
1553         $context = \context_system::instance();
1554         $timestart = new DateTime();
1555         $interval = new DateInterval("P1D"); // One day.
1556         $timedurationuntil = new DateTime();
1557         $timedurationuntil->add($interval);
1558         $formdata = [
1559             'id' => 0,
1560             'userid' => $user->id,
1561             'modulename' => '',
1562             'instance' => 0,
1563             'visible' => 1,
1564             'name' => 'Test',
1565             'timestart' => [
1566                 'day' => $timestart->format('j'),
1567                 'month' => $timestart->format('n'),
1568                 'year' => $timestart->format('Y'),
1569                 'hour' => $timestart->format('G'),
1570                 'minute' => 0,
1571             ],
1572             'eventtype' => 'user',
1573             'description' => [
1574                 'text' => '',
1575                 'format' => 1,
1576                 'itemid' => 0
1577             ],
1578             'location' => 'Test',
1579             'duration' => 1,
1580             'timedurationuntil' => [
1581                 'day' => $timedurationuntil->format('j'),
1582                 'month' => $timedurationuntil->format('n'),
1583                 'year' => $timedurationuntil->format('Y'),
1584                 'hour' => $timedurationuntil->format('G'),
1585                 'minute' => 0,
1586             ]
1587         ];
1589         $formdata = \core_calendar\local\event\forms\create::mock_generate_submit_keys($formdata);
1590         $querystring = http_build_query($formdata, '', '&');
1592         $generator->role_assign($roleid, $user->id, $context->id);
1593         assign_capability('moodle/calendar:manageownentries', CAP_ALLOW, $roleid, $context, true);
1595         $user->ignoresesskey = true;
1596         $this->resetAfterTest(true);
1597         $this->setUser($user);
1599         $result = external_api::clean_returnvalue(
1600             core_calendar_external::submit_create_update_form_returns(),
1601             core_calendar_external::submit_create_update_form($querystring)
1602         );
1604         $event = $result['event'];
1605         $this->assertEquals($user->id, $event['userid']);
1606         $this->assertEquals($formdata['eventtype'], $event['eventtype']);
1607         $this->assertEquals($formdata['name'], $event['name']);
1608     }
1610     /**
1611      * A user without the moodle/calendar:manageownentries capability at the
1612      * system context should not be able to create a user event.
1613      */
1614     public function test_submit_create_update_form_create_user_event_no_permission() {
1615         $generator = $this->getDataGenerator();
1616         $user = $generator->create_user();
1617         $roleid = $generator->create_role();
1618         $context = \context_system::instance();
1619         $timestart = new DateTime();
1620         $interval = new DateInterval("P1D"); // One day.
1621         $timedurationuntil = new DateTime();
1622         $timedurationuntil->add($interval);
1623         $formdata = [
1624             'id' => 0,
1625             'userid' => $user->id,
1626             'modulename' => '',
1627             'instance' => 0,
1628             'visible' => 1,
1629             'name' => 'Test',
1630             'timestart' => [
1631                 'day' => $timestart->format('j'),
1632                 'month' => $timestart->format('n'),
1633                 'year' => $timestart->format('Y'),
1634                 'hour' => $timestart->format('G'),
1635                 'minute' => 0,
1636             ],
1637             'eventtype' => 'user',
1638             'description' => [
1639                 'text' => '',
1640                 'format' => 1,
1641             ],
1642             'location' => 'Test',
1643             'duration' => 1,
1644             'timedurationuntil' => [
1645                 'day' => $timedurationuntil->format('j'),
1646                 'month' => $timedurationuntil->format('n'),
1647                 'year' => $timedurationuntil->format('Y'),
1648                 'hour' => $timedurationuntil->format('G'),
1649                 'minute' => 0,
1650             ]
1651         ];
1653         $formdata = \core_calendar\local\event\forms\create::mock_generate_submit_keys($formdata);
1654         $querystring = http_build_query($formdata, '', '&');
1656         $generator->role_assign($roleid, $user->id, $context->id);
1657         assign_capability('moodle/calendar:manageownentries', CAP_PROHIBIT, $roleid, $context, true);
1659         $user->ignoresesskey = true;
1660         $this->resetAfterTest(true);
1661         $this->setUser($user);
1663         $this->expectException('moodle_exception');
1665         external_api::clean_returnvalue(
1666             core_calendar_external::submit_create_update_form_returns(),
1667             core_calendar_external::submit_create_update_form($querystring)
1668         );
1669     }
1671     /**
1672      * A user with the moodle/calendar:manageentries capability at the
1673      * site course context should be able to create a site event.
1674      */
1675     public function test_submit_create_update_form_create_site_event() {
1676         $generator = $this->getDataGenerator();
1677         $user = $generator->create_user();
1678         $context = context_system::instance();
1679         $roleid = $generator->create_role();
1680         $timestart = new DateTime();
1681         $interval = new DateInterval("P1D"); // One day.
1682         $timedurationuntil = new DateTime();
1683         $timedurationuntil->add($interval);
1684         $formdata = [
1685             'id' => 0,
1686             'userid' => $user->id,
1687             'modulename' => '',
1688             'instance' => 0,
1689             'visible' => 1,
1690             'name' => 'Test',
1691             'timestart' => [
1692                 'day' => $timestart->format('j'),
1693                 'month' => $timestart->format('n'),
1694                 'year' => $timestart->format('Y'),
1695                 'hour' => $timestart->format('G'),
1696                 'minute' => 0,
1697             ],
1698             'eventtype' => 'site',
1699             'description' => [
1700                 'text' => '',
1701                 'format' => 1,
1702                 'itemid' => 0
1703             ],
1704             'location' => 'Test',
1705             'duration' => 1,
1706             'timedurationuntil' => [
1707                 'day' => $timedurationuntil->format('j'),
1708                 'month' => $timedurationuntil->format('n'),
1709                 'year' => $timedurationuntil->format('Y'),
1710                 'hour' => $timedurationuntil->format('G'),
1711                 'minute' => 0,
1712             ]
1713         ];
1715         $formdata = \core_calendar\local\event\forms\create::mock_generate_submit_keys($formdata);
1716         $querystring = http_build_query($formdata, '', '&');
1718         $generator->role_assign($roleid, $user->id, $context->id);
1720         assign_capability('moodle/calendar:manageentries', CAP_ALLOW, $roleid, $context, true);
1722         $user->ignoresesskey = true;
1723         $this->resetAfterTest(true);
1724         $this->setUser($user);
1726         $result = external_api::clean_returnvalue(
1727             core_calendar_external::submit_create_update_form_returns(),
1728             core_calendar_external::submit_create_update_form($querystring)
1729         );
1731         $event = $result['event'];
1732         $this->assertEquals($user->id, $event['userid']);
1733         $this->assertEquals($formdata['eventtype'], $event['eventtype']);
1734         $this->assertEquals($formdata['name'], $event['name']);
1735     }
1737     /**
1738      * A user without the moodle/calendar:manageentries capability at the
1739      * site course context should not be able to create a site event.
1740      */
1741     public function test_submit_create_update_form_create_site_event_no_permission() {
1742         $generator = $this->getDataGenerator();
1743         $user = $generator->create_user();
1744         $context = context_course::instance(SITEID);
1745         $roleid = $generator->create_role();
1746         $timestart = new DateTime();
1747         $interval = new DateInterval("P1D"); // One day.
1748         $timedurationuntil = new DateTime();
1749         $timedurationuntil->add($interval);
1750         $formdata = [
1751             'id' => 0,
1752             'userid' => $user->id,
1753             'modulename' => '',
1754             'instance' => 0,
1755             'visible' => 1,
1756             'name' => 'Test',
1757             'timestart' => [
1758                 'day' => $timestart->format('j'),
1759                 'month' => $timestart->format('n'),
1760                 'year' => $timestart->format('Y'),
1761                 'hour' => $timestart->format('G'),
1762                 'minute' => 0,
1763             ],
1764             'eventtype' => 'site',
1765             'description' => [
1766                 'text' => '',
1767                 'format' => 1,
1768             ],
1769             'location' => 'Test',
1770             'duration' => 1,
1771             'timedurationuntil' => [
1772                 'day' => $timedurationuntil->format('j'),
1773                 'month' => $timedurationuntil->format('n'),
1774                 'year' => $timedurationuntil->format('Y'),
1775                 'hour' => $timedurationuntil->format('G'),
1776                 'minute' => 0,
1777             ]
1778         ];
1780         $formdata = \core_calendar\local\event\forms\create::mock_generate_submit_keys($formdata);
1781         $querystring = http_build_query($formdata, '', '&');
1783         $generator->role_assign($roleid, $user->id, $context->id);
1785         assign_capability('moodle/calendar:manageentries', CAP_PROHIBIT, $roleid, $context, true);
1787         $user->ignoresesskey = true;
1788         $this->resetAfterTest(true);
1789         $this->setUser($user);
1791         $result = external_api::clean_returnvalue(
1792             core_calendar_external::submit_create_update_form_returns(),
1793             core_calendar_external::submit_create_update_form($querystring)
1794         );
1796         $this->assertTrue($result['validationerror']);
1797     }
1799     /**
1800      * A user that has the moodle/calendar:manageentries in a course that they
1801      * are enrolled in should be able to create a course event in that course.
1802      */
1803     public function test_submit_create_update_form_create_course_event() {
1804         $generator = $this->getDataGenerator();
1805         $user = $generator->create_user();
1806         $course = $generator->create_course();
1807         $context = context_course::instance($course->id);
1808         $roleid = $generator->create_role();
1809         $timestart = new DateTime();
1810         $interval = new DateInterval("P1D"); // One day.
1811         $timedurationuntil = new DateTime();
1812         $timedurationuntil->add($interval);
1813         $formdata = [
1814             'id' => 0,
1815             'userid' => $user->id,
1816             'modulename' => '',
1817             'instance' => 0,
1818             'visible' => 1,
1819             'name' => 'Test',
1820             'timestart' => [
1821                 'day' => $timestart->format('j'),
1822                 'month' => $timestart->format('n'),
1823                 'year' => $timestart->format('Y'),
1824                 'hour' => $timestart->format('G'),
1825                 'minute' => 0,
1826             ],
1827             'eventtype' => 'course',
1828             'courseid' => $course->id,
1829             'description' => [
1830                 'text' => '',
1831                 'format' => 1,
1832                 'itemid' => 0,
1833             ],
1834             'location' => 'Test',
1835             'duration' => 1,
1836             'timedurationuntil' => [
1837                 'day' => $timedurationuntil->format('j'),
1838                 'month' => $timedurationuntil->format('n'),
1839                 'year' => $timedurationuntil->format('Y'),
1840                 'hour' => $timedurationuntil->format('G'),
1841                 'minute' => 0,
1842             ]
1843         ];
1845         $formdata = \core_calendar\local\event\forms\create::mock_generate_submit_keys($formdata);
1846         $querystring = http_build_query($formdata, '', '&');
1848         $generator->enrol_user($user->id, $course->id, 'student');
1849         $generator->role_assign($roleid, $user->id, $context->id);
1851         assign_capability('moodle/calendar:manageentries', CAP_ALLOW, $roleid, $context, true);
1853         $user->ignoresesskey = true;
1854         $this->resetAfterTest(true);
1855         $this->setUser($user);
1857         $result = external_api::clean_returnvalue(
1858             core_calendar_external::submit_create_update_form_returns(),
1859             core_calendar_external::submit_create_update_form($querystring)
1860         );
1862         $event = $result['event'];
1863         $this->assertEquals($user->id, $event['userid']);
1864         $this->assertEquals($formdata['eventtype'], $event['eventtype']);
1865         $this->assertEquals($formdata['name'], $event['name']);
1866         $this->assertEquals($formdata['courseid'], $event['course']['id']);
1867     }
1869     /**
1870      * A user without the moodle/calendar:manageentries capability in a course
1871      * that they are enrolled in should not be able to create a course event in that course.
1872      */
1873     public function test_submit_create_update_form_create_course_event_no_permission() {
1874         $generator = $this->getDataGenerator();
1875         $user = $generator->create_user();
1876         $course = $generator->create_course();
1877         $context = context_course::instance($course->id);
1878         $roleid = $generator->create_role();
1879         $timestart = new DateTime();
1880         $interval = new DateInterval("P1D"); // One day.
1881         $timedurationuntil = new DateTime();
1882         $timedurationuntil->add($interval);
1883         $formdata = [
1884             'id' => 0,
1885             'userid' => $user->id,
1886             'modulename' => '',
1887             'instance' => 0,
1888             'visible' => 1,
1889             'name' => 'Test',
1890             'timestart' => [
1891                 'day' => $timestart->format('j'),
1892                 'month' => $timestart->format('n'),
1893                 'year' => $timestart->format('Y'),
1894                 'hour' => $timestart->format('G'),
1895                 'minute' => 0,
1896             ],
1897             'eventtype' => 'course',
1898             'courseid' => $course->id,
1899             'description' => [
1900                 'text' => '',
1901                 'format' => 1,
1902             ],
1903             'location' => 'Test',
1904             'duration' => 1,
1905             'timedurationuntil' => [
1906                 'day' => $timedurationuntil->format('j'),
1907                 'month' => $timedurationuntil->format('n'),
1908                 'year' => $timedurationuntil->format('Y'),
1909                 'hour' => $timedurationuntil->format('G'),
1910                 'minute' => 0,
1911             ]
1912         ];
1914         $formdata = \core_calendar\local\event\forms\create::mock_generate_submit_keys($formdata);
1915         $querystring = http_build_query($formdata, '', '&');
1917         $generator->enrol_user($user->id, $course->id, 'student');
1918         $generator->role_assign($roleid, $user->id, $context->id);
1920         assign_capability('moodle/calendar:manageentries', CAP_PROHIBIT, $roleid, $context, true);
1922         $user->ignoresesskey = true;
1923         $this->resetAfterTest(true);
1924         $this->setUser($user);
1926         $result = external_api::clean_returnvalue(
1927             core_calendar_external::submit_create_update_form_returns(),
1928             core_calendar_external::submit_create_update_form($querystring)
1929         );
1931         $this->assertTrue($result['validationerror']);
1932     }
1934     /**
1935      * A user should not be able to create an event for a course that they are
1936      * not enrolled in.
1937      */
1938     public function test_submit_create_update_form_create_course_event_not_enrolled() {
1939         $generator = $this->getDataGenerator();
1940         $user = $generator->create_user();
1941         $course = $generator->create_course();
1942         $course2 = $generator->create_course();
1943         $context = context_course::instance($course->id);
1944         $roleid = $generator->create_role();
1945         $timestart = new DateTime();
1946         $interval = new DateInterval("P1D"); // One day.
1947         $timedurationuntil = new DateTime();
1948         $timedurationuntil->add($interval);
1949         $formdata = [
1950             'id' => 0,
1951             'userid' => $user->id,
1952             'modulename' => '',
1953             'instance' => 0,
1954             'visible' => 1,
1955             'name' => 'Test',
1956             'timestart' => [
1957                 'day' => $timestart->format('j'),
1958                 'month' => $timestart->format('n'),
1959                 'year' => $timestart->format('Y'),
1960                 'hour' => $timestart->format('G'),
1961                 'minute' => 0,
1962             ],
1963             'eventtype' => 'course',
1964             'courseid' => $course2->id, // Not enrolled.
1965             'description' => [
1966                 'text' => '',
1967                 'format' => 1,
1968             ],
1969             'location' => 'Test',
1970             'duration' => 1,
1971             'timedurationuntil' => [
1972                 'day' => $timedurationuntil->format('j'),
1973                 'month' => $timedurationuntil->format('n'),
1974                 'year' => $timedurationuntil->format('Y'),
1975                 'hour' => $timedurationuntil->format('G'),
1976                 'minute' => 0,
1977             ]
1978         ];
1980         $formdata = \core_calendar\local\event\forms\create::mock_generate_submit_keys($formdata);
1981         $querystring = http_build_query($formdata, '', '&');
1983         $generator->enrol_user($user->id, $course->id, 'student');
1984         $generator->role_assign($roleid, $user->id, $context->id);
1986         assign_capability('moodle/calendar:manageentries', CAP_ALLOW, $roleid, $context, true);
1988         $user->ignoresesskey = true;
1989         $this->resetAfterTest(true);
1990         $this->setUser($user);
1992         $result = external_api::clean_returnvalue(
1993             core_calendar_external::submit_create_update_form_returns(),
1994             core_calendar_external::submit_create_update_form($querystring)
1995         );
1997         $this->assertTrue($result['validationerror']);
1998     }
2000     /**
2001      * A user should be able to create an event for a group that they are a member of in
2002      * a course in which they are enrolled and have the moodle/calendar:manageentries capability.
2003      */
2004     public function test_submit_create_update_form_create_group_event_group_member_manage_course() {
2005         $generator = $this->getDataGenerator();
2006         $user = $generator->create_user();
2007         $course = $generator->create_course();
2008         $group = $generator->create_group(array('courseid' => $course->id));
2009         $context = context_course::instance($course->id);
2010         $roleid = $generator->create_role();
2011         $timestart = new DateTime();
2012         $interval = new DateInterval("P1D"); // One day.
2013         $timedurationuntil = new DateTime();
2014         $timedurationuntil->add($interval);
2015         $formdata = [
2016             'id' => 0,
2017             'userid' => $user->id,
2018             'modulename' => '',
2019             'instance' => 0,
2020             'visible' => 1,
2021             'name' => 'Test',
2022             'timestart' => [
2023                 'day' => $timestart->format('j'),
2024                 'month' => $timestart->format('n'),
2025                 'year' => $timestart->format('Y'),
2026                 'hour' => $timestart->format('G'),
2027                 'minute' => 0,
2028             ],
2029             'eventtype' => 'group',
2030             'groupid' => $group->id,
2031             'groupcourseid' => $course->id,
2032             'description' => [
2033                 'text' => '',
2034                 'format' => 1,
2035                 'itemid' => 0
2036             ],
2037             'location' => 'Test',
2038             'duration' => 1,
2039             'timedurationuntil' => [
2040                 'day' => $timedurationuntil->format('j'),
2041                 'month' => $timedurationuntil->format('n'),
2042                 'year' => $timedurationuntil->format('Y'),
2043                 'hour' => $timedurationuntil->format('G'),
2044                 'minute' => 0,
2045             ]
2046         ];
2048         $formdata = \core_calendar\local\event\forms\create::mock_generate_submit_keys($formdata);
2049         $querystring = http_build_query($formdata, '', '&');
2051         $generator->enrol_user($user->id, $course->id, 'student');
2052         $generator->role_assign($roleid, $user->id, $context->id);
2053         $generator->create_group_member(['groupid' => $group->id, 'userid' => $user->id]);
2055         assign_capability('moodle/calendar:manageentries', CAP_ALLOW, $roleid, $context, true);
2057         $user->ignoresesskey = true;
2058         $this->resetAfterTest(true);
2059         $this->setUser($user);
2061         $result = external_api::clean_returnvalue(
2062             core_calendar_external::submit_create_update_form_returns(),
2063             core_calendar_external::submit_create_update_form($querystring)
2064         );
2066         $event = $result['event'];
2067         $this->assertEquals($user->id, $event['userid']);
2068         $this->assertEquals($formdata['eventtype'], $event['eventtype']);
2069         $this->assertEquals($formdata['name'], $event['name']);
2070         $this->assertEquals($group->id, $event['groupid']);
2071     }
2073     /**
2074      * A user should be able to create an event for a group that they are a member of in
2075      * a course in which they are enrolled and have the moodle/calendar:managegroupentries capability.
2076      */
2077     public function test_submit_create_update_form_create_group_event_group_member_manage_group_entries() {
2078         $generator = $this->getDataGenerator();
2079         $user = $generator->create_user();
2080         $course = $generator->create_course();
2081         $group = $generator->create_group(array('courseid' => $course->id));
2082         $context = context_course::instance($course->id);
2083         $roleid = $generator->create_role();
2084         $timestart = new DateTime();
2085         $interval = new DateInterval("P1D"); // One day.
2086         $timedurationuntil = new DateTime();
2087         $timedurationuntil->add($interval);
2088         $formdata = [
2089             'id' => 0,
2090             'userid' => $user->id,
2091             'modulename' => '',
2092             'instance' => 0,
2093             'visible' => 1,
2094             'name' => 'Test',
2095             'timestart' => [
2096                 'day' => $timestart->format('j'),
2097                 'month' => $timestart->format('n'),
2098                 'year' => $timestart->format('Y'),
2099                 'hour' => $timestart->format('G'),
2100                 'minute' => 0,
2101             ],
2102             'eventtype' => 'group',
2103             'groupid' => $group->id,
2104             'groupcourseid' => $course->id,
2105             'description' => [
2106                 'text' => '',
2107                 'format' => 1,
2108                 'itemid' => 0
2109             ],
2110             'location' => 'Test',
2111             'duration' => 1,
2112             'timedurationuntil' => [
2113                 'day' => $timedurationuntil->format('j'),
2114                 'month' => $timedurationuntil->format('n'),
2115                 'year' => $timedurationuntil->format('Y'),
2116                 'hour' => $timedurationuntil->format('G'),
2117                 'minute' => 0,
2118             ]
2119         ];
2121         $formdata = \core_calendar\local\event\forms\create::mock_generate_submit_keys($formdata);
2122         $querystring = http_build_query($formdata, '', '&');
2124         $generator->enrol_user($user->id, $course->id, 'student');
2125         $generator->role_assign($roleid, $user->id, $context->id);
2126         $generator->create_group_member(['groupid' => $group->id, 'userid' => $user->id]);
2128         assign_capability('moodle/calendar:manageentries', CAP_PROHIBIT, $roleid, $context, true);
2129         assign_capability('moodle/calendar:managegroupentries', CAP_ALLOW, $roleid, $context, true);
2131         $user->ignoresesskey = true;
2132         $this->resetAfterTest(true);
2133         $this->setUser($user);
2135         $result = external_api::clean_returnvalue(
2136             core_calendar_external::submit_create_update_form_returns(),
2137             core_calendar_external::submit_create_update_form($querystring)
2138         );
2140         $event = $result['event'];
2141         $this->assertEquals($user->id, $event['userid']);
2142         $this->assertEquals($formdata['eventtype'], $event['eventtype']);
2143         $this->assertEquals($formdata['name'], $event['name']);
2144         $this->assertEquals($group->id, $event['groupid']);
2145     }
2147     /**
2148      * A user should be able to create an event for any group in a course in which
2149      * they are enrolled and have the moodle/site:accessallgroups capability.
2150      */
2151     public function test_submit_create_update_form_create_group_event_access_all_groups() {
2152         $generator = $this->getDataGenerator();
2153         $user = $generator->create_user();
2154         $course = $generator->create_course();
2155         $group = $generator->create_group(array('courseid' => $course->id));
2156         $context = context_course::instance($course->id);
2157         $roleid = $generator->create_role();
2158         $timestart = new DateTime();
2159         $interval = new DateInterval("P1D"); // One day.
2160         $timedurationuntil = new DateTime();
2161         $timedurationuntil->add($interval);
2162         $formdata = [
2163             'id' => 0,
2164             'userid' => $user->id,
2165             'modulename' => '',
2166             'instance' => 0,
2167             'visible' => 1,
2168             'name' => 'Test',
2169             'timestart' => [
2170                 'day' => $timestart->format('j'),
2171                 'month' => $timestart->format('n'),
2172                 'year' => $timestart->format('Y'),
2173                 'hour' => $timestart->format('G'),
2174                 'minute' => 0,
2175             ],
2176             'eventtype' => 'group',
2177             'groupid' => $group->id,
2178             'groupcourseid' => $course->id,
2179             'description' => [
2180                 'text' => '',
2181                 'format' => 1,
2182                 'itemid' => 0
2183             ],
2184             'location' => 'Test',
2185             'duration' => 1,
2186             'timedurationuntil' => [
2187                 'day' => $timedurationuntil->format('j'),
2188                 'month' => $timedurationuntil->format('n'),
2189                 'year' => $timedurationuntil->format('Y'),
2190                 'hour' => $timedurationuntil->format('G'),
2191                 'minute' => 0,
2192             ]
2193         ];
2195         $formdata = \core_calendar\local\event\forms\create::mock_generate_submit_keys($formdata);
2196         $querystring = http_build_query($formdata, '', '&');
2198         $generator->enrol_user($user->id, $course->id, 'student');
2199         $generator->role_assign($roleid, $user->id, $context->id);
2201         assign_capability('moodle/calendar:manageentries', CAP_ALLOW, $roleid, $context, true);
2202         assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $roleid, $context, true);
2204         $user->ignoresesskey = true;
2205         $this->resetAfterTest(true);
2206         $this->setUser($user);
2208         $result = external_api::clean_returnvalue(
2209             core_calendar_external::submit_create_update_form_returns(),
2210             core_calendar_external::submit_create_update_form($querystring)
2211         );
2213         $event = $result['event'];
2214         $this->assertEquals($user->id, $event['userid']);
2215         $this->assertEquals($formdata['eventtype'], $event['eventtype']);
2216         $this->assertEquals($formdata['name'], $event['name']);
2217         $this->assertEquals($group->id, $event['groupid']);
2218     }
2220     /**
2221      * A user should not be able to create an event for any group that they are not a
2222      * member of in a course in which they are enrolled but don't have the
2223      * moodle/site:accessallgroups capability.
2224      */
2225     public function test_submit_create_update_form_create_group_event_non_member_no_permission() {
2226         $generator = $this->getDataGenerator();
2227         $user = $generator->create_user();
2228         $course = $generator->create_course();
2229         $group = $generator->create_group(array('courseid' => $course->id));
2230         $context = context_course::instance($course->id);
2231         $roleid = $generator->create_role();
2232         $timestart = new DateTime();
2233         $interval = new DateInterval("P1D"); // One day.
2234         $timedurationuntil = new DateTime();
2235         $timedurationuntil->add($interval);
2236         $formdata = [
2237             'id' => 0,
2238             'userid' => $user->id,
2239             'modulename' => '',
2240             'instance' => 0,
2241             'visible' => 1,
2242             'name' => 'Test',
2243             'timestart' => [
2244                 'day' => $timestart->format('j'),
2245                 'month' => $timestart->format('n'),
2246                 'year' => $timestart->format('Y'),
2247                 'hour' => $timestart->format('G'),
2248                 'minute' => 0,
2249             ],
2250             'eventtype' => 'group',
2251             'groupid' => $group->id,
2252             'groupcourseid' => $course->id,
2253             'description' => [
2254                 'text' => '',
2255                 'format' => 1,
2256             ],
2257             'location' => 'Test',
2258             'duration' => 1,
2259             'timedurationuntil' => [
2260                 'day' => $timedurationuntil->format('j'),
2261                 'month' => $timedurationuntil->format('n'),
2262                 'year' => $timedurationuntil->format('Y'),
2263                 'hour' => $timedurationuntil->format('G'),
2264                 'minute' => 0,
2265             ]
2266         ];
2268         $formdata = \core_calendar\local\event\forms\create::mock_generate_submit_keys($formdata);
2269         $querystring = http_build_query($formdata, '', '&');
2271         $generator->enrol_user($user->id, $course->id, 'student');
2272         $generator->role_assign($roleid, $user->id, $context->id);
2274         assign_capability('moodle/calendar:manageentries', CAP_ALLOW, $roleid, $context, true);
2275         assign_capability('moodle/site:accessallgroups', CAP_PROHIBIT, $roleid, $context, true);
2277         $user->ignoresesskey = true;
2278         $this->resetAfterTest(true);
2279         $this->setUser($user);
2281         $result = external_api::clean_returnvalue(
2282             core_calendar_external::submit_create_update_form_returns(),
2283             core_calendar_external::submit_create_update_form($querystring)
2284         );
2286         $this->assertTrue($result['validationerror']);
2287     }
2289     /**
2290      * A user should not be able load the calendar monthly view for a course they cannot access.
2291      */
2292     public function test_get_calendar_monthly_view_no_course_permission() {
2293         global $USER;
2294         $this->resetAfterTest(true);
2295         $this->setAdminUser();
2297         $generator = $this->getDataGenerator();
2298         $user1 = $generator->create_user();
2299         $user2 = $generator->create_user();
2300         $course = $generator->create_course();
2301         $generator->enrol_user($user1->id, $course->id, 'student');
2302         $name = 'Course Event (course' . $course->id . ')';
2303         $record = new stdClass();
2304         $record->courseid = $course->id;
2305         $courseevent = $this->create_calendar_event($name, $USER->id, 'course', 0, time(), $record);
2307         $timestart = new DateTime();
2308         // Admin can load the course.
2309         $data = external_api::clean_returnvalue(
2310             core_calendar_external::get_calendar_monthly_view_returns(),
2311             core_calendar_external::get_calendar_monthly_view($timestart->format('Y'), $timestart->format('n'),
2312                                                               $course->id, null, false, true)
2313         );
2314         $this->assertEquals($data['courseid'], $course->id);
2315         // User enrolled in the course can load the course calendar.
2316         $this->setUser($user1);
2317         $data = external_api::clean_returnvalue(
2318             core_calendar_external::get_calendar_monthly_view_returns(),
2319             core_calendar_external::get_calendar_monthly_view($timestart->format('Y'), $timestart->format('n'),
2320                                                               $course->id, null, false, true)
2321         );
2322         $this->assertEquals($data['courseid'], $course->id);
2323         // User not enrolled in the course cannot load the course calendar.
2324         $this->setUser($user2);
2325         $this->expectException('require_login_exception');
2326         $data = external_api::clean_returnvalue(
2327             core_calendar_external::get_calendar_monthly_view_returns(),
2328             core_calendar_external::get_calendar_monthly_view($timestart->format('Y'), $timestart->format('n'),
2329                                                               $course->id, null, false, false)
2330         );
2331     }
2333     /**
2334      * A user should not be able load the calendar day view for a course they cannot access.
2335      */
2336     public function test_get_calendar_day_view_no_course_permission() {
2337         global $USER;
2338         $this->resetAfterTest(true);
2339         $this->setAdminUser();
2341         $generator = $this->getDataGenerator();
2342         $user1 = $generator->create_user();
2343         $user2 = $generator->create_user();
2344         $course = $generator->create_course();
2345         $generator->enrol_user($user1->id, $course->id, 'student');
2346         $name = 'Course Event (course' . $course->id . ')';
2347         $record = new stdClass();
2348         $record->courseid = $course->id;
2349         $courseevent = $this->create_calendar_event($name, $USER->id, 'course', 0, time(), $record);
2351         $timestart = new DateTime();
2352         // Admin can load the course.
2353         $data = external_api::clean_returnvalue(
2354             core_calendar_external::get_calendar_day_view_returns(),
2355             core_calendar_external::get_calendar_day_view($timestart->format('Y'), $timestart->format('n'),
2356                                                           $timestart->format('j'), $course->id, null)
2357         );
2358         $this->assertEquals($data['courseid'], $course->id);
2359         // User enrolled in the course can load the course calendar.
2360         $this->setUser($user1);
2361         $data = external_api::clean_returnvalue(
2362             core_calendar_external::get_calendar_day_view_returns(),
2363             core_calendar_external::get_calendar_day_view($timestart->format('Y'), $timestart->format('n'),
2364                                                           $timestart->format('j'), $course->id, null)
2365         );
2366         $this->assertEquals($data['courseid'], $course->id);
2367         // User not enrolled in the course cannot load the course calendar.
2368         $this->setUser($user2);
2369         $this->expectException('require_login_exception');
2370         $data = external_api::clean_returnvalue(
2371             core_calendar_external::get_calendar_day_view_returns(),
2372             core_calendar_external::get_calendar_day_view($timestart->format('Y'), $timestart->format('n'),
2373                                                           $timestart->format('j'), $course->id, null)
2374         );
2375     }
2377     /**
2378      * A user should not be able load the calendar upcoming view for a course they cannot access.
2379      */
2380     public function test_get_calendar_upcoming_view_no_course_permission() {
2381         global $USER;
2382         $this->resetAfterTest(true);
2383         $this->setAdminUser();
2385         $generator = $this->getDataGenerator();
2386         $user1 = $generator->create_user();
2387         $user2 = $generator->create_user();
2388         $course = $generator->create_course();
2389         $generator->enrol_user($user1->id, $course->id, 'student');
2390         $name = 'Course Event (course' . $course->id . ')';
2391         $record = new stdClass();
2392         $record->courseid = $course->id;
2393         $courseevent = $this->create_calendar_event($name, $USER->id, 'course', 0, time(), $record);
2395         // Admin can load the course.
2396         $data = external_api::clean_returnvalue(
2397             core_calendar_external::get_calendar_upcoming_view_returns(),
2398             core_calendar_external::get_calendar_upcoming_view($course->id, null)
2399         );
2400         $this->assertEquals($data['courseid'], $course->id);
2401         // User enrolled in the course can load the course calendar.
2402         $this->setUser($user1);
2403         $data = external_api::clean_returnvalue(
2404             core_calendar_external::get_calendar_upcoming_view_returns(),
2405             core_calendar_external::get_calendar_upcoming_view($course->id, null)
2406         );
2407         $this->assertEquals($data['courseid'], $course->id);
2408         // User not enrolled in the course cannot load the course calendar.
2409         $this->setUser($user2);
2410         $this->expectException('require_login_exception');
2411         $data = external_api::clean_returnvalue(
2412             core_calendar_external::get_calendar_upcoming_view_returns(),
2413             core_calendar_external::get_calendar_upcoming_view($course->id, null)
2414         );
2415     }
2417     /**
2418      * A user should not be able load the calendar event for a course they cannot access.
2419      */
2420     public function test_get_calendar_event_by_id_no_course_permission() {
2421         global $USER;
2422         $this->resetAfterTest(true);
2423         $this->setAdminUser();
2425         $generator = $this->getDataGenerator();
2426         $user1 = $generator->create_user();
2427         $user2 = $generator->create_user();
2428         $course = $generator->create_course();
2429         $generator->enrol_user($user1->id, $course->id, 'student');
2430         $name = 'Course Event (course' . $course->id . ')';
2431         $record = new stdClass();
2432         $record->courseid = $course->id;
2433         $courseevent = $this->create_calendar_event($name, $USER->id, 'course', 0, time(), $record);
2435         // Admin can load the course event.
2436         $data = external_api::clean_returnvalue(
2437             core_calendar_external::get_calendar_event_by_id_returns(),
2438             core_calendar_external::get_calendar_event_by_id($courseevent->id)
2439         );
2440         $this->assertEquals($data['event']['id'], $courseevent->id);
2441         // User enrolled in the course can load the course event.
2442         $this->setUser($user1);
2443         $data = external_api::clean_returnvalue(
2444             core_calendar_external::get_calendar_event_by_id_returns(),
2445             core_calendar_external::get_calendar_event_by_id($courseevent->id)
2446         );
2447         $this->assertEquals($data['event']['id'], $courseevent->id);
2448         // User not enrolled in the course cannot load the course event.
2449         $this->setUser($user2);
2450         $this->expectException('required_capability_exception');
2451         $data = external_api::clean_returnvalue(
2452             core_calendar_external::get_calendar_event_by_id_returns(),
2453             core_calendar_external::get_calendar_event_by_id($courseevent->id)
2454         );
2455     }
2457     /**
2458      * A user should not be able load the calendar events for a category they cannot see.
2459      */
2460     public function test_get_calendar_events_hidden_category() {
2461         global $USER;
2462         $this->resetAfterTest(true);
2463         $this->setAdminUser();
2465         $generator = $this->getDataGenerator();
2466         $user1 = $generator->create_user();
2467         $category = $generator->create_category(['visible' => 0]);
2468         $name = 'Category Event (category: ' . $category->id . ')';
2469         $record = new stdClass();
2470         $record->categoryid = $category->id;
2471         $categoryevent = $this->create_calendar_event($name, $USER->id, 'category', 0, time(), $record);
2473         $events = [
2474             'eventids' => [$categoryevent->id]
2475         ];
2476         $options = [];
2477         // Admin can load the category event.
2478         $data = external_api::clean_returnvalue(
2479             core_calendar_external::get_calendar_events_returns(),
2480             core_calendar_external::get_calendar_events($events, $options)
2481         );
2482         $this->assertEquals($data['events'][0]['id'], $categoryevent->id);
2483         // User with no special permission to see hidden categories will not see the event.
2484         $this->setUser($user1);
2485         $data = external_api::clean_returnvalue(
2486             core_calendar_external::get_calendar_events_returns(),
2487             core_calendar_external::get_calendar_events($events, $options)
2488         );
2489         $this->assertCount(0, $data['events']);
2490         $this->assertEquals('nopermissions', $data['warnings'][0]['warningcode']);
2491     }