MDL-65809 environment: mbstring extension required
[moodle.git] / enrol / tests / externallib_test.php
blobe7b93189b85532a140584daa7e538675f781a529
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 defined('MOODLE_INTERNAL') || die();
19 global $CFG;
21 require_once($CFG->dirroot . '/webservice/tests/helpers.php');
22 require_once($CFG->dirroot . '/enrol/externallib.php');
24 /**
25 * Enrol external PHPunit tests
27 * @package core_enrol
28 * @category external
29 * @copyright 2012 Jerome Mouneyrac
30 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 * @since Moodle 2.4
33 class core_enrol_externallib_testcase extends externallib_advanced_testcase {
35 /**
36 * dataProvider for test_get_enrolled_users_visibility().
38 public function get_enrolled_users_visibility_provider() {
39 return array(
40 'Course without groups, default behavior (not filtering by cap, group, active)' =>
41 array(
42 'settings' => array(
43 'coursegroupmode' => NOGROUPS,
44 'withcapability' => null,
45 'groupid' => null,
46 'onlyactive' => false,
47 'allowedcaps' => array(),
49 'results' => array( // Everybody can view everybody.
50 'user0' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
51 'user1' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
52 'user2' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
53 'user31' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
54 'userall' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
58 'Course with visible groups, default behavior (not filtering by cap, group, active)' =>
59 array(
60 'settings' => array(
61 'coursegroupmode' => VISIBLEGROUPS,
62 'withcapability' => null,
63 'groupid' => null,
64 'onlyactive' => false,
65 'allowedcaps' => array(),
67 'results' => array( // Everybody can view everybody.
68 'user0' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
69 'user1' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
70 'user2' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
71 'user31' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
72 'userall' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
76 'Course with separate groups, default behavior (not filtering by cap, group, active)' =>
77 array(
78 'settings' => array(
79 'coursegroupmode' => SEPARATEGROUPS,
80 'withcapability' => null,
81 'groupid' => null,
82 'onlyactive' => false,
83 'allowedcaps' => array(),
85 'results' => array( // Only users from own groups are visible.
86 'user0' => array('canview' => array()), // Poor guy, cannot see anybody, himself included.
87 'user1' => array('canview' => array('user1', 'userall')),
88 'user2' => array('canview' => array('user2', 'user2su', 'userall')),
89 'user31' => array('canview' => array('user31', 'user32', 'userall')),
90 'userall' => array('canview' => array('user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
94 'Course with separate groups, default behavior (not filtering but having moodle/site:accessallgroups)' =>
95 array(
96 'settings' => array(
97 'coursegroupmode' => VISIBLEGROUPS,
98 'withcapability' => null,
99 'groupid' => null,
100 'onlyactive' => false,
101 'allowedcaps' => array('moodle/site:accessallgroups'),
103 'results' => array( // Everybody can view everybody.
104 'user0' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
105 'user1' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
106 'user2' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
107 'user31' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
108 'userall' => array('canview' => array('user0', 'user1', 'user2', 'user2su', 'user31', 'user32', 'userall')),
112 'Course with separate groups, filtering onlyactive (missing moodle/course:enrolreview)' =>
113 array(
114 'settings' => array(
115 'coursegroupmode' => SEPARATEGROUPS,
116 'withcapability' => null,
117 'groupid' => null,
118 'onlyactive' => true,
119 'allowedcaps' => array(),
121 'results' => array( // returns exception, cannot view anybody without the cap.
122 'user2' => array('exception' => array(
123 'type' => 'required_capability_exception',
124 'message' => 'Review course enrolments')),
125 'userall' => array('exception' => array(
126 'type' => 'required_capability_exception',
127 'message' => 'Review course enrolments')),
131 'Course with separate groups, filtering onlyactive (having moodle/course:enrolreview)' =>
132 array(
133 'settings' => array(
134 'coursegroupmode' => SEPARATEGROUPS,
135 'withcapability' => null,
136 'groupid' => null,
137 'onlyactive' => true,
138 'allowedcaps' => array('moodle/course:enrolreview'),
140 'results' => array( // Suspended are not returned.
141 'user2' => array('canview' => array('user2', 'userall')),
142 'user31' => array('canview' => array('user31', 'user32', 'userall')),
143 'userall' => array('canview' => array('user1', 'user2', 'user31', 'user32', 'userall')),
147 'Course with separate groups, filtering by groupid (not having moodle/site:accessallgroups)' =>
148 array(
149 'settings' => array(
150 'coursegroupmode' => SEPARATEGROUPS,
151 'withcapability' => null,
152 'groupid' => 'group2',
153 'onlyactive' => false,
154 'allowedcaps' => array(),
156 'results' => array( // Only group 2 members and only for members. Exception for non-members.
157 'user0' => array('exception' => array(
158 'type' => 'required_capability_exception',
159 'message' => 'Access all groups')),
160 'user1' => array('exception' => array(
161 'type' => 'required_capability_exception',
162 'message' => 'Access all groups')),
163 'user2' => array('canview' => array('user2', 'user2su', 'userall')),
164 'userall' => array('canview' => array('user2', 'user2su', 'userall')),
168 'Course with separate groups, filtering by groupid (having moodle/site:accessallgroups)' =>
169 array(
170 'settings' => array(
171 'coursegroupmode' => SEPARATEGROUPS,
172 'withcapability' => null,
173 'groupid' => 'group2',
174 'onlyactive' => false,
175 'allowedcaps' => array('moodle/site:accessallgroups'),
177 'results' => array( // All users with 'moodle/site:accessallgroups' can view group 2
178 'user0' => array('canview' => array('user2', 'user2su', 'userall')),
179 'user1' => array('canview' => array('user2', 'user2su', 'userall')),
180 'user2' => array('canview' => array('user2', 'user2su', 'userall')),
181 'userall' => array('canview' => array('user2', 'user2su', 'userall')),
185 'Course with separate groups, filtering by withcapability (not having moodle/role:review)' =>
186 array(
187 'settings' => array(
188 'coursegroupmode' => SEPARATEGROUPS,
189 'withcapability' => 'moodle/course:bulkmessaging',
190 'groupid' => null,
191 'onlyactive' => false,
192 'allowedcaps' => array(),
194 'results' => array( // No user has 'moodle/role:review' so exception.
195 'user0' => array('exception' => array(
196 'type' => 'required_capability_exception',
197 'message' => 'Review permissions for others')),
198 'user1' => array('exception' => array(
199 'type' => 'required_capability_exception',
200 'message' => 'Review permissions for others')),
201 'user2' => array('exception' => array(
202 'type' => 'required_capability_exception',
203 'message' => 'Review permissions for others')),
204 'userall' => array('exception' => array(
205 'type' => 'required_capability_exception',
206 'message' => 'Review permissions for others')),
210 'Course with separate groups, filtering by withcapability (having moodle/role:review)' =>
211 array(
212 'settings' => array(
213 'coursegroupmode' => SEPARATEGROUPS,
214 'withcapability' => 'moodle/course:bulkmessaging',
215 'groupid' => null,
216 'onlyactive' => false,
217 'allowedcaps' => array('moodle/role:review'),
219 'results' => array( // No user has withcapability, but all have 'moodle/role:review'. Empties.
220 'user0' => array('canview' => array()),
221 'user1' => array('canview' => array()),
222 'user2' => array('canview' => array()),
223 'userall' => array('canview' => array()),
227 'Course with separate groups, filtering by withcapability (having moodle/role:review)' =>
228 array(
229 'settings' => array(
230 'coursegroupmode' => SEPARATEGROUPS,
231 'withcapability' => 'moodle/course:bulkmessaging',
232 'groupid' => null,
233 'onlyactive' => false,
234 'allowedcaps' => array('moodle/role:review', 'moodle/course:bulkmessaging'),
236 'results' => array( // Users (previous) have withcapability, and all have 'moodle/role:review'.
237 'user0' => array('canview' => array()),
238 'user1' => array('canview' => array('user1')),
239 'user2' => array('canview' => array('user2')),
240 'userall' => array('canview' => array('user1', 'user2', 'userall')),
247 * Verify get_enrolled_users() returned users are the expected in every situation.
249 * @dataProvider get_enrolled_users_visibility_provider
251 public function test_get_enrolled_users_visibility($settings, $results) {
253 global $USER;
255 $this->resetAfterTest();
257 // Create the course and the users.
258 $course = $this->getDataGenerator()->create_course(array('groupmode' => $settings['coursegroupmode']));
259 $coursecontext = context_course::instance($course->id);
260 $user0 = $this->getDataGenerator()->create_user(array('username' => 'user0')); // A user without group.
261 $user1 = $this->getDataGenerator()->create_user(array('username' => 'user1')); // User for group 1.
262 $user2 = $this->getDataGenerator()->create_user(array('username' => 'user2')); // Two users for group 2.
263 $user2su = $this->getDataGenerator()->create_user(array('username' => 'user2su')); // (one suspended).
264 $user31 = $this->getDataGenerator()->create_user(array('username' => 'user31')); // Two users for group 3.
265 $user32 = $this->getDataGenerator()->create_user(array('username' => 'user32')); // (both enabled).
266 $userall = $this->getDataGenerator()->create_user(array('username' => 'userall')); // A user in all groups.
268 // Create utility array of created users, to produce better assertion messages.
269 $createdusers = array();
270 foreach (array($user0, $user1, $user2, $user2su, $user31, $user32, $userall) as $createduser) {
271 $createdusers[$createduser->id] = $createduser->username;
274 // Enrol the users in the course.
275 $this->getDataGenerator()->enrol_user($user0->id, $course->id);
276 $this->getDataGenerator()->enrol_user($user1->id, $course->id);
277 $this->getDataGenerator()->enrol_user($user2->id, $course->id);
278 $this->getDataGenerator()->enrol_user($user2su->id, $course->id, null, 'manual', 0, 0, ENROL_USER_SUSPENDED);
279 $this->getDataGenerator()->enrol_user($user31->id, $course->id);
280 $this->getDataGenerator()->enrol_user($user32->id, $course->id);
281 $this->getDataGenerator()->enrol_user($userall->id, $course->id);
283 // Create 3 groups.
284 $group1 = $this->getDataGenerator()->create_group(array('courseid' => $course->id));
285 $group2 = $this->getDataGenerator()->create_group(array('courseid' => $course->id));
286 $group3 = $this->getDataGenerator()->create_group(array('courseid' => $course->id));
288 // Add the users to the groups.
289 $this->getDataGenerator()->create_group_member(array('groupid' => $group1->id, 'userid' => $user1->id));
290 $this->getDataGenerator()->create_group_member(array('groupid' => $group2->id, 'userid' => $user2->id));
291 $this->getDataGenerator()->create_group_member(array('groupid' => $group2->id, 'userid' => $user2su->id));
292 $this->getDataGenerator()->create_group_member(array('groupid' => $group3->id, 'userid' => $user31->id));
293 $this->getDataGenerator()->create_group_member(array('groupid' => $group3->id, 'userid' => $user32->id));
294 $this->getDataGenerator()->create_group_member(array('groupid' => $group1->id, 'userid' => $userall->id));
295 $this->getDataGenerator()->create_group_member(array('groupid' => $group2->id, 'userid' => $userall->id));
296 $this->getDataGenerator()->create_group_member(array('groupid' => $group3->id, 'userid' => $userall->id));
298 // Create a role to add the allowedcaps. Users will have this role assigned.
299 $roleid = $this->getDataGenerator()->create_role();
300 // Allow the specified capabilities.
301 if (!empty($settings['allowedcaps'])) {
302 foreach ($settings['allowedcaps'] as $capability) {
303 assign_capability($capability, CAP_ALLOW, $roleid, $coursecontext);
307 // For each of the users, configure everything, perform the call, and assert results.
308 foreach ($results as $user => $expectations) {
309 // Convert canview expectations into a nice array of ids for easier handling.
310 $canview = array();
311 $exception = null;
312 // Analyse the expectations.
313 if (isset($expectations['canview'])) {
314 foreach ($expectations['canview'] as $canviewuser) {
315 $canview[] = $createdusers[${$canviewuser}->id];
317 } else if (isset($expectations['exception'])) {
318 $exception = $expectations['exception'];
319 $this->expectException($exception['type']);
320 $this->expectExceptionMessage($exception['message']);
321 } else {
322 // Failed, only canview and exception are supported.
323 $this->markTestIncomplete('Incomplete, only canview and exception are supported');
325 // Switch to the user and assign the role.
326 $this->setUser(${$user});
327 role_assign($roleid, $USER->id, $coursecontext);
329 // Convert groupid to proper id.
330 $groupid = 0;
331 if (isset($settings['groupid'])) {
332 $groupid = ${$settings['groupid']}->id;
335 // Call to the function.
336 $options = array(
337 array('name' => 'withcapability', 'value' => $settings['withcapability']),
338 array('name' => 'groupid', 'value' => $groupid),
339 array('name' => 'onlyactive', 'value' => $settings['onlyactive']),
340 array('name' => 'userfields', 'value' => 'id')
342 $enrolledusers = core_enrol_external::get_enrolled_users($course->id, $options);
344 // We need to execute the return values cleaning process to simulate the web service server.
345 $enrolledusers = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_returns(), $enrolledusers);
347 // We are only interested in ids to check visibility.
348 $viewed = array();
349 // Verify the user canview the expected users.
350 foreach ($enrolledusers as $enrolleduser) {
351 $viewed[] = $createdusers[$enrolleduser['id']];
353 // Verify viewed matches canview expectation (using canonicalize to ignore ordering).
354 $this->assertEquals($canview, $viewed, "Problem checking visible users for '{$createdusers[$USER->id]}'", 0, 1, true);
359 * Test get_users_courses
361 public function test_get_users_courses() {
362 global $CFG, $DB;
363 require_once($CFG->dirroot . '/completion/criteria/completion_criteria_self.php');
365 $this->resetAfterTest(true);
366 $CFG->enablecompletion = 1;
368 $timenow = time();
369 $coursedata1 = array(
370 'fullname' => '<b>Course 1</b>', // Adding tags here to check that external_format_string works.
371 'shortname' => '<b>Course 1</b>', // Adding tags here to check that external_format_string works.
372 'summary' => 'Lightwork Course 1 description',
373 'summaryformat' => FORMAT_MOODLE,
374 'lang' => 'en',
375 'enablecompletion' => true,
376 'showgrades' => true,
377 'startdate' => $timenow,
378 'enddate' => $timenow + WEEKSECS,
379 'marker' => 1
382 $coursedata2 = array(
383 'lang' => 'kk', // Check invalid language pack.
386 $course1 = self::getDataGenerator()->create_course($coursedata1);
387 $course2 = self::getDataGenerator()->create_course($coursedata2);
388 $courses = array($course1, $course2);
389 $contexts = array ($course1->id => context_course::instance($course1->id),
390 $course2->id => context_course::instance($course2->id));
392 $student = $this->getDataGenerator()->create_user();
393 $otherstudent = $this->getDataGenerator()->create_user();
394 $studentroleid = $DB->get_field('role', 'id', array('shortname' => 'student'));
395 $this->getDataGenerator()->enrol_user($student->id, $course1->id, $studentroleid);
396 $this->getDataGenerator()->enrol_user($otherstudent->id, $course1->id, $studentroleid);
397 $this->getDataGenerator()->enrol_user($student->id, $course2->id, $studentroleid);
399 // Force last access.
400 $timenow = time();
401 $lastaccess = array(
402 'userid' => $student->id,
403 'courseid' => $course1->id,
404 'timeaccess' => $timenow
406 $DB->insert_record('user_lastaccess', $lastaccess);
408 // Force completion, setting at least one criteria.
409 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_self.php');
410 $criteriadata = new stdClass();
411 $criteriadata->id = $course1->id;
412 // Self completion.
413 $criteriadata->criteria_self = 1;
415 $criterion = new completion_criteria_self();
416 $criterion->update_config($criteriadata);
418 $ccompletion = new completion_completion(array('course' => $course1->id, 'userid' => $student->id));
419 $ccompletion->mark_complete();
421 // Set course hidden and favourited.
422 set_user_preference('block_myoverview_hidden_course_' . $course1->id, 1, $student);
423 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($student->id));
424 $ufservice->create_favourite('core_course', 'courses', $course1->id, \context_system::instance());
426 $this->setUser($student);
427 // Call the external function.
428 $enrolledincourses = core_enrol_external::get_users_courses($student->id);
430 // We need to execute the return values cleaning process to simulate the web service server.
431 $enrolledincourses = external_api::clean_returnvalue(core_enrol_external::get_users_courses_returns(), $enrolledincourses);
433 // Check we retrieve the good total number of enrolled users.
434 $this->assertEquals(2, count($enrolledincourses));
436 // We need to format summary and summaryformat before to compare them with those values returned by the webservice.
437 list($course1->summary, $course1->summaryformat) =
438 external_format_text($course1->summary, $course1->summaryformat, $contexts[$course1->id]->id, 'course', 'summary', 0);
440 // Check there are no differences between $course1 properties and course values returned by the webservice
441 // only for those fields listed in the $coursedata1 array.
442 $course1->fullname = external_format_string($course1->fullname, $contexts[$course1->id]->id);
443 $course1->shortname = external_format_string($course1->shortname, $contexts[$course1->id]->id);
444 foreach ($enrolledincourses as $courseenrol) {
445 if ($courseenrol['id'] == $course1->id) {
446 foreach ($coursedata1 as $fieldname => $value) {
447 $this->assertEquals($courseenrol[$fieldname], $course1->$fieldname);
449 // Text extra fields.
450 $this->assertEquals($course1->fullname, $courseenrol['displayname']);
451 $this->assertEquals([], $courseenrol['overviewfiles']);
452 $this->assertEquals($timenow, $courseenrol['lastaccess']);
453 $this->assertEquals(100.0, $courseenrol['progress']);
454 $this->assertEquals(true, $courseenrol['completed']);
455 $this->assertTrue($courseenrol['completionhascriteria']);
456 $this->assertTrue($courseenrol['hidden']);
457 $this->assertTrue($courseenrol['isfavourite']);
458 } else {
459 // Check language pack. Should be empty since an incorrect one was used when creating the course.
460 $this->assertEmpty($courseenrol['lang']);
461 $this->assertEquals($course2->fullname, $courseenrol['displayname']);
462 $this->assertEquals([], $courseenrol['overviewfiles']);
463 $this->assertEquals(0, $courseenrol['lastaccess']);
464 $this->assertEquals(0, $courseenrol['progress']);
465 $this->assertEquals(false, $courseenrol['completed']);
466 $this->assertFalse($courseenrol['completionhascriteria']);
467 $this->assertFalse($courseenrol['hidden']);
468 $this->assertFalse($courseenrol['isfavourite']);
472 // Now check that admin users can see all the info.
473 $this->setAdminUser();
475 $enrolledincourses = core_enrol_external::get_users_courses($student->id);
476 $enrolledincourses = external_api::clean_returnvalue(core_enrol_external::get_users_courses_returns(), $enrolledincourses);
477 $this->assertEquals(2, count($enrolledincourses));
478 foreach ($enrolledincourses as $courseenrol) {
479 if ($courseenrol['id'] == $course1->id) {
480 $this->assertEquals($timenow, $courseenrol['lastaccess']);
481 $this->assertEquals(100.0, $courseenrol['progress']);
482 $this->assertTrue($courseenrol['completionhascriteria']);
483 $this->assertFalse($courseenrol['isfavourite']); // This always false.
484 $this->assertFalse($courseenrol['hidden']); // This always false.
485 } else {
486 $this->assertEquals(0, $courseenrol['progress']);
487 $this->assertFalse($courseenrol['completionhascriteria']);
488 $this->assertFalse($courseenrol['isfavourite']); // This always false.
489 $this->assertFalse($courseenrol['hidden']); // This always false.
493 // Check other users can't see private info.
494 $this->setUser($otherstudent);
496 $enrolledincourses = core_enrol_external::get_users_courses($student->id);
497 $enrolledincourses = external_api::clean_returnvalue(core_enrol_external::get_users_courses_returns(), $enrolledincourses);
498 $this->assertEquals(1, count($enrolledincourses));
500 $this->assertEquals($timenow, $enrolledincourses[0]['lastaccess']); // I can see this, not hidden.
501 $this->assertEquals(null, $enrolledincourses[0]['progress']); // I can't see this, private.
503 // Change some global profile visibility fields.
504 $CFG->hiddenuserfields = 'lastaccess';
505 $enrolledincourses = core_enrol_external::get_users_courses($student->id);
506 $enrolledincourses = external_api::clean_returnvalue(core_enrol_external::get_users_courses_returns(), $enrolledincourses);
508 $this->assertEquals(0, $enrolledincourses[0]['lastaccess']); // I can't see this, hidden by global setting.
512 * Test get_course_enrolment_methods
514 public function test_get_course_enrolment_methods() {
515 global $DB;
517 $this->resetAfterTest(true);
519 // Get enrolment plugins.
520 $selfplugin = enrol_get_plugin('self');
521 $this->assertNotEmpty($selfplugin);
522 $manualplugin = enrol_get_plugin('manual');
523 $this->assertNotEmpty($manualplugin);
525 $studentrole = $DB->get_record('role', array('shortname'=>'student'));
526 $this->assertNotEmpty($studentrole);
528 $course1 = self::getDataGenerator()->create_course();
529 $coursedata = new stdClass();
530 $coursedata->visible = 0;
531 $course2 = self::getDataGenerator()->create_course($coursedata);
533 // Add enrolment methods for course.
534 $instanceid1 = $selfplugin->add_instance($course1, array('status' => ENROL_INSTANCE_ENABLED,
535 'name' => 'Test instance 1',
536 'customint6' => 1,
537 'roleid' => $studentrole->id));
538 $instanceid2 = $selfplugin->add_instance($course1, array('status' => ENROL_INSTANCE_DISABLED,
539 'name' => 'Test instance 2',
540 'roleid' => $studentrole->id));
542 $instanceid3 = $manualplugin->add_instance($course1, array('status' => ENROL_INSTANCE_ENABLED,
543 'name' => 'Test instance 3'));
545 $enrolmentmethods = $DB->get_records('enrol', array('courseid' => $course1->id, 'status' => ENROL_INSTANCE_ENABLED));
546 $this->assertCount(2, $enrolmentmethods);
548 $this->setAdminUser();
550 // Check if information is returned.
551 $enrolmentmethods = core_enrol_external::get_course_enrolment_methods($course1->id);
552 $enrolmentmethods = external_api::clean_returnvalue(core_enrol_external::get_course_enrolment_methods_returns(),
553 $enrolmentmethods);
554 // Enrolment information is currently returned by self enrolment plugin, so count == 1.
555 // This should be changed as we implement get_enrol_info() for other enrolment plugins.
556 $this->assertCount(1, $enrolmentmethods);
558 $enrolmentmethod = $enrolmentmethods[0];
559 $this->assertEquals($course1->id, $enrolmentmethod['courseid']);
560 $this->assertEquals('self', $enrolmentmethod['type']);
561 $this->assertTrue($enrolmentmethod['status']);
562 $this->assertFalse(isset($enrolmentmethod['wsfunction']));
564 $instanceid4 = $selfplugin->add_instance($course2, array('status' => ENROL_INSTANCE_ENABLED,
565 'name' => 'Test instance 4',
566 'roleid' => $studentrole->id,
567 'customint6' => 1,
568 'password' => 'test'));
569 $enrolmentmethods = core_enrol_external::get_course_enrolment_methods($course2->id);
570 $enrolmentmethods = external_api::clean_returnvalue(core_enrol_external::get_course_enrolment_methods_returns(),
571 $enrolmentmethods);
572 $this->assertCount(1, $enrolmentmethods);
574 $enrolmentmethod = $enrolmentmethods[0];
575 $this->assertEquals($course2->id, $enrolmentmethod['courseid']);
576 $this->assertEquals('self', $enrolmentmethod['type']);
577 $this->assertTrue($enrolmentmethod['status']);
578 $this->assertEquals('enrol_self_get_instance_info', $enrolmentmethod['wsfunction']);
580 // Try to retrieve information using a normal user for a hidden course.
581 $user = self::getDataGenerator()->create_user();
582 $this->setUser($user);
583 try {
584 core_enrol_external::get_course_enrolment_methods($course2->id);
585 } catch (moodle_exception $e) {
586 $this->assertEquals('coursehidden', $e->errorcode);
590 public function get_enrolled_users_setup($capability) {
591 global $USER;
593 $this->resetAfterTest(true);
595 $return = new stdClass();
597 $return->course = self::getDataGenerator()->create_course();
598 $return->user1 = self::getDataGenerator()->create_user();
599 $return->user2 = self::getDataGenerator()->create_user();
600 $return->user3 = self::getDataGenerator()->create_user();
601 $this->setUser($return->user3);
603 // Set the required capabilities by the external function.
604 $return->context = context_course::instance($return->course->id);
605 $return->roleid = $this->assignUserCapability($capability, $return->context->id);
606 $this->assignUserCapability('moodle/user:viewdetails', $return->context->id, $return->roleid);
608 // Enrol the users in the course.
609 $this->getDataGenerator()->enrol_user($return->user1->id, $return->course->id, $return->roleid, 'manual');
610 $this->getDataGenerator()->enrol_user($return->user2->id, $return->course->id, $return->roleid, 'manual');
611 $this->getDataGenerator()->enrol_user($return->user3->id, $return->course->id, $return->roleid, 'manual');
613 return $return;
617 * Test get_enrolled_users from core_enrol_external without additional
618 * parameters.
620 public function test_get_enrolled_users_without_parameters() {
621 $capability = 'moodle/course:viewparticipants';
622 $data = $this->get_enrolled_users_setup($capability);
624 // Call the external function.
625 $enrolledusers = core_enrol_external::get_enrolled_users($data->course->id);
627 // We need to execute the return values cleaning process to simulate the web service server.
628 $enrolledusers = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_returns(), $enrolledusers);
630 // Check the result set.
631 $this->assertEquals(3, count($enrolledusers));
632 $this->assertArrayHasKey('email', $enrolledusers[0]);
636 * Test get_enrolled_users from core_enrol_external with some parameters set.
638 public function test_get_enrolled_users_with_parameters() {
639 $capability = 'moodle/course:viewparticipants';
640 $data = $this->get_enrolled_users_setup($capability);
642 // Call the function with some parameters set.
643 $enrolledusers = core_enrol_external::get_enrolled_users($data->course->id, array(
644 array('name' => 'limitfrom', 'value' => 2),
645 array('name' => 'limitnumber', 'value' => 1),
646 array('name' => 'userfields', 'value' => 'id')
649 // We need to execute the return values cleaning process to simulate the web service server.
650 $enrolledusers = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_returns(), $enrolledusers);
652 // Check the result set, we should only get the 3rd result, which is $user3.
653 $this->assertCount(1, $enrolledusers);
654 $this->assertEquals($data->user3->id, $enrolledusers[0]['id']);
655 $this->assertArrayHasKey('id', $enrolledusers[0]);
656 $this->assertArrayNotHasKey('email', $enrolledusers[0]);
660 * Test get_enrolled_users from core_enrol_external with capability to
661 * viewparticipants removed.
663 * @expectedException moodle_exception
665 public function test_get_enrolled_users_without_capability() {
666 $capability = 'moodle/course:viewparticipants';
667 $data = $this->get_enrolled_users_setup($capability);
669 // Call without required capability.
670 $this->unassignUserCapability($capability, $data->context->id, $data->roleid);
671 $categories = core_enrol_external::get_enrolled_users($data->course->id);
674 public function get_enrolled_users_with_capability_setup($capability) {
675 global $USER, $DB;
677 $this->resetAfterTest(true);
679 $return = new stdClass();
681 // Create the course and fetch its context.
682 $return->course = self::getDataGenerator()->create_course();
683 $context = context_course::instance($return->course->id);
685 // Create one teacher, and two students.
686 $return->teacher = self::getDataGenerator()->create_user();
687 $return->student1 = self::getDataGenerator()->create_user();
688 $return->student2 = self::getDataGenerator()->create_user();
690 // Create a new student role based on the student archetype but with the capability prohibitted.
691 $fakestudentroleid = create_role('Fake student role', 'fakestudent', 'Fake student role', 'student');
692 assign_capability($capability, CAP_PROHIBIT, $fakestudentroleid, $context->id);
694 // Enrol all of the users in the course.
695 // * 'teacher' is an editing teacher.
696 // * 'student1' is a standard student.
697 // * 'student2' is a student with the capability prohibitted.
698 $editingteacherroleid = $DB->get_field('role', 'id', array('shortname' => 'editingteacher'));
699 $studentroleid = $DB->get_field('role', 'id', array('shortname' => 'student'));
700 $this->getDataGenerator()->enrol_user($return->teacher->id, $return->course->id, $editingteacherroleid);
701 $this->getDataGenerator()->enrol_user($return->student1->id, $return->course->id, $studentroleid);
702 $this->getDataGenerator()->enrol_user($return->student2->id, $return->course->id, $fakestudentroleid);
704 // Log in as the teacher.
705 $this->setUser($return->teacher);
707 // Clear caches.
708 accesslib_clear_all_caches_for_unit_testing();
710 return $return;
714 * Test get_enrolled_users_with_capability without additional paramaters.
716 public function test_get_enrolled_users_with_capability_without_parameters() {
717 $capability = 'moodle/course:viewparticipants';
718 $data = $this->get_enrolled_users_with_capability_setup($capability);
720 $result = core_enrol_external::get_enrolled_users_with_capability(
721 array(
722 'coursecapabilities' => array(
723 'courseid' => $data->course->id,
724 'capabilities' => array(
725 $capability,
729 array()
732 // We need to execute the return values cleaning process to simulate the web service server.
733 $result = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_with_capability_returns(), $result);
735 // Check an array containing the expected user for the course capability is returned.
736 $expecteduserlist = $result[0];
737 $this->assertEquals($data->course->id, $expecteduserlist['courseid']);
738 $this->assertEquals($capability, $expecteduserlist['capability']);
739 $this->assertEquals(2, count($expecteduserlist['users']));
743 * Test get_enrolled_users_with_capability
745 public function test_get_enrolled_users_with_capability_with_parameters () {
746 $capability = 'moodle/course:viewparticipants';
747 $data = $this->get_enrolled_users_with_capability_setup($capability);
749 $result = core_enrol_external::get_enrolled_users_with_capability(
750 array(
751 'coursecapabilities' => array(
752 'courseid' => $data->course->id,
753 'capabilities' => array(
754 $capability,
758 array(
759 array('name' => 'limitfrom', 'value' => 1),
760 array('name' => 'limitnumber', 'value' => 1),
761 array('name' => 'userfields', 'value' => 'id')
765 // We need to execute the return values cleaning process to simulate the web service server.
766 $result = external_api::clean_returnvalue(core_enrol_external::get_enrolled_users_with_capability_returns(), $result);
768 // Check an array containing the expected user for the course capability is returned.
769 $expecteduserlist = $result[0]['users'];
770 $expecteduser = reset($expecteduserlist);
771 $this->assertEquals(1, count($expecteduserlist));
772 $this->assertEquals($data->student1->id, $expecteduser['id']);
776 * Test for core_enrol_external::edit_user_enrolment().
778 public function test_edit_user_enrolment() {
779 global $DB;
781 $this->resetAfterTest(true);
782 $datagen = $this->getDataGenerator();
784 /** @var enrol_manual_plugin $manualplugin */
785 $manualplugin = enrol_get_plugin('manual');
786 $this->assertNotNull($manualplugin);
788 $studentroleid = $DB->get_field('role', 'id', ['shortname' => 'student'], MUST_EXIST);
789 $teacherroleid = $DB->get_field('role', 'id', ['shortname' => 'editingteacher'], MUST_EXIST);
790 $course = $datagen->create_course();
791 $user = $datagen->create_user();
792 $teacher = $datagen->create_user();
794 $instanceid = null;
795 $instances = enrol_get_instances($course->id, true);
796 foreach ($instances as $inst) {
797 if ($inst->enrol == 'manual') {
798 $instanceid = (int)$inst->id;
799 break;
802 if (empty($instanceid)) {
803 $instanceid = $manualplugin->add_default_instance($course);
804 if (empty($instanceid)) {
805 $instanceid = $manualplugin->add_instance($course);
808 $this->assertNotNull($instanceid);
810 $instance = $DB->get_record('enrol', ['id' => $instanceid], '*', MUST_EXIST);
811 $manualplugin->enrol_user($instance, $user->id, $studentroleid, 0, 0, ENROL_USER_ACTIVE);
812 $manualplugin->enrol_user($instance, $teacher->id, $teacherroleid, 0, 0, ENROL_USER_ACTIVE);
813 $ueid = (int)$DB->get_field(
814 'user_enrolments',
815 'id',
816 ['enrolid' => $instance->id, 'userid' => $user->id],
817 MUST_EXIST
820 // Login as teacher.
821 $this->setUser($teacher);
823 $now = new DateTime();
824 $nowtime = $now->getTimestamp();
826 // Invalid data.
827 $data = core_enrol_external::edit_user_enrolment($course->id, $ueid, ENROL_USER_ACTIVE, $nowtime, $nowtime);
828 $data = external_api::clean_returnvalue(core_enrol_external::edit_user_enrolment_returns(), $data);
829 $this->assertFalse($data['result']);
830 $this->assertNotEmpty($data['errors']);
832 // Valid data.
833 $nextmonth = clone($now);
834 $nextmonth->add(new DateInterval('P1M'));
835 $nextmonthtime = $nextmonth->getTimestamp();
836 $data = core_enrol_external::edit_user_enrolment($course->id, $ueid, ENROL_USER_ACTIVE, $nowtime, $nextmonthtime);
837 $data = external_api::clean_returnvalue(core_enrol_external::edit_user_enrolment_returns(), $data);
838 $this->assertTrue($data['result']);
839 $this->assertEmpty($data['errors']);
841 // Check updated user enrolment.
842 $ue = $DB->get_record('user_enrolments', ['id' => $ueid], '*', MUST_EXIST);
843 $this->assertEquals(ENROL_USER_ACTIVE, $ue->status);
844 $this->assertEquals($nowtime, $ue->timestart);
845 $this->assertEquals($nextmonthtime, $ue->timeend);
847 // Suspend user.
848 $data = core_enrol_external::edit_user_enrolment($course->id, $ueid, ENROL_USER_SUSPENDED);
849 $data = external_api::clean_returnvalue(core_enrol_external::edit_user_enrolment_returns(), $data);
850 $this->assertTrue($data['result']);
851 $this->assertEmpty($data['errors']);
853 // Check updated user enrolment.
854 $ue = $DB->get_record('user_enrolments', ['id' => $ueid], '*', MUST_EXIST);
855 $this->assertEquals(ENROL_USER_SUSPENDED, $ue->status);
859 * dataProvider for test_submit_user_enrolment_form().
861 public function submit_user_enrolment_form_provider() {
862 $now = new DateTime();
864 $nextmonth = clone($now);
865 $nextmonth->add(new DateInterval('P1M'));
867 return [
868 'Invalid data' => [
869 'customdata' => [
870 'status' => ENROL_USER_ACTIVE,
871 'timestart' => [
872 'day' => $now->format('j'),
873 'month' => $now->format('n'),
874 'year' => $now->format('Y'),
875 'hour' => $now->format('G'),
876 'minute' => 0,
877 'enabled' => 1,
879 'timeend' => [
880 'day' => $now->format('j'),
881 'month' => $now->format('n'),
882 'year' => $now->format('Y'),
883 'hour' => $now->format('G'),
884 'minute' => 0,
885 'enabled' => 1,
888 'expectedresult' => false,
889 'validationerror' => true
891 'Valid data' => [
892 'customdata' => [
893 'status' => ENROL_USER_ACTIVE,
894 'timestart' => [
895 'day' => $now->format('j'),
896 'month' => $now->format('n'),
897 'year' => $now->format('Y'),
898 'hour' => $now->format('G'),
899 'minute' => 0,
900 'enabled' => 1,
902 'timeend' => [
903 'day' => $nextmonth->format('j'),
904 'month' => $nextmonth->format('n'),
905 'year' => $nextmonth->format('Y'),
906 'hour' => $nextmonth->format('G'),
907 'minute' => 0,
908 'enabled' => 1,
911 'expectedresult' => true,
912 'validationerror' => false
914 'Suspend user' => [
915 'customdata' => [
916 'status' => ENROL_USER_SUSPENDED,
918 'expectedresult' => true,
919 'validationerror' => false
925 * @param array $customdata The data we are providing to the webservice.
926 * @param bool $expectedresult The result we are expecting to receive from the webservice.
927 * @param bool $validationerror The validationerror we are expecting to receive from the webservice.
928 * @dataProvider submit_user_enrolment_form_provider
930 public function test_submit_user_enrolment_form($customdata, $expectedresult, $validationerror) {
931 global $CFG, $DB;
933 $this->resetAfterTest(true);
934 $datagen = $this->getDataGenerator();
936 /** @var enrol_manual_plugin $manualplugin */
937 $manualplugin = enrol_get_plugin('manual');
939 $studentroleid = $DB->get_field('role', 'id', ['shortname' => 'student'], MUST_EXIST);
940 $teacherroleid = $DB->get_field('role', 'id', ['shortname' => 'editingteacher'], MUST_EXIST);
941 $course = $datagen->create_course();
942 $user = $datagen->create_user();
943 $teacher = $datagen->create_user();
945 $instanceid = null;
946 $instances = enrol_get_instances($course->id, true);
947 foreach ($instances as $inst) {
948 if ($inst->enrol == 'manual') {
949 $instanceid = (int)$inst->id;
950 break;
953 if (empty($instanceid)) {
954 $instanceid = $manualplugin->add_default_instance($course);
955 if (empty($instanceid)) {
956 $instanceid = $manualplugin->add_instance($course);
959 $this->assertNotNull($instanceid);
961 $instance = $DB->get_record('enrol', ['id' => $instanceid], '*', MUST_EXIST);
962 $manualplugin->enrol_user($instance, $user->id, $studentroleid, 0, 0, ENROL_USER_ACTIVE);
963 $manualplugin->enrol_user($instance, $teacher->id, $teacherroleid, 0, 0, ENROL_USER_ACTIVE);
964 $ueid = (int) $DB->get_field(
965 'user_enrolments',
966 'id',
967 ['enrolid' => $instance->id, 'userid' => $user->id],
968 MUST_EXIST
971 // Login as teacher.
972 $teacher->ignoresesskey = true;
973 $this->setUser($teacher);
975 $formdata = [
976 'ue' => $ueid,
977 'ifilter' => 0,
978 'status' => null,
979 'timestart' => null,
980 'timeend' => null,
983 $formdata = array_merge($formdata, $customdata);
985 require_once("$CFG->dirroot/enrol/editenrolment_form.php");
986 $formdata = enrol_user_enrolment_form::mock_generate_submit_keys($formdata);
988 $querystring = http_build_query($formdata, '', '&');
990 $result = external_api::clean_returnvalue(
991 core_enrol_external::submit_user_enrolment_form_returns(),
992 core_enrol_external::submit_user_enrolment_form($querystring)
995 $this->assertEquals(
996 ['result' => $expectedresult, 'validationerror' => $validationerror],
997 $result,
998 '', 0.0, 10, true);
1000 if (!empty($result['result'])) {
1001 $ue = $DB->get_record('user_enrolments', ['id' => $ueid], '*', MUST_EXIST);
1002 $this->assertEquals($formdata['status'], $ue->status);
1007 * Test for core_enrol_external::unenrol_user_enrolment().
1009 public function test_unenerol_user_enrolment() {
1010 global $DB;
1012 $this->resetAfterTest(true);
1013 $datagen = $this->getDataGenerator();
1015 /** @var enrol_manual_plugin $manualplugin */
1016 $manualplugin = enrol_get_plugin('manual');
1017 $this->assertNotNull($manualplugin);
1019 $studentroleid = $DB->get_field('role', 'id', ['shortname' => 'student'], MUST_EXIST);
1020 $teacherroleid = $DB->get_field('role', 'id', ['shortname' => 'editingteacher'], MUST_EXIST);
1021 $course = $datagen->create_course();
1022 $user = $datagen->create_user();
1023 $teacher = $datagen->create_user();
1025 $instanceid = null;
1026 $instances = enrol_get_instances($course->id, true);
1027 foreach ($instances as $inst) {
1028 if ($inst->enrol == 'manual') {
1029 $instanceid = (int)$inst->id;
1030 break;
1033 if (empty($instanceid)) {
1034 $instanceid = $manualplugin->add_default_instance($course);
1035 if (empty($instanceid)) {
1036 $instanceid = $manualplugin->add_instance($course);
1039 $this->assertNotNull($instanceid);
1041 $instance = $DB->get_record('enrol', ['id' => $instanceid], '*', MUST_EXIST);
1042 $manualplugin->enrol_user($instance, $user->id, $studentroleid, 0, 0, ENROL_USER_ACTIVE);
1043 $manualplugin->enrol_user($instance, $teacher->id, $teacherroleid, 0, 0, ENROL_USER_ACTIVE);
1044 $ueid = (int)$DB->get_field(
1045 'user_enrolments',
1046 'id',
1047 ['enrolid' => $instance->id, 'userid' => $user->id],
1048 MUST_EXIST
1051 // Login as teacher.
1052 $this->setUser($teacher);
1054 // Invalid data by passing invalid ueid.
1055 $data = core_enrol_external::unenrol_user_enrolment(101010);
1056 $data = external_api::clean_returnvalue(core_enrol_external::unenrol_user_enrolment_returns(), $data);
1057 $this->assertFalse($data['result']);
1058 $this->assertNotEmpty($data['errors']);
1060 // Valid data.
1061 $data = core_enrol_external::unenrol_user_enrolment($ueid);
1062 $data = external_api::clean_returnvalue(core_enrol_external::unenrol_user_enrolment_returns(), $data);
1063 $this->assertTrue($data['result']);
1064 $this->assertEmpty($data['errors']);
1066 // Check unenrol user enrolment.
1067 $ue = $DB->count_records('user_enrolments', ['id' => $ueid]);
1068 $this->assertEquals(0, $ue);