Automatically generated installer lang files
[moodle.git] / enrol / tests / externallib_test.php
blobb0199c0bafe7a95359867ff4c11a4882f07b087e
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 namespace core_enrol;
19 use core_enrol_external;
20 use core_external\external_api;
21 use enrol_user_enrolment_form;
22 use externallib_advanced_testcase;
24 defined('MOODLE_INTERNAL') || die();
26 global $CFG;
28 require_once($CFG->dirroot . '/webservice/tests/helpers.php');
29 require_once($CFG->dirroot . '/enrol/externallib.php');
31 /**
32 * Enrol external PHPunit tests
34 * @package core_enrol
35 * @category external
36 * @copyright 2012 Jerome Mouneyrac
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 * @since Moodle 2.4
40 class externallib_test extends externallib_advanced_testcase {
42 /**
43 * dataProvider for test_get_enrolled_users_visibility().
45 public function get_enrolled_users_visibility_provider() {
46 return array(
47 'Course without groups, default behavior (not filtering by cap, group, active)' =>
48 array(
49 'settings' => array(
50 'coursegroupmode' => NOGROUPS,
51 'withcapability' => null,
52 'groupid' => null,
53 'onlyactive' => false,
54 'allowedcaps' => array(),
56 'results' => array( // Everybody can view everybody.
57 'user0' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
58 'user1' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
59 'user2' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
60 'user31' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
61 'userall' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
65 'Course with visible groups, default behavior (not filtering by cap, group, active)' =>
66 array(
67 'settings' => array(
68 'coursegroupmode' => VISIBLEGROUPS,
69 'withcapability' => null,
70 'groupid' => null,
71 'onlyactive' => false,
72 'allowedcaps' => array(),
74 'results' => array( // Everybody can view everybody.
75 'user0' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
76 'user1' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
77 'user2' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
78 'user31' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
79 'userall' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
83 'Course with separate groups, default behavior (not filtering by cap, group, active)' =>
84 array(
85 'settings' => array(
86 'coursegroupmode' => SEPARATEGROUPS,
87 'withcapability' => null,
88 'groupid' => null,
89 'onlyactive' => false,
90 'allowedcaps' => array(),
92 'results' => array( // Only users from own groups are visible.
93 'user0' => array('canview' => array()), // Poor guy, cannot see anybody, himself included.
94 'user1' => array('canview' => array('user1', 'userall')),
95 'user2' => array('canview' => array('user2', 'user2su', 'userall')),
96 'user31' => array('canview' => array('user31', 'user32', 'userall')),
97 'userall' => array('canview' => array('user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
101 'Course with separate groups, default behavior (not filtering but having moodle/site:accessallgroups)' =>
102 array(
103 'settings' => array(
104 'coursegroupmode' => VISIBLEGROUPS,
105 'withcapability' => null,
106 'groupid' => null,
107 'onlyactive' => false,
108 'allowedcaps' => array('moodle/site:accessallgroups'),
110 'results' => array( // Everybody can view everybody.
111 'user0' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
112 'user1' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
113 'user2' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
114 'user31' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
115 'userall' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
119 'Course with separate groups, filtering onlyactive (missing moodle/course:enrolreview)' =>
120 array(
121 'settings' => array(
122 'coursegroupmode' => SEPARATEGROUPS,
123 'withcapability' => null,
124 'groupid' => null,
125 'onlyactive' => true,
126 'allowedcaps' => array(),
128 'results' => array( // returns exception, cannot view anybody without the cap.
129 'user2' => array('exception' => array(
130 'type' => 'required_capability_exception',
131 'message' => 'Review course enrolments')),
132 'userall' => array('exception' => array(
133 'type' => 'required_capability_exception',
134 'message' => 'Review course enrolments')),
138 'Course with separate groups, filtering onlyactive (having moodle/course:enrolreview)' =>
139 array(
140 'settings' => array(
141 'coursegroupmode' => SEPARATEGROUPS,
142 'withcapability' => null,
143 'groupid' => null,
144 'onlyactive' => true,
145 'allowedcaps' => array('moodle/course:enrolreview'),
147 'results' => array( // Suspended are not returned.
148 'user2' => array('canview' => array('user2', 'userall')),
149 'user31' => array('canview' => array('user31', 'user32', 'userall')),
150 'userall' => array('canview' => array('user1', 'user2', 'user31', 'user32', 'userall')),
154 'Course with separate groups, filtering by groupid (not having moodle/site:accessallgroups)' =>
155 array(
156 'settings' => array(
157 'coursegroupmode' => SEPARATEGROUPS,
158 'withcapability' => null,
159 'groupid' => 'group2',
160 'onlyactive' => false,
161 'allowedcaps' => array(),
163 'results' => array( // Only group 2 members and only for members. Exception for non-members.
164 'user0' => array('exception' => array(
165 'type' => 'required_capability_exception',
166 'message' => 'Access all groups')),
167 'user1' => array('exception' => array(
168 'type' => 'required_capability_exception',
169 'message' => 'Access all groups')),
170 'user2' => array('canview' => array('user2', 'user2su', 'userall')),
171 'userall' => array('canview' => array('user2', 'user2su', 'userall')),
175 'Course with separate groups, filtering by groupid (having moodle/site:accessallgroups)' =>
176 array(
177 'settings' => array(
178 'coursegroupmode' => SEPARATEGROUPS,
179 'withcapability' => null,
180 'groupid' => 'group2',
181 'onlyactive' => false,
182 'allowedcaps' => array('moodle/site:accessallgroups'),
184 'results' => array( // All users with 'moodle/site:accessallgroups' can view group 2
185 'user0' => array('canview' => array('user2', 'user2su', 'userall')),
186 'user1' => array('canview' => array('user2', 'user2su', 'userall')),
187 'user2' => array('canview' => array('user2', 'user2su', 'userall')),
188 'userall' => array('canview' => array('user2', 'user2su', 'userall')),
192 'Course with separate groups, filtering by withcapability (not having moodle/role:review)' =>
193 array(
194 'settings' => array(
195 'coursegroupmode' => SEPARATEGROUPS,
196 'withcapability' => 'moodle/course:bulkmessaging',
197 'groupid' => null,
198 'onlyactive' => false,
199 'allowedcaps' => array(),
201 'results' => array( // No user has 'moodle/role:review' so exception.
202 'user0' => array('exception' => array(
203 'type' => 'required_capability_exception',
204 'message' => 'Review permissions for others')),
205 'user1' => array('exception' => array(
206 'type' => 'required_capability_exception',
207 'message' => 'Review permissions for others')),
208 'user2' => array('exception' => array(
209 'type' => 'required_capability_exception',
210 'message' => 'Review permissions for others')),
211 'userall' => array('exception' => array(
212 'type' => 'required_capability_exception',
213 'message' => 'Review permissions for others')),
217 'Course with separate groups, filtering by withcapability (having moodle/role:review)' =>
218 array(
219 'settings' => array(
220 'coursegroupmode' => SEPARATEGROUPS,
221 'withcapability' => 'moodle/course:bulkmessaging',
222 'groupid' => null,
223 'onlyactive' => false,
224 'allowedcaps' => array('moodle/role:review'),
226 'results' => array( // No user has withcapability, but all have 'moodle/role:review'. Empties.
227 'user0' => array('canview' => array()),
228 'user1' => array('canview' => array()),
229 'user2' => array('canview' => array()),
230 'userall' => array('canview' => array()),
234 'Course with separate groups, filtering by withcapability (having moodle/role:review)' =>
235 array(
236 'settings' => array(
237 'coursegroupmode' => SEPARATEGROUPS,
238 'withcapability' => 'moodle/course:bulkmessaging',
239 'groupid' => null,
240 'onlyactive' => false,
241 'allowedcaps' => array('moodle/role:review', 'moodle/course:bulkmessaging'),
243 'results' => array( // Users (previous) have withcapability, and all have 'moodle/role:review'.
244 'user0' => array('canview' => array()),
245 'user1' => array('canview' => array('user1')),
246 'user2' => array('canview' => array('user2')),
247 'userall' => array('canview' => array('user1', 'user2', 'userall')),
254 * Verify get_enrolled_users() returned users are the expected in every situation.
256 * @dataProvider get_enrolled_users_visibility_provider
258 public function test_get_enrolled_users_visibility($settings, $results) {
260 global $USER;
262 $this->resetAfterTest();
264 // Create the course and the users.
265 $course = $this->getDataGenerator()->create_course(array('groupmode' => $settings['coursegroupmode']));
266 $coursecontext = \context_course::instance($course->id);
267 $user0 = $this->getDataGenerator()->create_user(array('username' => 'user0')); // A user without group.
268 $user1 = $this->getDataGenerator()->create_user(array('username' => 'user1')); // User for group 1.
269 $user2 = $this->getDataGenerator()->create_user(array('username' => 'user2')); // Two users for group 2.
270 $user2su = $this->getDataGenerator()->create_user(array('username' => 'user2su')); // (one suspended).
271 $user31 = $this->getDataGenerator()->create_user(array('username' => 'user31')); // Two users for group 3.
272 $user32 = $this->getDataGenerator()->create_user(array('username' => 'user32')); // (both enabled).
273 $userall = $this->getDataGenerator()->create_user(array('username' => 'userall')); // A user in all groups.
275 // Create utility array of created users, to produce better assertion messages.
276 $createdusers = array();
277 foreach (array($user0, $user1, $user2, $user2su, $user31, $user32, $userall) as $createduser) {
278 $createdusers[$createduser->id] = $createduser->username;
281 // Enrol the users in the course.
282 $this->getDataGenerator()->enrol_user($user0->id, $course->id);
283 $this->getDataGenerator()->enrol_user($user1->id, $course->id);
284 $this->getDataGenerator()->enrol_user($user2->id, $course->id);
285 $this->getDataGenerator()->enrol_user($user2su->id, $course->id, null, 'manual', 0, 0, ENROL_USER_SUSPENDED);
286 $this->getDataGenerator()->enrol_user($user31->id, $course->id);
287 $this->getDataGenerator()->enrol_user($user32->id, $course->id);
288 $this->getDataGenerator()->enrol_user($userall->id, $course->id);
290 // Create 3 groups.
291 $group1 = $this->getDataGenerator()->create_group(array('courseid' => $course->id));
292 $group2 = $this->getDataGenerator()->create_group(array('courseid' => $course->id));
293 $group3 = $this->getDataGenerator()->create_group(array('courseid' => $course->id));
295 // Add the users to the groups.
296 $this->getDataGenerator()->create_group_member(array('groupid' => $group1->id, 'userid' => $user1->id));
297 $this->getDataGenerator()->create_group_member(array('groupid' => $group2->id, 'userid' => $user2->id));
298 $this->getDataGenerator()->create_group_member(array('groupid' => $group2->id, 'userid' => $user2su->id));
299 $this->getDataGenerator()->create_group_member(array('groupid' => $group3->id, 'userid' => $user31->id));
300 $this->getDataGenerator()->create_group_member(array('groupid' => $group3->id, 'userid' => $user32->id));
301 $this->getDataGenerator()->create_group_member(array('groupid' => $group1->id, 'userid' => $userall->id));
302 $this->getDataGenerator()->create_group_member(array('groupid' => $group2->id, 'userid' => $userall->id));
303 $this->getDataGenerator()->create_group_member(array('groupid' => $group3->id, 'userid' => $userall->id));
305 // Create a role to add the allowedcaps. Users will have this role assigned.
306 $roleid = $this->getDataGenerator()->create_role();
307 // Allow the specified capabilities.
308 if (!empty($settings['allowedcaps'])) {
309 foreach ($settings['allowedcaps'] as $capability) {
310 assign_capability($capability, CAP_ALLOW, $roleid, $coursecontext);
314 // For each of the users, configure everything, perform the call, and assert results.
315 foreach ($results as $user => $expectations) {
316 // Convert canview expectations into a nice array of ids for easier handling.
317 $canview = array();
318 $exception = null;
319 // Analyse the expectations.
320 if (isset($expectations['canview'])) {
321 foreach ($expectations['canview'] as $canviewuser) {
322 $canview[] = $createdusers[${$canviewuser}->id];
324 } else if (isset($expectations['exception'])) {
325 $exception = $expectations['exception'];
326 $this->expectException($exception['type']);
327 $this->expectExceptionMessage($exception['message']);
328 } else {
329 // Failed, only canview and exception are supported.
330 $this->markTestIncomplete('Incomplete, only canview and exception are supported');
332 // Switch to the user and assign the role.
333 $this->setUser(${$user});
334 role_assign($roleid, $USER->id, $coursecontext);
336 // Convert groupid to proper id.
337 $groupid = 0;
338 if (isset($settings['groupid'])) {
339 $groupid = ${$settings['groupid']}->id;
342 // Call to the function.
343 $options = array(
344 array('name' => 'withcapability', 'value' => $settings['withcapability']),
345 array('name' => 'groupid', 'value' => $groupid),
346 array('name' => 'onlyactive', 'value' => $settings['onlyactive']),
347 array('name' => 'userfields', 'value' => 'id')
349 $enrolledusers = core_enrol_external::get_enrolled_users($course->id, $options);
351 // We need to execute the return values cleaning process to simulate the web service server.
352 $enrolledusers = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_returns(), $enrolledusers);
354 // We are only interested in ids to check visibility.
355 $viewed = array();
356 // Verify the user canview the expected users.
357 foreach ($enrolledusers as $enrolleduser) {
358 $viewed[] = $createdusers[$enrolleduser['id']];
360 // Verify viewed matches canview expectation (using canonicalize to ignore ordering).
361 $this->assertEqualsCanonicalizing($canview, $viewed, "Problem checking visible users for '{$createdusers[$USER->id]}'");
366 * Verify get_enrolled_users() returned users according to their status.
368 public function test_get_enrolled_users_active_suspended() {
369 global $USER;
371 $this->resetAfterTest();
373 // Create the course and the users.
374 $course = $this->getDataGenerator()->create_course();
375 $coursecontext = \context_course::instance($course->id);
376 $user0 = $this->getDataGenerator()->create_user(['username' => 'user0active']);
377 $user1 = $this->getDataGenerator()->create_user(['username' => 'user1active']);
378 $user2 = $this->getDataGenerator()->create_user(['username' => 'user2active']);
379 $user2su = $this->getDataGenerator()->create_user(['username' => 'user2suspended']); // Suspended user.
380 $user3 = $this->getDataGenerator()->create_user(['username' => 'user3active']);
381 $user3su = $this->getDataGenerator()->create_user(['username' => 'user3suspended']); // Suspended user.
383 // Enrol the users in the course.
384 $this->getDataGenerator()->enrol_user($user0->id, $course->id);
385 $this->getDataGenerator()->enrol_user($user1->id, $course->id);
386 $this->getDataGenerator()->enrol_user($user2->id, $course->id);
387 $this->getDataGenerator()->enrol_user($user2su->id, $course->id, null, 'manual', 0, 0, ENROL_USER_SUSPENDED);
388 $this->getDataGenerator()->enrol_user($user3->id, $course->id);
389 $this->getDataGenerator()->enrol_user($user3su->id, $course->id, null, 'manual', 0, 0, ENROL_USER_SUSPENDED);
391 // Create a role to add the allowedcaps. Users will have this role assigned.
392 $roleid = $this->getDataGenerator()->create_role();
393 // Allow the specified capabilities.
394 assign_capability('moodle/course:enrolreview', CAP_ALLOW, $roleid, $coursecontext);
395 assign_capability('moodle/user:viewalldetails', CAP_ALLOW, $roleid, $coursecontext);
397 // Switch to the user and assign the role.
398 $this->setUser($user0);
399 role_assign($roleid, $USER->id, $coursecontext);
401 // Suspended users.
402 $options = [
403 ['name' => 'onlysuspended', 'value' => true],
404 ['name' => 'userfields', 'value' => 'id,username']
406 $suspendedusers = core_enrol_external::get_enrolled_users($course->id, $options);
408 // We need to execute the return values cleaning process to simulate the web service server.
409 $suspendedusers = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_returns(), $suspendedusers);
410 $this->assertCount(2, $suspendedusers);
412 foreach ($suspendedusers as $suspendeduser) {
413 $this->assertStringContainsString('suspended', $suspendeduser['username']);
416 // Active users.
417 $options = [
418 ['name' => 'onlyactive', 'value' => true],
419 ['name' => 'userfields', 'value' => 'id,username']
421 $activeusers = core_enrol_external::get_enrolled_users($course->id, $options);
423 // We need to execute the return values cleaning process to simulate the web service server.
424 $activeusers = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_returns(), $activeusers);
425 $this->assertCount(4, $activeusers);
427 foreach ($activeusers as $activeuser) {
428 $this->assertStringContainsString('active', $activeuser['username']);
431 // All enrolled users.
432 $options = [
433 ['name' => 'userfields', 'value' => 'id,username']
435 $allusers = core_enrol_external::get_enrolled_users($course->id, $options);
437 // We need to execute the return values cleaning process to simulate the web service server.
438 $allusers = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_returns(), $allusers);
439 $this->assertCount(6, $allusers);
441 // Active and suspended. Test exception is thrown.
442 $options = [
443 ['name' => 'onlyactive', 'value' => true],
444 ['name' => 'onlysuspended', 'value' => true],
445 ['name' => 'userfields', 'value' => 'id,username']
447 $this->expectException('coding_exception');
448 $message = 'Coding error detected, it must be fixed by a programmer: Both onlyactive ' .
449 'and onlysuspended are set, this is probably not what you want!';
450 $this->expectExceptionMessage($message);
451 core_enrol_external::get_enrolled_users($course->id, $options);
455 * Test get_users_courses
457 public function test_get_users_courses() {
458 global $CFG, $DB;
459 require_once($CFG->dirroot . '/completion/criteria/completion_criteria_self.php');
461 $this->resetAfterTest(true);
462 $CFG->enablecompletion = 1;
464 $timenow = time();
465 $coursedata1 = array(
466 // Adding tags here to check that \core_external\util::format_string works.
467 'fullname' => '<b>Course 1</b>',
468 // Adding tags here to check that \core_external\util::format_string works.
469 'shortname' => '<b>Course 1</b>',
470 'summary' => 'Lightwork Course 1 description',
471 'summaryformat' => FORMAT_MOODLE,
472 'lang' => 'en',
473 'enablecompletion' => true,
474 'showgrades' => true,
475 'startdate' => $timenow,
476 'enddate' => $timenow + WEEKSECS,
477 'marker' => 1
480 $coursedata2 = array(
481 'lang' => 'kk', // Check invalid language pack.
484 $course1 = self::getDataGenerator()->create_course($coursedata1);
485 $course2 = self::getDataGenerator()->create_course($coursedata2);
486 $courses = array($course1, $course2);
487 $contexts = array ($course1->id => \context_course::instance($course1->id),
488 $course2->id => \context_course::instance($course2->id));
490 $student = $this->getDataGenerator()->create_user();
491 $otherstudent = $this->getDataGenerator()->create_user();
492 $studentroleid = $DB->get_field('role', 'id', array('shortname' => 'student'));
493 $this->getDataGenerator()->enrol_user($student->id, $course1->id, $studentroleid);
494 $this->getDataGenerator()->enrol_user($otherstudent->id, $course1->id, $studentroleid);
495 $this->getDataGenerator()->enrol_user($student->id, $course2->id, $studentroleid);
497 // Force last access.
498 $timenow = time();
499 $lastaccess = array(
500 'userid' => $student->id,
501 'courseid' => $course1->id,
502 'timeaccess' => $timenow
504 $DB->insert_record('user_lastaccess', $lastaccess);
506 // Force completion, setting at least one criteria.
507 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_self.php');
508 $criteriadata = new \stdClass();
509 $criteriadata->id = $course1->id;
510 // Self completion.
511 $criteriadata->criteria_self = 1;
513 $criterion = new \completion_criteria_self();
514 $criterion->update_config($criteriadata);
516 $ccompletion = new \completion_completion(array('course' => $course1->id, 'userid' => $student->id));
517 $ccompletion->mark_complete();
519 // Set course hidden and favourited.
520 set_user_preference('block_myoverview_hidden_course_' . $course1->id, 1, $student);
521 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($student->id));
522 $ufservice->create_favourite('core_course', 'courses', $course1->id, \context_system::instance());
524 $this->setUser($student);
525 // Call the external function.
526 $enrolledincourses = core_enrol_external::get_users_courses($student->id, true);
528 // We need to execute the return values cleaning process to simulate the web service server.
529 $enrolledincourses = external_api::clean_returnvalue(core_enrol_external::get_users_courses_returns(), $enrolledincourses);
531 // Check we retrieve the good total number of enrolled users.
532 $this->assertEquals(2, count($enrolledincourses));
534 // We need to format summary and summaryformat before to compare them with those values returned by the webservice.
535 [$course1->summary, $course1->summaryformat] = \core_external\util::format_text(
536 $course1->summary,
537 $course1->summaryformat,
538 $contexts[$course1->id],
539 'course',
540 'summary',
544 // Check there are no differences between $course1 properties and course values returned by the webservice
545 // only for those fields listed in the $coursedata1 array.
546 $course1->fullname = \core_external\util::format_string($course1->fullname, $contexts[$course1->id]->id);
547 $course1->shortname = \core_external\util::format_string($course1->shortname, $contexts[$course1->id]->id);
548 foreach ($enrolledincourses as $courseenrol) {
549 if ($courseenrol['id'] == $course1->id) {
550 foreach ($coursedata1 as $fieldname => $value) {
551 $this->assertEquals($courseenrol[$fieldname], $course1->$fieldname);
553 // Text extra fields.
554 $this->assertEquals($course1->fullname, $courseenrol['displayname']);
555 $this->assertEquals([], $courseenrol['overviewfiles']);
556 $this->assertEquals($timenow, $courseenrol['lastaccess']);
557 $this->assertEquals(100.0, $courseenrol['progress']);
558 $this->assertEquals(true, $courseenrol['completed']);
559 $this->assertTrue($courseenrol['completionhascriteria']);
560 $this->assertTrue($courseenrol['completionusertracked']);
561 $this->assertTrue($courseenrol['hidden']);
562 $this->assertTrue($courseenrol['isfavourite']);
563 $this->assertEquals(2, $courseenrol['enrolledusercount']);
564 $this->assertEquals($course1->timemodified, $courseenrol['timemodified']);
565 } else {
566 // Check language pack. Should be empty since an incorrect one was used when creating the course.
567 $this->assertEmpty($courseenrol['lang']);
568 $this->assertEquals($course2->fullname, $courseenrol['displayname']);
569 $this->assertEquals([], $courseenrol['overviewfiles']);
570 $this->assertEquals(0, $courseenrol['lastaccess']);
571 $this->assertEquals(0, $courseenrol['progress']);
572 $this->assertEquals(false, $courseenrol['completed']);
573 $this->assertFalse($courseenrol['completionhascriteria']);
574 $this->assertFalse($courseenrol['completionusertracked']);
575 $this->assertFalse($courseenrol['hidden']);
576 $this->assertFalse($courseenrol['isfavourite']);
577 $this->assertEquals(1, $courseenrol['enrolledusercount']);
578 $this->assertEquals($course2->timemodified, $courseenrol['timemodified']);
582 // Check that returnusercount works correctly.
583 $enrolledincourses = core_enrol_external::get_users_courses($student->id, false);
584 $enrolledincourses = external_api::clean_returnvalue(core_enrol_external::get_users_courses_returns(), $enrolledincourses);
585 foreach ($enrolledincourses as $courseenrol) {
586 $this->assertFalse(isset($courseenrol['enrolledusercount']));
589 // Now check that admin users can see all the info.
590 $this->setAdminUser();
592 $enrolledincourses = core_enrol_external::get_users_courses($student->id, true);
593 $enrolledincourses = external_api::clean_returnvalue(core_enrol_external::get_users_courses_returns(), $enrolledincourses);
594 $this->assertEquals(2, count($enrolledincourses));
595 foreach ($enrolledincourses as $courseenrol) {
596 if ($courseenrol['id'] == $course1->id) {
597 $this->assertEquals($timenow, $courseenrol['lastaccess']);
598 $this->assertEquals(100.0, $courseenrol['progress']);
599 $this->assertTrue($courseenrol['completionhascriteria']);
600 $this->assertTrue($courseenrol['completionusertracked']);
601 $this->assertFalse($courseenrol['isfavourite']); // This always false.
602 $this->assertFalse($courseenrol['hidden']); // This always false.
603 } else {
604 $this->assertEquals(0, $courseenrol['progress']);
605 $this->assertFalse($courseenrol['completionhascriteria']);
606 $this->assertFalse($courseenrol['completionusertracked']);
607 $this->assertFalse($courseenrol['isfavourite']); // This always false.
608 $this->assertFalse($courseenrol['hidden']); // This always false.
612 // Check other users can't see private info.
613 $this->setUser($otherstudent);
615 $enrolledincourses = core_enrol_external::get_users_courses($student->id, true);
616 $enrolledincourses = external_api::clean_returnvalue(core_enrol_external::get_users_courses_returns(), $enrolledincourses);
617 $this->assertEquals(1, count($enrolledincourses));
619 $this->assertEquals($timenow, $enrolledincourses[0]['lastaccess']); // I can see this, not hidden.
620 $this->assertEquals(null, $enrolledincourses[0]['progress']); // I can't see this, private.
622 // Change some global profile visibility fields.
623 $CFG->hiddenuserfields = 'lastaccess';
624 $enrolledincourses = core_enrol_external::get_users_courses($student->id, true);
625 $enrolledincourses = external_api::clean_returnvalue(core_enrol_external::get_users_courses_returns(), $enrolledincourses);
627 $this->assertEquals(0, $enrolledincourses[0]['lastaccess']); // I can't see this, hidden by global setting.
631 * Test that get_users_courses respects the capability to view participants when viewing courses of other user
633 public function test_get_users_courses_can_view_participants(): void {
634 global $DB;
636 $this->resetAfterTest();
638 $course = $this->getDataGenerator()->create_course();
639 $context = \context_course::instance($course->id);
641 $user1 = $this->getDataGenerator()->create_and_enrol($course, 'student');
642 $user2 = $this->getDataGenerator()->create_and_enrol($course, 'student');
644 $this->setUser($user1);
646 $courses = core_enrol_external::clean_returnvalue(
647 core_enrol_external::get_users_courses_returns(),
648 core_enrol_external::get_users_courses($user2->id, false)
651 $this->assertCount(1, $courses);
652 $this->assertEquals($course->id, reset($courses)['id']);
654 // Prohibit the capability for viewing course participants.
655 $studentrole = $DB->get_field('role', 'id', ['shortname' => 'student']);
656 assign_capability('moodle/course:viewparticipants', CAP_PROHIBIT, $studentrole, $context->id);
658 $courses = core_enrol_external::clean_returnvalue(
659 core_enrol_external::get_users_courses_returns(),
660 core_enrol_external::get_users_courses($user2->id, false)
662 $this->assertEmpty($courses);
666 * Test that get_users_courses respects the capability to view a users profile when viewing courses of other user
668 public function test_get_users_courses_can_view_profile(): void {
669 $this->resetAfterTest();
671 $course = $this->getDataGenerator()->create_course([
672 'groupmode' => VISIBLEGROUPS,
675 $user1 = $this->getDataGenerator()->create_and_enrol($course, 'student');
676 $user2 = $this->getDataGenerator()->create_and_enrol($course, 'student');
678 // Create separate groups for each of our students.
679 $group1 = $this->getDataGenerator()->create_group(['courseid' => $course->id]);
680 groups_add_member($group1, $user1);
681 $group2 = $this->getDataGenerator()->create_group(['courseid' => $course->id]);
682 groups_add_member($group2, $user2);
684 $this->setUser($user1);
686 $courses = core_enrol_external::clean_returnvalue(
687 core_enrol_external::get_users_courses_returns(),
688 core_enrol_external::get_users_courses($user2->id, false)
691 $this->assertCount(1, $courses);
692 $this->assertEquals($course->id, reset($courses)['id']);
694 // Change to separate groups mode, so students can't view information about each other in different groups.
695 $course->groupmode = SEPARATEGROUPS;
696 update_course($course);
698 $courses = core_enrol_external::clean_returnvalue(
699 core_enrol_external::get_users_courses_returns(),
700 core_enrol_external::get_users_courses($user2->id, false)
702 $this->assertEmpty($courses);
706 * Test get_users_courses with mathjax in the name.
708 public function test_get_users_courses_with_mathjax() {
709 global $DB;
711 $this->resetAfterTest(true);
713 // Enable MathJax filter in content and headings.
714 $this->configure_filters([
715 ['name' => 'mathjaxloader', 'state' => TEXTFILTER_ON, 'move' => -1, 'applytostrings' => true],
718 // Create a course with MathJax in the name and summary.
719 $coursedata = [
720 'fullname' => 'Course 1 $$(a+b)=2$$',
721 'shortname' => 'Course 1 $$(a+b)=2$$',
722 'summary' => 'Lightwork Course 1 description $$(a+b)=2$$',
723 'summaryformat' => FORMAT_HTML,
726 $course = self::getDataGenerator()->create_course($coursedata);
727 $context = \context_course::instance($course->id);
729 // Enrol a student in the course.
730 $student = $this->getDataGenerator()->create_user();
731 $studentroleid = $DB->get_field('role', 'id', ['shortname' => 'student']);
732 $this->getDataGenerator()->enrol_user($student->id, $course->id, $studentroleid);
734 $this->setUser($student);
736 // Call the external function.
737 $enrolledincourses = core_enrol_external::get_users_courses($student->id, true);
739 // We need to execute the return values cleaning process to simulate the web service server.
740 $enrolledincourses = external_api::clean_returnvalue(core_enrol_external::get_users_courses_returns(), $enrolledincourses);
742 // Check that the amount of courses is the right one.
743 $this->assertCount(1, $enrolledincourses);
745 // Filter the values to compare them with the returned ones.
746 $course->fullname = \core_external\util::format_string($course->fullname, $context->id);
747 $course->shortname = \core_external\util::format_string($course->shortname, $context->id);
748 [$course->summary, $course->summaryformat] = \core_external\util::format_text(
749 $course->summary,
750 $course->summaryformat,
751 $context,
752 'course',
753 'summary',
757 // Compare the values.
758 $this->assertStringContainsString('<span class="filter_mathjaxloader_equation">', $enrolledincourses[0]['fullname']);
759 $this->assertStringContainsString('<span class="filter_mathjaxloader_equation">', $enrolledincourses[0]['shortname']);
760 $this->assertStringContainsString('<span class="filter_mathjaxloader_equation">', $enrolledincourses[0]['summary']);
761 $this->assertEquals($course->fullname, $enrolledincourses[0]['fullname']);
762 $this->assertEquals($course->shortname, $enrolledincourses[0]['shortname']);
763 $this->assertEquals($course->summary, $enrolledincourses[0]['summary']);
767 * Test get_course_enrolment_methods
769 public function test_get_course_enrolment_methods() {
770 global $DB;
772 $this->resetAfterTest(true);
774 // Get enrolment plugins.
775 $selfplugin = enrol_get_plugin('self');
776 $this->assertNotEmpty($selfplugin);
777 $manualplugin = enrol_get_plugin('manual');
778 $this->assertNotEmpty($manualplugin);
780 $studentrole = $DB->get_record('role', array('shortname'=>'student'));
781 $this->assertNotEmpty($studentrole);
783 $course1 = self::getDataGenerator()->create_course();
784 $coursedata = new \stdClass();
785 $coursedata->visible = 0;
786 $course2 = self::getDataGenerator()->create_course($coursedata);
788 // Add enrolment methods for course.
789 $instanceid1 = $selfplugin->add_instance($course1, array('status' => ENROL_INSTANCE_ENABLED,
790 'name' => 'Test instance 1',
791 'customint6' => 1,
792 'roleid' => $studentrole->id));
793 $instanceid2 = $selfplugin->add_instance($course1, array('status' => ENROL_INSTANCE_DISABLED,
794 'name' => 'Test instance 2',
795 'roleid' => $studentrole->id));
797 $instanceid3 = $manualplugin->add_instance($course1, array('status' => ENROL_INSTANCE_ENABLED,
798 'name' => 'Test instance 3'));
800 $enrolmentmethods = $DB->get_records('enrol', array('courseid' => $course1->id, 'status' => ENROL_INSTANCE_ENABLED));
801 $this->assertCount(2, $enrolmentmethods);
803 $this->setAdminUser();
805 // Check if information is returned.
806 $enrolmentmethods = core_enrol_external::get_course_enrolment_methods($course1->id);
807 $enrolmentmethods = external_api::clean_returnvalue(core_enrol_external::get_course_enrolment_methods_returns(),
808 $enrolmentmethods);
809 // Enrolment information is currently returned by self enrolment plugin, so count == 1.
810 // This should be changed as we implement get_enrol_info() for other enrolment plugins.
811 $this->assertCount(1, $enrolmentmethods);
813 $enrolmentmethod = $enrolmentmethods[0];
814 $this->assertEquals($course1->id, $enrolmentmethod['courseid']);
815 $this->assertEquals('self', $enrolmentmethod['type']);
816 $this->assertTrue($enrolmentmethod['status']);
817 $this->assertFalse(isset($enrolmentmethod['wsfunction']));
819 $instanceid4 = $selfplugin->add_instance($course2, array('status' => ENROL_INSTANCE_ENABLED,
820 'name' => 'Test instance 4',
821 'roleid' => $studentrole->id,
822 'customint6' => 1,
823 'password' => 'test'));
824 $enrolmentmethods = core_enrol_external::get_course_enrolment_methods($course2->id);
825 $enrolmentmethods = external_api::clean_returnvalue(core_enrol_external::get_course_enrolment_methods_returns(),
826 $enrolmentmethods);
827 $this->assertCount(1, $enrolmentmethods);
829 $enrolmentmethod = $enrolmentmethods[0];
830 $this->assertEquals($course2->id, $enrolmentmethod['courseid']);
831 $this->assertEquals('self', $enrolmentmethod['type']);
832 $this->assertTrue($enrolmentmethod['status']);
833 $this->assertEquals('enrol_self_get_instance_info', $enrolmentmethod['wsfunction']);
835 // Try to retrieve information using a normal user for a hidden course.
836 $user = self::getDataGenerator()->create_user();
837 $this->setUser($user);
838 try {
839 core_enrol_external::get_course_enrolment_methods($course2->id);
840 } catch (\moodle_exception $e) {
841 $this->assertEquals('coursehidden', $e->errorcode);
845 public function get_enrolled_users_setup($capability) {
846 global $USER;
848 $this->resetAfterTest(true);
850 $return = new \stdClass();
852 $return->course = self::getDataGenerator()->create_course();
853 $return->user1 = self::getDataGenerator()->create_user();
854 $return->user2 = self::getDataGenerator()->create_user();
855 $return->user3 = self::getDataGenerator()->create_user();
856 $this->setUser($return->user3);
858 // Set the required capabilities by the external function.
859 $return->context = \context_course::instance($return->course->id);
860 $return->roleid = $this->assignUserCapability($capability, $return->context->id);
861 $this->assignUserCapability('moodle/user:viewdetails', $return->context->id, $return->roleid);
863 // Enrol the users in the course.
864 $this->getDataGenerator()->enrol_user($return->user1->id, $return->course->id, $return->roleid, 'manual');
865 $this->getDataGenerator()->enrol_user($return->user2->id, $return->course->id, $return->roleid, 'manual');
866 $this->getDataGenerator()->enrol_user($return->user3->id, $return->course->id, $return->roleid, 'manual');
868 return $return;
872 * Test get_enrolled_users from core_enrol_external without additional
873 * parameters.
875 public function test_get_enrolled_users_without_parameters() {
876 $capability = 'moodle/course:viewparticipants';
877 $data = $this->get_enrolled_users_setup($capability);
879 // Call the external function.
880 $enrolledusers = core_enrol_external::get_enrolled_users($data->course->id);
882 // We need to execute the return values cleaning process to simulate the web service server.
883 $enrolledusers = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_returns(), $enrolledusers);
885 // Check the result set.
886 $this->assertEquals(3, count($enrolledusers));
887 $this->assertArrayHasKey('email', $enrolledusers[0]);
891 * Test get_enrolled_users from core_enrol_external with some parameters set.
893 public function test_get_enrolled_users_with_parameters() {
894 $capability = 'moodle/course:viewparticipants';
895 $data = $this->get_enrolled_users_setup($capability);
897 // Call the function with some parameters set.
898 $enrolledusers = core_enrol_external::get_enrolled_users($data->course->id, array(
899 array('name' => 'limitfrom', 'value' => 2),
900 array('name' => 'limitnumber', 'value' => 1),
901 array('name' => 'userfields', 'value' => 'id')
904 // We need to execute the return values cleaning process to simulate the web service server.
905 $enrolledusers = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_returns(), $enrolledusers);
907 // Check the result set, we should only get the 3rd result, which is $user3.
908 $this->assertCount(1, $enrolledusers);
909 $this->assertEquals($data->user3->id, $enrolledusers[0]['id']);
910 $this->assertArrayHasKey('id', $enrolledusers[0]);
911 $this->assertArrayNotHasKey('email', $enrolledusers[0]);
916 * Test get_enrolled_users last course access.
918 public function test_get_enrolled_users_including_lastcourseaccess() {
919 global $DB;
920 $capability = 'moodle/course:viewparticipants';
921 $data = $this->get_enrolled_users_setup($capability);
923 // Call the external function.
924 $enrolledusers = core_enrol_external::get_enrolled_users($data->course->id);
925 // We need to execute the return values cleaning process to simulate the web service server.
926 $enrolledusers = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_returns(), $enrolledusers);
928 // Check the result set.
929 $this->assertEquals(3, count($enrolledusers));
930 $this->assertArrayHasKey('email', $enrolledusers[0]);
931 $this->assertEquals(0, $enrolledusers[0]['lastcourseaccess']);
932 $this->assertEquals(0, $enrolledusers[1]['lastcourseaccess']);
933 $this->assertNotEquals(0, $enrolledusers[2]['lastcourseaccess']); // We forced an access to the course via setUser.
935 // Force last access.
936 $timenow = time();
937 $lastaccess = array(
938 'userid' => $enrolledusers[0]['id'],
939 'courseid' => $data->course->id,
940 'timeaccess' => $timenow
942 $DB->insert_record('user_lastaccess', $lastaccess);
944 $enrolledusers = core_enrol_external::get_enrolled_users($data->course->id);
945 $enrolledusers = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_returns(), $enrolledusers);
947 // Check the result set.
948 $this->assertEquals(3, count($enrolledusers));
949 $this->assertEquals($timenow, $enrolledusers[0]['lastcourseaccess']);
950 $this->assertEquals(0, $enrolledusers[1]['lastcourseaccess']);
951 $this->assertNotEquals(0, $enrolledusers[2]['lastcourseaccess']);
955 * Test get_enrolled_users from core_enrol_external with capability to
956 * viewparticipants removed.
958 public function test_get_enrolled_users_without_capability() {
959 $capability = 'moodle/course:viewparticipants';
960 $data = $this->get_enrolled_users_setup($capability);
962 // Call without required capability.
963 $this->unassignUserCapability($capability, $data->context->id, $data->roleid);
964 $this->expectException(\moodle_exception::class);
965 $categories = core_enrol_external::get_enrolled_users($data->course->id);
968 public function get_enrolled_users_with_capability_setup($capability) {
969 global $USER, $DB;
971 $this->resetAfterTest(true);
973 $return = new \stdClass();
975 // Create the course and fetch its context.
976 $return->course = self::getDataGenerator()->create_course();
977 $context = \context_course::instance($return->course->id);
979 // Create one teacher, and two students.
980 $return->teacher = self::getDataGenerator()->create_user();
981 $return->student1 = self::getDataGenerator()->create_user();
982 $return->student2 = self::getDataGenerator()->create_user();
984 // Create a new student role based on the student archetype but with the capability prohibitted.
985 $fakestudentroleid = create_role('Fake student role', 'fakestudent', 'Fake student role', 'student');
986 assign_capability($capability, CAP_PROHIBIT, $fakestudentroleid, $context->id);
988 // Enrol all of the users in the course.
989 // * 'teacher' is an editing teacher.
990 // * 'student1' is a standard student.
991 // * 'student2' is a student with the capability prohibitted.
992 $editingteacherroleid = $DB->get_field('role', 'id', array('shortname' => 'editingteacher'));
993 $studentroleid = $DB->get_field('role', 'id', array('shortname' => 'student'));
994 $this->getDataGenerator()->enrol_user($return->teacher->id, $return->course->id, $editingteacherroleid);
995 $this->getDataGenerator()->enrol_user($return->student1->id, $return->course->id, $studentroleid);
996 $this->getDataGenerator()->enrol_user($return->student2->id, $return->course->id, $fakestudentroleid);
998 // Log in as the teacher.
999 $this->setUser($return->teacher);
1001 // Clear caches.
1002 accesslib_clear_all_caches_for_unit_testing();
1004 return $return;
1008 * Test get_enrolled_users_with_capability without additional paramaters.
1010 public function test_get_enrolled_users_with_capability_without_parameters() {
1011 $capability = 'moodle/course:viewparticipants';
1012 $data = $this->get_enrolled_users_with_capability_setup($capability);
1014 $result = core_enrol_external::get_enrolled_users_with_capability(
1015 array(
1016 'coursecapabilities' => array(
1017 'courseid' => $data->course->id,
1018 'capabilities' => array(
1019 $capability,
1023 array()
1026 // We need to execute the return values cleaning process to simulate the web service server.
1027 $result = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_with_capability_returns(), $result);
1029 // Check an array containing the expected user for the course capability is returned.
1030 $expecteduserlist = $result[0];
1031 $this->assertEquals($data->course->id, $expecteduserlist['courseid']);
1032 $this->assertEquals($capability, $expecteduserlist['capability']);
1033 $this->assertEquals(2, count($expecteduserlist['users']));
1037 * Test get_enrolled_users_with_capability
1039 public function test_get_enrolled_users_with_capability_with_parameters () {
1040 $capability = 'moodle/course:viewparticipants';
1041 $data = $this->get_enrolled_users_with_capability_setup($capability);
1043 $result = core_enrol_external::get_enrolled_users_with_capability(
1044 array(
1045 'coursecapabilities' => array(
1046 'courseid' => $data->course->id,
1047 'capabilities' => array(
1048 $capability,
1052 array(
1053 array('name' => 'limitfrom', 'value' => 1),
1054 array('name' => 'limitnumber', 'value' => 1),
1055 array('name' => 'userfields', 'value' => 'id')
1059 // We need to execute the return values cleaning process to simulate the web service server.
1060 $result = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_with_capability_returns(), $result);
1062 // Check an array containing the expected user for the course capability is returned.
1063 $expecteduserlist = $result[0]['users'];
1064 $expecteduser = reset($expecteduserlist);
1065 $this->assertEquals(1, count($expecteduserlist));
1066 $this->assertEquals($data->student1->id, $expecteduser['id']);
1070 * Test get_enrolled_users last course access.
1072 public function test_get_enrolled_users_with_capability_including_lastcourseaccess() {
1073 global $DB;
1074 $capability = 'moodle/course:viewparticipants';
1075 $data = $this->get_enrolled_users_with_capability_setup($capability);
1077 $parameters = array(
1078 'coursecapabilities' => array(
1079 'courseid' => $data->course->id,
1080 'capabilities' => array(
1081 $capability,
1086 $result = core_enrol_external::get_enrolled_users_with_capability($parameters, array());
1087 // We need to execute the return values cleaning process to simulate the web service server.
1088 $result = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_with_capability_returns(), $result);
1090 // Check an array containing the expected user for the course capability is returned.
1091 $expecteduserlist = $result[0];
1092 $this->assertEquals($data->course->id, $expecteduserlist['courseid']);
1093 $this->assertEquals($capability, $expecteduserlist['capability']);
1094 $this->assertEquals(2, count($expecteduserlist['users']));
1095 // We forced an access to the course via setUser.
1096 $this->assertNotEquals(0, $expecteduserlist['users'][0]['lastcourseaccess']);
1097 $this->assertEquals(0, $expecteduserlist['users'][1]['lastcourseaccess']);
1099 // Force last access.
1100 $timenow = time();
1101 $lastaccess = array(
1102 'userid' => $expecteduserlist['users'][1]['id'],
1103 'courseid' => $data->course->id,
1104 'timeaccess' => $timenow
1106 $DB->insert_record('user_lastaccess', $lastaccess);
1108 $result = core_enrol_external::get_enrolled_users_with_capability($parameters, array());
1109 // We need to execute the return values cleaning process to simulate the web service server.
1110 $result = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_with_capability_returns(), $result);
1112 // Check the result set.
1113 $expecteduserlist = $result[0];
1114 $this->assertEquals(2, count($expecteduserlist['users']));
1115 $this->assertNotEquals(0, $expecteduserlist['users'][0]['lastcourseaccess']);
1116 $this->assertEquals($timenow, $expecteduserlist['users'][1]['lastcourseaccess']);
1120 * dataProvider for test_submit_user_enrolment_form().
1122 public function submit_user_enrolment_form_provider() {
1123 $now = new \DateTime();
1125 $nextmonth = clone($now);
1126 $nextmonth->add(new \DateInterval('P1M'));
1128 return [
1129 'Invalid data' => [
1130 'customdata' => [
1131 'status' => ENROL_USER_ACTIVE,
1132 'timestart' => [
1133 'day' => $now->format('j'),
1134 'month' => $now->format('n'),
1135 'year' => $now->format('Y'),
1136 'hour' => $now->format('G'),
1137 'minute' => 0,
1138 'enabled' => 1,
1140 'timeend' => [
1141 'day' => $now->format('j'),
1142 'month' => $now->format('n'),
1143 'year' => $now->format('Y'),
1144 'hour' => $now->format('G'),
1145 'minute' => 0,
1146 'enabled' => 1,
1149 'expectedresult' => false,
1150 'validationerror' => true,
1152 'Valid data' => [
1153 'customdata' => [
1154 'status' => ENROL_USER_ACTIVE,
1155 'timestart' => [
1156 'day' => $now->format('j'),
1157 'month' => $now->format('n'),
1158 'year' => $now->format('Y'),
1159 'hour' => $now->format('G'),
1160 'minute' => 0,
1161 'enabled' => 1,
1163 'timeend' => [
1164 'day' => $nextmonth->format('j'),
1165 'month' => $nextmonth->format('n'),
1166 'year' => $nextmonth->format('Y'),
1167 'hour' => $nextmonth->format('G'),
1168 'minute' => 0,
1169 'enabled' => 1,
1172 'expectedresult' => true,
1173 'validationerror' => false
1175 'Suspend user' => [
1176 'customdata' => [
1177 'status' => ENROL_USER_SUSPENDED,
1179 'expectedresult' => true,
1180 'validationerror' => false
1186 * @param array $customdata The data we are providing to the webservice.
1187 * @param bool $expectedresult The result we are expecting to receive from the webservice.
1188 * @param bool $validationerror The validationerror we are expecting to receive from the webservice.
1189 * @dataProvider submit_user_enrolment_form_provider
1191 public function test_submit_user_enrolment_form($customdata, $expectedresult, $validationerror) {
1192 global $CFG, $DB;
1194 $this->resetAfterTest(true);
1195 $datagen = $this->getDataGenerator();
1197 /** @var enrol_manual_plugin $manualplugin */
1198 $manualplugin = enrol_get_plugin('manual');
1200 $studentroleid = $DB->get_field('role', 'id', ['shortname' => 'student'], MUST_EXIST);
1201 $teacherroleid = $DB->get_field('role', 'id', ['shortname' => 'editingteacher'], MUST_EXIST);
1202 $course = $datagen->create_course();
1203 $user = $datagen->create_user();
1204 $teacher = $datagen->create_user();
1206 $instanceid = null;
1207 $instances = enrol_get_instances($course->id, true);
1208 foreach ($instances as $inst) {
1209 if ($inst->enrol == 'manual') {
1210 $instanceid = (int)$inst->id;
1211 break;
1214 if (empty($instanceid)) {
1215 $instanceid = $manualplugin->add_default_instance($course);
1216 if (empty($instanceid)) {
1217 $instanceid = $manualplugin->add_instance($course);
1220 $this->assertNotNull($instanceid);
1222 $instance = $DB->get_record('enrol', ['id' => $instanceid], '*', MUST_EXIST);
1223 $manualplugin->enrol_user($instance, $user->id, $studentroleid, 0, 0, ENROL_USER_ACTIVE);
1224 $manualplugin->enrol_user($instance, $teacher->id, $teacherroleid, 0, 0, ENROL_USER_ACTIVE);
1225 $ueid = (int) $DB->get_field(
1226 'user_enrolments',
1227 'id',
1228 ['enrolid' => $instance->id, 'userid' => $user->id],
1229 MUST_EXIST
1232 // Login as teacher.
1233 $teacher->ignoresesskey = true;
1234 $this->setUser($teacher);
1236 $formdata = [
1237 'ue' => $ueid,
1238 'ifilter' => 0,
1239 'status' => null,
1240 'timestart' => null,
1241 'duration' => null,
1242 'timeend' => null,
1245 $formdata = array_merge($formdata, $customdata);
1247 require_once("$CFG->dirroot/enrol/editenrolment_form.php");
1248 $formdata = enrol_user_enrolment_form::mock_generate_submit_keys($formdata);
1250 $querystring = http_build_query($formdata, '', '&');
1252 $result = external_api::clean_returnvalue(
1253 core_enrol_external::submit_user_enrolment_form_returns(),
1254 core_enrol_external::submit_user_enrolment_form($querystring)
1257 $this->assertEqualsCanonicalizing(
1258 ['result' => $expectedresult, 'validationerror' => $validationerror],
1259 $result);
1261 if ($result['result']) {
1262 $ue = $DB->get_record('user_enrolments', ['id' => $ueid], '*', MUST_EXIST);
1263 $this->assertEquals($formdata['status'], $ue->status);
1268 * Test for core_enrol_external::unenrol_user_enrolment().
1270 public function test_unenerol_user_enrolment() {
1271 global $DB;
1273 $this->resetAfterTest(true);
1274 $datagen = $this->getDataGenerator();
1276 /** @var enrol_manual_plugin $manualplugin */
1277 $manualplugin = enrol_get_plugin('manual');
1278 $this->assertNotNull($manualplugin);
1280 $studentroleid = $DB->get_field('role', 'id', ['shortname' => 'student'], MUST_EXIST);
1281 $teacherroleid = $DB->get_field('role', 'id', ['shortname' => 'editingteacher'], MUST_EXIST);
1282 $course = $datagen->create_course();
1283 $user = $datagen->create_user();
1284 $teacher = $datagen->create_user();
1286 $instanceid = null;
1287 $instances = enrol_get_instances($course->id, true);
1288 foreach ($instances as $inst) {
1289 if ($inst->enrol == 'manual') {
1290 $instanceid = (int)$inst->id;
1291 break;
1294 if (empty($instanceid)) {
1295 $instanceid = $manualplugin->add_default_instance($course);
1296 if (empty($instanceid)) {
1297 $instanceid = $manualplugin->add_instance($course);
1300 $this->assertNotNull($instanceid);
1302 $instance = $DB->get_record('enrol', ['id' => $instanceid], '*', MUST_EXIST);
1303 $manualplugin->enrol_user($instance, $user->id, $studentroleid, 0, 0, ENROL_USER_ACTIVE);
1304 $manualplugin->enrol_user($instance, $teacher->id, $teacherroleid, 0, 0, ENROL_USER_ACTIVE);
1305 $ueid = (int)$DB->get_field(
1306 'user_enrolments',
1307 'id',
1308 ['enrolid' => $instance->id, 'userid' => $user->id],
1309 MUST_EXIST
1312 // Login as teacher.
1313 $this->setUser($teacher);
1315 // Invalid data by passing invalid ueid.
1316 $data = core_enrol_external::unenrol_user_enrolment(101010);
1317 $data = external_api::clean_returnvalue(core_enrol_external::unenrol_user_enrolment_returns(), $data);
1318 $this->assertFalse($data['result']);
1319 $this->assertNotEmpty($data['errors']);
1321 // Valid data.
1322 $data = core_enrol_external::unenrol_user_enrolment($ueid);
1323 $data = external_api::clean_returnvalue(core_enrol_external::unenrol_user_enrolment_returns(), $data);
1324 $this->assertTrue($data['result']);
1325 $this->assertEmpty($data['errors']);
1327 // Check unenrol user enrolment.
1328 $ue = $DB->count_records('user_enrolments', ['id' => $ueid]);
1329 $this->assertEquals(0, $ue);
1333 * Test for core_enrol_external::test_search_users().
1335 public function test_search_users() {
1336 global $DB;
1338 $this->resetAfterTest(true);
1339 $datagen = $this->getDataGenerator();
1341 /** @var enrol_manual_plugin $manualplugin */
1342 $manualplugin = enrol_get_plugin('manual');
1343 $this->assertNotNull($manualplugin);
1345 $studentroleid = $DB->get_field('role', 'id', ['shortname' => 'student'], MUST_EXIST);
1346 $teacherroleid = $DB->get_field('role', 'id', ['shortname' => 'editingteacher'], MUST_EXIST);
1348 $course1 = $datagen->create_course();
1349 $course2 = $datagen->create_course();
1351 $user1 = $datagen->create_user(['firstname' => 'user 1']);
1352 $user2 = $datagen->create_user(['firstname' => 'user 2']);
1353 $user3 = $datagen->create_user(['firstname' => 'user 3']);
1354 $teacher = $datagen->create_user(['firstname' => 'user 4']);
1356 $instanceid = null;
1357 $instances = enrol_get_instances($course1->id, true);
1358 foreach ($instances as $inst) {
1359 if ($inst->enrol == 'manual') {
1360 $instanceid = (int)$inst->id;
1361 break;
1364 if (empty($instanceid)) {
1365 $instanceid = $manualplugin->add_default_instance($course1);
1366 if (empty($instanceid)) {
1367 $instanceid = $manualplugin->add_instance($course1);
1370 $this->assertNotNull($instanceid);
1372 $instance = $DB->get_record('enrol', ['id' => $instanceid], '*', MUST_EXIST);
1373 $manualplugin->enrol_user($instance, $user1->id, $studentroleid, 0, 0, ENROL_USER_ACTIVE);
1374 $manualplugin->enrol_user($instance, $user2->id, $studentroleid, 0, 0, ENROL_USER_ACTIVE);
1375 $manualplugin->enrol_user($instance, $user3->id, $studentroleid, 0, 0, ENROL_USER_ACTIVE);
1376 $manualplugin->enrol_user($instance, $teacher->id, $teacherroleid, 0, 0, ENROL_USER_ACTIVE);
1378 $this->setUser($teacher);
1380 // Search for users in a course with enrolled users.
1381 $result = core_enrol_external::search_users($course1->id, 'user', true, 0, 30);
1382 $this->assertCount(4, $result);
1384 $this->expectException('moodle_exception');
1385 // Search for users in a course without any enrolled users, shouldn't return anything.
1386 $result = core_enrol_external::search_users($course2->id, 'user', true, 0, 30);
1387 $this->assertCount(0, $result);
1389 // Search for invalid first name.
1390 $result = core_enrol_external::search_users($course1->id, 'yada yada', true, 0, 30);
1391 $this->assertCount(0, $result);
1393 // Test pagination, it should return only 3 users.
1394 $result = core_enrol_external::search_users($course1->id, 'user', true, 0, 3);
1395 $this->assertCount(3, $result);
1397 // Test pagination, it should return only 3 users.
1398 $result = core_enrol_external::search_users($course1->id, 'user 1', true, 0, 1);
1399 $result = $result[0];
1400 $this->assertEquals($user1->id, $result['id']);
1401 $this->assertEquals($user1->email, $result['email']);
1402 $this->assertEquals(fullname($user1), $result['fullname']);
1404 $this->setUser($user1);
1406 // Search for users in a course with enrolled users.
1407 $result = core_enrol_external::search_users($course1->id, 'user', true, 0, 30);
1408 $this->assertCount(4, $result);
1410 $this->expectException('moodle_exception');
1411 // Search for users in a course without any enrolled users, shouldn't return anything.
1412 $result = core_enrol_external::search_users($course2->id, 'user', true, 0, 30);
1413 $this->assertCount(0, $result);
1415 // Search for invalid first name.
1416 $result = core_enrol_external::search_users($course1->id, 'yada yada', true, 0, 30);
1417 $this->assertCount(0, $result);
1421 * Tests the get_potential_users external function (not too much detail because the back-end
1422 * is covered in another test).
1424 public function test_get_potential_users(): void {
1425 $this->resetAfterTest();
1427 // Create a couple of custom profile fields, one of which is in user identity.
1428 $generator = $this->getDataGenerator();
1429 $generator->create_custom_profile_field(['datatype' => 'text',
1430 'shortname' => 'researchtopic', 'name' => 'Research topic']);
1431 $generator->create_custom_profile_field(['datatype' => 'text',
1432 'shortname' => 'specialid', 'name' => 'Special id']);
1433 set_config('showuseridentity', 'department,profile_field_specialid');
1435 // Create a course.
1436 $course = $generator->create_course();
1438 // Get enrol id for manual enrol plugin.
1439 foreach (enrol_get_instances($course->id, true) as $instance) {
1440 if ($instance->enrol === 'manual') {
1441 $enrolid = $instance->id;
1445 // Create a couple of test users.
1446 $user1 = $generator->create_user(['firstname' => 'Eigh', 'lastname' => 'User',
1447 'department' => 'Amphibians', 'profile_field_specialid' => 'Q123',
1448 'profile_field_researchtopic' => 'Frogs']);
1449 $user2 = $generator->create_user(['firstname' => 'Anne', 'lastname' => 'Other',
1450 'department' => 'Amphibians', 'profile_field_specialid' => 'Q456',
1451 'profile_field_researchtopic' => 'Toads']);
1453 // Do this as admin user.
1454 $this->setAdminUser();
1456 // Get potential users and extract the 2 we care about.
1457 $result = core_enrol_external::get_potential_users($course->id, $enrolid, '', false, 0, 10);
1458 $result1 = $this->extract_user_from_result($result, $user1->id);
1459 $result2 = $this->extract_user_from_result($result, $user2->id);
1461 // Check the fields are the expected ones.
1462 $this->assertEquals(['id', 'fullname', 'customfields',
1463 'profileimageurl', 'profileimageurlsmall', 'department'], array_keys($result1));
1464 $this->assertEquals('Eigh User', $result1['fullname']);
1465 $this->assertEquals('Amphibians', $result1['department']);
1467 // Check the custom fields ONLY include the user identity one.
1468 $fieldvalues = [];
1469 foreach ($result1['customfields'] as $customfield) {
1470 $fieldvalues[$customfield['shortname']] = $customfield['value'];
1472 $this->assertEquals(['specialid'], array_keys($fieldvalues));
1473 $this->AssertEquals('Q123', $fieldvalues['specialid']);
1475 // Just check user 2 is the right user.
1476 $this->assertEquals('Anne Other', $result2['fullname']);
1480 * Utility function to get one user out of the get_potential_users result.
1482 * @param array $result Result array
1483 * @param int $userid User id
1484 * @return array Data for that user
1486 protected function extract_user_from_result(array $result, int $userid): array {
1487 foreach ($result as $item) {
1488 if ($item['id'] == $userid) {
1489 return $item;
1492 $this->fail('User not in result: ' . $userid);