MDL-58720 course: Return restricted sections and modules in get_contents
[moodle.git] / course / tests / externallib_test.php
CommitLineData
2a7a0216
JM
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * External course functions unit tests
19 *
20 * @package core_course
21 * @category external
22 * @copyright 2012 Jerome Mouneyrac
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26defined('MOODLE_INTERNAL') || die();
27
28global $CFG;
29
30require_once($CFG->dirroot . '/webservice/tests/helpers.php');
31
32/**
33 * External course functions unit tests
34 *
35 * @package core_course
36 * @category external
37 * @copyright 2012 Jerome Mouneyrac
38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 */
8252b7c2 40class core_course_externallib_testcase extends externallib_advanced_testcase {
2a7a0216
JM
41
42 /**
43 * Tests set up
44 */
45 protected function setUp() {
46 global $CFG;
47 require_once($CFG->dirroot . '/course/externallib.php');
48 }
49
50 /**
51 * Test create_categories
52 */
53 public function test_create_categories() {
54
55 global $DB;
56
57 $this->resetAfterTest(true);
58
59 // Set the required capabilities by the external function
60 $contextid = context_system::instance()->id;
61 $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
62
63 // Create base categories.
64 $category1 = new stdClass();
65 $category1->name = 'Root Test Category 1';
66 $category2 = new stdClass();
67 $category2->name = 'Root Test Category 2';
68 $category2->idnumber = 'rootcattest2';
69 $category2->desc = 'Description for root test category 1';
644fcbb6 70 $category2->theme = 'bootstrapbase';
2a7a0216
JM
71 $categories = array(
72 array('name' => $category1->name, 'parent' => 0),
73 array('name' => $category2->name, 'parent' => 0, 'idnumber' => $category2->idnumber,
74 'description' => $category2->desc, 'theme' => $category2->theme)
75 );
76
77 $createdcats = core_course_external::create_categories($categories);
78
fb695f6e
JM
79 // We need to execute the return values cleaning process to simulate the web service server.
80 $createdcats = external_api::clean_returnvalue(core_course_external::create_categories_returns(), $createdcats);
81
2a7a0216
JM
82 // Initially confirm that base data was inserted correctly.
83 $this->assertEquals($category1->name, $createdcats[0]['name']);
84 $this->assertEquals($category2->name, $createdcats[1]['name']);
85
86 // Save the ids.
87 $category1->id = $createdcats[0]['id'];
88 $category2->id = $createdcats[1]['id'];
89
90 // Create on sub category.
91 $category3 = new stdClass();
92 $category3->name = 'Sub Root Test Category 3';
93 $subcategories = array(
94 array('name' => $category3->name, 'parent' => $category1->id)
95 );
96
97 $createdsubcats = core_course_external::create_categories($subcategories);
98
fb695f6e
JM
99 // We need to execute the return values cleaning process to simulate the web service server.
100 $createdsubcats = external_api::clean_returnvalue(core_course_external::create_categories_returns(), $createdsubcats);
101
2a7a0216
JM
102 // Confirm that sub categories were inserted correctly.
103 $this->assertEquals($category3->name, $createdsubcats[0]['name']);
104
105 // Save the ids.
106 $category3->id = $createdsubcats[0]['id'];
107
108 // Calling the ws function should provide a new sortorder to give category1,
109 // category2, category3. New course categories are ordered by id not name.
110 $category1 = $DB->get_record('course_categories', array('id' => $category1->id));
111 $category2 = $DB->get_record('course_categories', array('id' => $category2->id));
112 $category3 = $DB->get_record('course_categories', array('id' => $category3->id));
113
db1eed70
MG
114 // sortorder sequence (and sortorder) must be:
115 // category 1
116 // category 3
117 // category 2
118 $this->assertGreaterThan($category1->sortorder, $category3->sortorder);
119 $this->assertGreaterThan($category3->sortorder, $category2->sortorder);
2a7a0216
JM
120
121 // Call without required capability
122 $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
52f3e060 123 $this->expectException('required_capability_exception');
2a7a0216
JM
124 $createdsubcats = core_course_external::create_categories($subcategories);
125
126 }
127
128 /**
129 * Test delete categories
130 */
131 public function test_delete_categories() {
132 global $DB;
133
134 $this->resetAfterTest(true);
135
136 // Set the required capabilities by the external function
137 $contextid = context_system::instance()->id;
138 $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
139
140 $category1 = self::getDataGenerator()->create_category();
141 $category2 = self::getDataGenerator()->create_category(
142 array('parent' => $category1->id));
143 $category3 = self::getDataGenerator()->create_category();
144 $category4 = self::getDataGenerator()->create_category(
145 array('parent' => $category3->id));
146 $category5 = self::getDataGenerator()->create_category(
147 array('parent' => $category4->id));
148
149 //delete category 1 and 2 + delete category 4, category 5 moved under category 3
150 core_course_external::delete_categories(array(
151 array('id' => $category1->id, 'recursive' => 1),
152 array('id' => $category4->id)
153 ));
154
155 //check $category 1 and 2 are deleted
156 $notdeletedcount = $DB->count_records_select('course_categories',
157 'id IN ( ' . $category1->id . ',' . $category2->id . ',' . $category4->id . ')');
158 $this->assertEquals(0, $notdeletedcount);
159
160 //check that $category5 as $category3 for parent
161 $dbcategory5 = $DB->get_record('course_categories', array('id' => $category5->id));
162 $this->assertEquals($dbcategory5->path, $category3->path . '/' . $category5->id);
163
164 // Call without required capability
165 $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
52f3e060 166 $this->expectException('required_capability_exception');
2a7a0216
JM
167 $createdsubcats = core_course_external::delete_categories(
168 array(array('id' => $category3->id)));
169 }
170
171 /**
172 * Test get categories
173 */
174 public function test_get_categories() {
175 global $DB;
176
177 $this->resetAfterTest(true);
7d6c58bc
JM
178
179 $generatedcats = array();
2a7a0216
JM
180 $category1data['idnumber'] = 'idnumbercat1';
181 $category1data['name'] = 'Category 1 for PHPunit test';
182 $category1data['description'] = 'Category 1 description';
183 $category1data['descriptionformat'] = FORMAT_MOODLE;
184 $category1 = self::getDataGenerator()->create_category($category1data);
7d6c58bc 185 $generatedcats[$category1->id] = $category1;
2a7a0216
JM
186 $category2 = self::getDataGenerator()->create_category(
187 array('parent' => $category1->id));
7d6c58bc 188 $generatedcats[$category2->id] = $category2;
2a7a0216
JM
189 $category6 = self::getDataGenerator()->create_category(
190 array('parent' => $category1->id, 'visible' => 0));
7d6c58bc 191 $generatedcats[$category6->id] = $category6;
2a7a0216 192 $category3 = self::getDataGenerator()->create_category();
7d6c58bc 193 $generatedcats[$category3->id] = $category3;
2a7a0216
JM
194 $category4 = self::getDataGenerator()->create_category(
195 array('parent' => $category3->id));
7d6c58bc 196 $generatedcats[$category4->id] = $category4;
2a7a0216
JM
197 $category5 = self::getDataGenerator()->create_category(
198 array('parent' => $category4->id));
7d6c58bc 199 $generatedcats[$category5->id] = $category5;
2a7a0216
JM
200
201 // Set the required capabilities by the external function.
202 $context = context_system::instance();
203 $roleid = $this->assignUserCapability('moodle/category:manage', $context->id);
204
205 // Retrieve category1 + sub-categories except not visible ones
206 $categories = core_course_external::get_categories(array(
207 array('key' => 'id', 'value' => $category1->id),
208 array('key' => 'visible', 'value' => 1)), 1);
209
fb695f6e
JM
210 // We need to execute the return values cleaning process to simulate the web service server.
211 $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
212
2a7a0216
JM
213 // Check we retrieve the good total number of categories.
214 $this->assertEquals(2, count($categories));
215
216 // Check the return values
7d6c58bc
JM
217 foreach ($categories as $category) {
218 $generatedcat = $generatedcats[$category['id']];
219 $this->assertEquals($category['idnumber'], $generatedcat->idnumber);
220 $this->assertEquals($category['name'], $generatedcat->name);
46be1d58
MG
221 // Description was converted to the HTML format.
222 $this->assertEquals($category['description'], format_text($generatedcat->description, FORMAT_MOODLE, array('para' => false)));
7d6c58bc
JM
223 $this->assertEquals($category['descriptionformat'], FORMAT_HTML);
224 }
2a7a0216 225
c1da311a
JL
226 // Check categories by ids.
227 $ids = implode(',', array_keys($generatedcats));
228 $categories = core_course_external::get_categories(array(
229 array('key' => 'ids', 'value' => $ids)), 0);
230
231 // We need to execute the return values cleaning process to simulate the web service server.
232 $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
233
234 // Check we retrieve the good total number of categories.
235 $this->assertEquals(6, count($categories));
236 // Check ids.
237 $returnedids = [];
238 foreach ($categories as $category) {
239 $returnedids[] = $category['id'];
240 }
241 // Sort the arrays upon comparision.
242 $this->assertEquals(array_keys($generatedcats), $returnedids, '', 0.0, 10, true);
243
2a7a0216
JM
244 // Check different params.
245 $categories = core_course_external::get_categories(array(
246 array('key' => 'id', 'value' => $category1->id),
c1da311a 247 array('key' => 'ids', 'value' => $category1->id),
2a7a0216
JM
248 array('key' => 'idnumber', 'value' => $category1->idnumber),
249 array('key' => 'visible', 'value' => 1)), 0);
fb695f6e
JM
250
251 // We need to execute the return values cleaning process to simulate the web service server.
252 $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
253
2a7a0216
JM
254 $this->assertEquals(1, count($categories));
255
b8b1be15
JL
256 // Same query, but forcing a parameters clean.
257 $categories = core_course_external::get_categories(array(
258 array('key' => 'id', 'value' => "$category1->id"),
259 array('key' => 'idnumber', 'value' => $category1->idnumber),
260 array('key' => 'name', 'value' => $category1->name . "<br/>"),
261 array('key' => 'visible', 'value' => '1')), 0);
262 $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
263
264 $this->assertEquals(1, count($categories));
265
2a7a0216
JM
266 // Retrieve categories from parent.
267 $categories = core_course_external::get_categories(array(
268 array('key' => 'parent', 'value' => $category3->id)), 1);
bdf9f4d4
JL
269 $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
270
2a7a0216
JM
271 $this->assertEquals(2, count($categories));
272
273 // Retrieve all categories.
274 $categories = core_course_external::get_categories();
fb695f6e
JM
275
276 // We need to execute the return values cleaning process to simulate the web service server.
277 $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
278
2a7a0216
JM
279 $this->assertEquals($DB->count_records('course_categories'), count($categories));
280
2a7a0216 281 $this->unassignUserCapability('moodle/category:manage', $context->id, $roleid);
7180cdc7
PFO
282
283 // Ensure maxdepthcategory is 2 and retrieve all categories without category:manage capability. It should retrieve all
284 // visible categories as well.
285 set_config('maxcategorydepth', 2);
286 $categories = core_course_external::get_categories();
287
288 // We need to execute the return values cleaning process to simulate the web service server.
289 $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
290
291 $this->assertEquals($DB->count_records('course_categories', array('visible' => 1)), count($categories));
292
293 // Call without required capability (it will fail cause of the search on idnumber).
52f3e060 294 $this->expectException('moodle_exception');
2a7a0216
JM
295 $categories = core_course_external::get_categories(array(
296 array('key' => 'id', 'value' => $category1->id),
297 array('key' => 'idnumber', 'value' => $category1->idnumber),
298 array('key' => 'visible', 'value' => 1)), 0);
299 }
300
301 /**
302 * Test update_categories
303 */
304 public function test_update_categories() {
305 global $DB;
306
307 $this->resetAfterTest(true);
308
309 // Set the required capabilities by the external function
310 $contextid = context_system::instance()->id;
311 $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
312
313 // Create base categories.
314 $category1data['idnumber'] = 'idnumbercat1';
315 $category1data['name'] = 'Category 1 for PHPunit test';
316 $category1data['description'] = 'Category 1 description';
317 $category1data['descriptionformat'] = FORMAT_MOODLE;
318 $category1 = self::getDataGenerator()->create_category($category1data);
319 $category2 = self::getDataGenerator()->create_category(
320 array('parent' => $category1->id));
321 $category3 = self::getDataGenerator()->create_category();
322 $category4 = self::getDataGenerator()->create_category(
323 array('parent' => $category3->id));
324 $category5 = self::getDataGenerator()->create_category(
325 array('parent' => $category4->id));
326
327 // We update all category1 attribut.
328 // Then we move cat4 and cat5 parent: cat3 => cat1
329 $categories = array(
330 array('id' => $category1->id,
331 'name' => $category1->name . '_updated',
332 'idnumber' => $category1->idnumber . '_updated',
333 'description' => $category1->description . '_updated',
334 'descriptionformat' => FORMAT_HTML,
335 'theme' => $category1->theme),
336 array('id' => $category4->id, 'parent' => $category1->id));
337
338 core_course_external::update_categories($categories);
339
340 // Check the values were updated.
341 $dbcategories = $DB->get_records_select('course_categories',
342 'id IN (' . $category1->id . ',' . $category2->id . ',' . $category2->id
343 . ',' . $category3->id . ',' . $category4->id . ',' . $category5->id .')');
344 $this->assertEquals($category1->name . '_updated',
345 $dbcategories[$category1->id]->name);
346 $this->assertEquals($category1->idnumber . '_updated',
347 $dbcategories[$category1->id]->idnumber);
348 $this->assertEquals($category1->description . '_updated',
349 $dbcategories[$category1->id]->description);
350 $this->assertEquals(FORMAT_HTML, $dbcategories[$category1->id]->descriptionformat);
351
352 // Check that category4 and category5 have been properly moved.
353 $this->assertEquals('/' . $category1->id . '/' . $category4->id,
354 $dbcategories[$category4->id]->path);
355 $this->assertEquals('/' . $category1->id . '/' . $category4->id . '/' . $category5->id,
356 $dbcategories[$category5->id]->path);
357
358 // Call without required capability.
359 $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
52f3e060 360 $this->expectException('required_capability_exception');
2a7a0216
JM
361 core_course_external::update_categories($categories);
362 }
363
364 /**
365 * Test create_courses
366 */
367 public function test_create_courses() {
368 global $DB;
369
370 $this->resetAfterTest(true);
371
821676f5
JM
372 // Enable course completion.
373 set_config('enablecompletion', 1);
141e7d87
DP
374 // Enable course themes.
375 set_config('allowcoursethemes', 1);
821676f5 376
2a7a0216
JM
377 // Set the required capabilities by the external function
378 $contextid = context_system::instance()->id;
379 $roleid = $this->assignUserCapability('moodle/course:create', $contextid);
380 $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
381
382 $category = self::getDataGenerator()->create_category();
383
384 // Create base categories.
385 $course1['fullname'] = 'Test course 1';
386 $course1['shortname'] = 'Testcourse1';
387 $course1['categoryid'] = $category->id;
388 $course2['fullname'] = 'Test course 2';
389 $course2['shortname'] = 'Testcourse2';
390 $course2['categoryid'] = $category->id;
391 $course2['idnumber'] = 'testcourse2idnumber';
392 $course2['summary'] = 'Description for course 2';
393 $course2['summaryformat'] = FORMAT_MOODLE;
394 $course2['format'] = 'weeks';
395 $course2['showgrades'] = 1;
396 $course2['newsitems'] = 3;
fbcdb0d7
DNA
397 $course2['startdate'] = 1420092000; // 01/01/2015.
398 $course2['enddate'] = 1422669600; // 01/31/2015.
2a7a0216
JM
399 $course2['numsections'] = 4;
400 $course2['maxbytes'] = 100000;
401 $course2['showreports'] = 1;
402 $course2['visible'] = 0;
403 $course2['hiddensections'] = 0;
404 $course2['groupmode'] = 0;
405 $course2['groupmodeforce'] = 0;
406 $course2['defaultgroupingid'] = 0;
407 $course2['enablecompletion'] = 1;
2a7a0216
JM
408 $course2['completionnotify'] = 1;
409 $course2['lang'] = 'en';
644fcbb6 410 $course2['forcetheme'] = 'bootstrapbase';
0e984d98
MG
411 $course3['fullname'] = 'Test course 3';
412 $course3['shortname'] = 'Testcourse3';
413 $course3['categoryid'] = $category->id;
414 $course3['format'] = 'topics';
415 $course3options = array('numsections' => 8,
416 'hiddensections' => 1,
417 'coursedisplay' => 1);
8d8d4da4 418 $course3['courseformatoptions'] = array();
0e984d98 419 foreach ($course3options as $key => $value) {
8d8d4da4 420 $course3['courseformatoptions'][] = array('name' => $key, 'value' => $value);
0e984d98 421 }
821676f5 422 $courses = array($course1, $course2, $course3);
2a7a0216
JM
423
424 $createdcourses = core_course_external::create_courses($courses);
425
fb695f6e
JM
426 // We need to execute the return values cleaning process to simulate the web service server.
427 $createdcourses = external_api::clean_returnvalue(core_course_external::create_courses_returns(), $createdcourses);
428
2a7a0216 429 // Check that right number of courses were created.
821676f5 430 $this->assertEquals(3, count($createdcourses));
2a7a0216
JM
431
432 // Check that the courses were correctly created.
433 foreach ($createdcourses as $createdcourse) {
850acb35 434 $courseinfo = course_get_format($createdcourse['id'])->get_course();
2a7a0216
JM
435
436 if ($createdcourse['shortname'] == $course2['shortname']) {
850acb35
MG
437 $this->assertEquals($courseinfo->fullname, $course2['fullname']);
438 $this->assertEquals($courseinfo->shortname, $course2['shortname']);
439 $this->assertEquals($courseinfo->category, $course2['categoryid']);
440 $this->assertEquals($courseinfo->idnumber, $course2['idnumber']);
441 $this->assertEquals($courseinfo->summary, $course2['summary']);
442 $this->assertEquals($courseinfo->summaryformat, $course2['summaryformat']);
443 $this->assertEquals($courseinfo->format, $course2['format']);
444 $this->assertEquals($courseinfo->showgrades, $course2['showgrades']);
445 $this->assertEquals($courseinfo->newsitems, $course2['newsitems']);
446 $this->assertEquals($courseinfo->startdate, $course2['startdate']);
fbcdb0d7 447 $this->assertEquals($courseinfo->enddate, $course2['enddate']);
89b909f6 448 $this->assertEquals(course_get_format($createdcourse['id'])->get_last_section_number(), $course2['numsections']);
850acb35
MG
449 $this->assertEquals($courseinfo->maxbytes, $course2['maxbytes']);
450 $this->assertEquals($courseinfo->showreports, $course2['showreports']);
451 $this->assertEquals($courseinfo->visible, $course2['visible']);
452 $this->assertEquals($courseinfo->hiddensections, $course2['hiddensections']);
453 $this->assertEquals($courseinfo->groupmode, $course2['groupmode']);
454 $this->assertEquals($courseinfo->groupmodeforce, $course2['groupmodeforce']);
455 $this->assertEquals($courseinfo->defaultgroupingid, $course2['defaultgroupingid']);
456 $this->assertEquals($courseinfo->completionnotify, $course2['completionnotify']);
457 $this->assertEquals($courseinfo->lang, $course2['lang']);
141e7d87 458 $this->assertEquals($courseinfo->theme, $course2['forcetheme']);
2a7a0216 459
821676f5
JM
460 // We enabled completion at the beginning of the test.
461 $this->assertEquals($courseinfo->enablecompletion, $course2['enablecompletion']);
2a7a0216
JM
462
463 } else if ($createdcourse['shortname'] == $course1['shortname']) {
464 $courseconfig = get_config('moodlecourse');
850acb35
MG
465 $this->assertEquals($courseinfo->fullname, $course1['fullname']);
466 $this->assertEquals($courseinfo->shortname, $course1['shortname']);
467 $this->assertEquals($courseinfo->category, $course1['categoryid']);
468 $this->assertEquals($courseinfo->summaryformat, FORMAT_HTML);
469 $this->assertEquals($courseinfo->format, $courseconfig->format);
470 $this->assertEquals($courseinfo->showgrades, $courseconfig->showgrades);
471 $this->assertEquals($courseinfo->newsitems, $courseconfig->newsitems);
472 $this->assertEquals($courseinfo->maxbytes, $courseconfig->maxbytes);
473 $this->assertEquals($courseinfo->showreports, $courseconfig->showreports);
474 $this->assertEquals($courseinfo->groupmode, $courseconfig->groupmode);
475 $this->assertEquals($courseinfo->groupmodeforce, $courseconfig->groupmodeforce);
476 $this->assertEquals($courseinfo->defaultgroupingid, 0);
0e984d98 477 } else if ($createdcourse['shortname'] == $course3['shortname']) {
850acb35
MG
478 $this->assertEquals($courseinfo->fullname, $course3['fullname']);
479 $this->assertEquals($courseinfo->shortname, $course3['shortname']);
480 $this->assertEquals($courseinfo->category, $course3['categoryid']);
481 $this->assertEquals($courseinfo->format, $course3['format']);
482 $this->assertEquals($courseinfo->hiddensections, $course3options['hiddensections']);
89b909f6
MG
483 $this->assertEquals(course_get_format($createdcourse['id'])->get_last_section_number(),
484 $course3options['numsections']);
850acb35 485 $this->assertEquals($courseinfo->coursedisplay, $course3options['coursedisplay']);
2a7a0216 486 } else {
75c597da 487 throw new moodle_exception('Unexpected shortname');
2a7a0216
JM
488 }
489 }
490
491 // Call without required capability
492 $this->unassignUserCapability('moodle/course:create', $contextid, $roleid);
52f3e060 493 $this->expectException('required_capability_exception');
2a7a0216
JM
494 $createdsubcats = core_course_external::create_courses($courses);
495 }
496
497 /**
498 * Test delete_courses
499 */
500 public function test_delete_courses() {
501 global $DB, $USER;
502
503 $this->resetAfterTest(true);
504
505 // Admin can delete a course.
506 $this->setAdminUser();
507 // Validate_context() will fail as the email is not set by $this->setAdminUser().
0fe86bbd 508 $USER->email = 'emailtopass@example.com';
2a7a0216
JM
509
510 $course1 = self::getDataGenerator()->create_course();
511 $course2 = self::getDataGenerator()->create_course();
512 $course3 = self::getDataGenerator()->create_course();
513
514 // Delete courses.
70f37963
JH
515 $result = core_course_external::delete_courses(array($course1->id, $course2->id));
516 $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
517 // Check for 0 warnings.
518 $this->assertEquals(0, count($result['warnings']));
2a7a0216
JM
519
520 // Check $course 1 and 2 are deleted.
521 $notdeletedcount = $DB->count_records_select('course',
522 'id IN ( ' . $course1->id . ',' . $course2->id . ')');
523 $this->assertEquals(0, $notdeletedcount);
524
70f37963
JH
525 // Try to delete non-existent course.
526 $result = core_course_external::delete_courses(array($course1->id));
527 $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
528 // Check for 1 warnings.
529 $this->assertEquals(1, count($result['warnings']));
530
531 // Try to delete Frontpage course.
532 $result = core_course_external::delete_courses(array(0));
533 $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
534 // Check for 1 warnings.
535 $this->assertEquals(1, count($result['warnings']));
536
537 // Fail when the user has access to course (enrolled) but does not have permission or is not admin.
538 $student1 = self::getDataGenerator()->create_user();
539 $studentrole = $DB->get_record('role', array('shortname' => 'student'));
540 $this->getDataGenerator()->enrol_user($student1->id,
541 $course3->id,
542 $studentrole->id);
543 $this->setUser($student1);
544 $result = core_course_external::delete_courses(array($course3->id));
545 $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
546 // Check for 1 warnings.
547 $this->assertEquals(1, count($result['warnings']));
548
2a7a0216
JM
549 // Fail when the user is not allow to access the course (enrolled) or is not admin.
550 $this->setGuestUser();
52f3e060 551 $this->expectException('require_login_exception');
70f37963
JH
552
553 $result = core_course_external::delete_courses(array($course3->id));
554 $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
2a7a0216
JM
555 }
556
557 /**
558 * Test get_courses
559 */
560 public function test_get_courses () {
561 global $DB;
562
563 $this->resetAfterTest(true);
564
7d6c58bc 565 $generatedcourses = array();
2a7a0216 566 $coursedata['idnumber'] = 'idnumbercourse1';
d889b587
JL
567 // Adding tags here to check that format_string is applied.
568 $coursedata['fullname'] = '<b>Course 1 for PHPunit test</b>';
569 $coursedata['shortname'] = '<b>Course 1 for PHPunit test</b>';
2a7a0216
JM
570 $coursedata['summary'] = 'Course 1 description';
571 $coursedata['summaryformat'] = FORMAT_MOODLE;
572 $course1 = self::getDataGenerator()->create_course($coursedata);
245d354c 573
7d6c58bc 574 $generatedcourses[$course1->id] = $course1;
2a7a0216 575 $course2 = self::getDataGenerator()->create_course();
7d6c58bc 576 $generatedcourses[$course2->id] = $course2;
0e984d98 577 $course3 = self::getDataGenerator()->create_course(array('format' => 'topics'));
7d6c58bc 578 $generatedcourses[$course3->id] = $course3;
2a7a0216
JM
579
580 // Set the required capabilities by the external function.
581 $context = context_system::instance();
582 $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
583 $this->assignUserCapability('moodle/course:update',
584 context_course::instance($course1->id)->id, $roleid);
585 $this->assignUserCapability('moodle/course:update',
586 context_course::instance($course2->id)->id, $roleid);
587 $this->assignUserCapability('moodle/course:update',
588 context_course::instance($course3->id)->id, $roleid);
589
590 $courses = core_course_external::get_courses(array('ids' =>
591 array($course1->id, $course2->id)));
592
fb695f6e
JM
593 // We need to execute the return values cleaning process to simulate the web service server.
594 $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
595
2a7a0216
JM
596 // Check we retrieve the good total number of categories.
597 $this->assertEquals(2, count($courses));
598
7d6c58bc 599 foreach ($courses as $course) {
d889b587 600 $coursecontext = context_course::instance($course['id']);
7d6c58bc
JM
601 $dbcourse = $generatedcourses[$course['id']];
602 $this->assertEquals($course['idnumber'], $dbcourse->idnumber);
d889b587
JL
603 $this->assertEquals($course['fullname'], external_format_string($dbcourse->fullname, $coursecontext->id));
604 $this->assertEquals($course['displayname'], external_format_string(get_course_display_name_for_list($dbcourse),
605 $coursecontext->id));
46be1d58
MG
606 // Summary was converted to the HTML format.
607 $this->assertEquals($course['summary'], format_text($dbcourse->summary, FORMAT_MOODLE, array('para' => false)));
7d6c58bc 608 $this->assertEquals($course['summaryformat'], FORMAT_HTML);
d889b587 609 $this->assertEquals($course['shortname'], external_format_string($dbcourse->shortname, $coursecontext->id));
7d6c58bc
JM
610 $this->assertEquals($course['categoryid'], $dbcourse->category);
611 $this->assertEquals($course['format'], $dbcourse->format);
612 $this->assertEquals($course['showgrades'], $dbcourse->showgrades);
613 $this->assertEquals($course['newsitems'], $dbcourse->newsitems);
614 $this->assertEquals($course['startdate'], $dbcourse->startdate);
fbcdb0d7 615 $this->assertEquals($course['enddate'], $dbcourse->enddate);
89b909f6 616 $this->assertEquals($course['numsections'], course_get_format($dbcourse)->get_last_section_number());
7d6c58bc
JM
617 $this->assertEquals($course['maxbytes'], $dbcourse->maxbytes);
618 $this->assertEquals($course['showreports'], $dbcourse->showreports);
619 $this->assertEquals($course['visible'], $dbcourse->visible);
620 $this->assertEquals($course['hiddensections'], $dbcourse->hiddensections);
621 $this->assertEquals($course['groupmode'], $dbcourse->groupmode);
622 $this->assertEquals($course['groupmodeforce'], $dbcourse->groupmodeforce);
623 $this->assertEquals($course['defaultgroupingid'], $dbcourse->defaultgroupingid);
624 $this->assertEquals($course['completionnotify'], $dbcourse->completionnotify);
625 $this->assertEquals($course['lang'], $dbcourse->lang);
626 $this->assertEquals($course['forcetheme'], $dbcourse->theme);
7d6c58bc 627 $this->assertEquals($course['enablecompletion'], $dbcourse->enablecompletion);
0e984d98 628 if ($dbcourse->format === 'topics') {
8d8d4da4 629 $this->assertEquals($course['courseformatoptions'], array(
8d8d4da4
MG
630 array('name' => 'hiddensections', 'value' => $dbcourse->hiddensections),
631 array('name' => 'coursedisplay', 'value' => $dbcourse->coursedisplay),
0e984d98
MG
632 ));
633 }
7d6c58bc 634 }
2a7a0216
JM
635
636 // Get all courses in the DB
637 $courses = core_course_external::get_courses(array());
fb695f6e
JM
638
639 // We need to execute the return values cleaning process to simulate the web service server.
640 $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
641
2a7a0216
JM
642 $this->assertEquals($DB->count_records('course'), count($courses));
643 }
644
a0cf7ee8
MG
645 /**
646 * Test get_courses without capability
647 */
648 public function test_get_courses_without_capability() {
649 $this->resetAfterTest(true);
650
651 $course1 = $this->getDataGenerator()->create_course();
652 $this->setUser($this->getDataGenerator()->create_user());
653
654 // No permissions are required to get the site course.
655 $courses = core_course_external::get_courses(array('ids' => [SITEID]));
656 $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
657
658 $this->assertEquals(1, count($courses));
659 $this->assertEquals('PHPUnit test site', $courses[0]['fullname']);
660 $this->assertEquals('site', $courses[0]['format']);
661
662 // Requesting course without being enrolled or capability to view it will throw an exception.
663 try {
664 core_course_external::get_courses(array('ids' => [$course1->id]));
665 $this->fail('Exception expected');
666 } catch (moodle_exception $e) {
667 $this->assertEquals(1, preg_match('/Course or activity not accessible. \(Not enrolled\)/', $e->getMessage()));
668 }
669 }
670
740c354f
JL
671 /**
672 * Test search_courses
673 */
674 public function test_search_courses () {
675
74fa9f76 676 global $DB;
740c354f
JL
677
678 $this->resetAfterTest(true);
679 $this->setAdminUser();
680 $generatedcourses = array();
681 $coursedata1['fullname'] = 'FIRST COURSE';
682 $course1 = self::getDataGenerator()->create_course($coursedata1);
245d354c
DW
683
684 $page = new moodle_page();
685 $page->set_course($course1);
686 $page->blocks->add_blocks([BLOCK_POS_LEFT => ['news_items'], BLOCK_POS_RIGHT => []], 'course-view-*');
687
740c354f
JL
688 $coursedata2['fullname'] = 'SECOND COURSE';
689 $course2 = self::getDataGenerator()->create_course($coursedata2);
245d354c
DW
690
691 $page = new moodle_page();
692 $page->set_course($course2);
693 $page->blocks->add_blocks([BLOCK_POS_LEFT => ['news_items'], BLOCK_POS_RIGHT => []], 'course-view-*');
740c354f
JL
694 // Search by name.
695 $results = core_course_external::search_courses('search', 'FIRST');
696 $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
697 $this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']);
698 $this->assertCount(1, $results['courses']);
699
700 // Create the forum.
701 $record = new stdClass();
702 $record->introformat = FORMAT_HTML;
703 $record->course = $course2->id;
704 // Set Aggregate type = Average of ratings.
705 $forum = self::getDataGenerator()->create_module('forum', $record);
706
707 // Search by module.
708 $results = core_course_external::search_courses('modulelist', 'forum');
709 $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
710 $this->assertEquals(1, $results['total']);
711
712 // Enable coursetag option.
713 set_config('block_tags_showcoursetags', true);
714 // Add tag 'TAG-LABEL ON SECOND COURSE' to Course2.
74fa9f76
MG
715 core_tag_tag::set_item_tags('core', 'course', $course2->id, context_course::instance($course2->id),
716 array('TAG-LABEL ON SECOND COURSE'));
717 $taginstance = $DB->get_record('tag_instance',
718 array('itemtype' => 'course', 'itemid' => $course2->id), '*', MUST_EXIST);
740c354f
JL
719 // Search by tagid.
720 $results = core_course_external::search_courses('tagid', $taginstance->tagid);
721 $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
722 $this->assertEquals($coursedata2['fullname'], $results['courses'][0]['fullname']);
723
724 // Search by block (use news_items default block).
725 $blockid = $DB->get_field('block', 'id', array('name' => 'news_items'));
726 $results = core_course_external::search_courses('blocklist', $blockid);
727 $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
728 $this->assertEquals(2, $results['total']);
729
730 // Now as a normal user.
731 $user = self::getDataGenerator()->create_user();
935ee1c6
EM
732
733 // Add a 3rd, hidden, course we shouldn't see, even when enrolled as student.
734 $coursedata3['fullname'] = 'HIDDEN COURSE';
735 $coursedata3['visible'] = 0;
736 $course3 = self::getDataGenerator()->create_course($coursedata3);
737 $this->getDataGenerator()->enrol_user($user->id, $course3->id, 'student');
738
739 $this->getDataGenerator()->enrol_user($user->id, $course2->id, 'student');
740c354f
JL
740 $this->setUser($user);
741
742 $results = core_course_external::search_courses('search', 'FIRST');
743 $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
744 $this->assertCount(1, $results['courses']);
745 $this->assertEquals(1, $results['total']);
746 $this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']);
747
935ee1c6
EM
748 // Check that we can see both without the limit to enrolled setting.
749 $results = core_course_external::search_courses('search', 'COURSE', 0, 0, array(), 0);
750 $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
751 $this->assertCount(2, $results['courses']);
752 $this->assertEquals(2, $results['total']);
753
754 // Check that we only see our enrolled course when limiting.
755 $results = core_course_external::search_courses('search', 'COURSE', 0, 0, array(), 1);
756 $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
757 $this->assertCount(1, $results['courses']);
758 $this->assertEquals(1, $results['total']);
759 $this->assertEquals($coursedata2['fullname'], $results['courses'][0]['fullname']);
760
740c354f 761 // Search by block (use news_items default block). Should fail (only admins allowed).
52f3e060 762 $this->expectException('required_capability_exception');
740c354f
JL
763 $results = core_course_external::search_courses('blocklist', $blockid);
764
765 }
766
2a7a0216 767 /**
8a5346a7
JL
768 * Create a course with contents
769 * @return array A list with the course object and course modules objects
2a7a0216 770 */
8a5346a7 771 private function prepare_get_course_contents_test() {
6a1131e2 772 global $DB;
935429e2 773 $course = self::getDataGenerator()->create_course(['numsections' => 3]);
487bc1b6
JM
774 $forumdescription = 'This is the forum description';
775 $forum = $this->getDataGenerator()->create_module('forum',
8a5346a7 776 array('course' => $course->id, 'intro' => $forumdescription),
487bc1b6 777 array('showdescription' => true));
2a7a0216 778 $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
8a5346a7 779 $data = $this->getDataGenerator()->create_module('data', array('assessed' => 1, 'scale' => 100, 'course' => $course->id));
2a7a0216 780 $datacm = get_coursemodule_from_instance('page', $data->id);
8a5346a7 781 $page = $this->getDataGenerator()->create_module('page', array('course' => $course->id));
2a7a0216 782 $pagecm = get_coursemodule_from_instance('page', $page->id);
487bc1b6
JM
783 $labeldescription = 'This is a very long label to test if more than 50 characters are returned.
784 So bla bla bla bla <b>bold bold bold</b> bla bla bla bla.';
785 $label = $this->getDataGenerator()->create_module('label', array('course' => $course->id,
786 'intro' => $labeldescription));
787 $labelcm = get_coursemodule_from_instance('label', $label->id);
935429e2
JL
788 // Module with availability restrictions not met.
789 $url = $this->getDataGenerator()->create_module('url',
790 array('course' => $course->id, 'name' => 'URL: % & $ ../', 'section' => 2),
791 array('availability' => '{"op":"&","c":[{"type":"date","d":">=","t":2502892800}],"showc":[true]}'));
8a5346a7 792 $urlcm = get_coursemodule_from_instance('url', $url->id);
935429e2
JL
793 // Module for the last section.
794 $this->getDataGenerator()->create_module('url',
795 array('course' => $course->id, 'name' => 'URL for last section', 'section' => 3));
796 // Module for section 1 with availability restrictions met.
797 $yesterday = time() - DAYSECS;
798 $this->getDataGenerator()->create_module('url',
799 array('course' => $course->id, 'name' => 'URL restrictions met', 'section' => 1),
800 array('availability' => '{"op":"&","c":[{"type":"date","d":">=","t":'. $yesterday .'}],"showc":[true]}'));
2a7a0216
JM
801
802 // Set the required capabilities by the external function.
803 $context = context_course::instance($course->id);
804 $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
805 $this->assignUserCapability('moodle/course:update', $context->id, $roleid);
12306a9f 806 $this->assignUserCapability('mod/data:view', $context->id, $roleid);
2a7a0216 807
6a1131e2
JL
808 $conditions = array('course' => $course->id, 'section' => 2);
809 $DB->set_field('course_sections', 'summary', 'Text with iframe <iframe src="https://moodle.org"></iframe>', $conditions);
935429e2
JL
810
811 // Add date availability condition not met for last section.
812 $availability = '{"op":"&","c":[{"type":"date","d":">=","t":2502892800}],"showc":[true]}';
813 $DB->set_field('course_sections', 'availability', $availability,
814 array('course' => $course->id, 'section' => 3));
6a1131e2
JL
815 rebuild_course_cache($course->id, true);
816
8a5346a7
JL
817 return array($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm);
818 }
819
820 /**
821 * Test get_course_contents
822 */
823 public function test_get_course_contents() {
824 $this->resetAfterTest(true);
2a7a0216 825
8a5346a7
JL
826 list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
827
828 $sections = core_course_external::get_course_contents($course->id, array());
fb695f6e 829 // We need to execute the return values cleaning process to simulate the web service server.
487bc1b6
JM
830 $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
831
487bc1b6
JM
832 $modinfo = get_fast_modinfo($course);
833 $testexecuted = 0;
935429e2 834 foreach ($sections[0]['modules'] as $module) {
487bc1b6
JM
835 if ($module['id'] == $forumcm->id and $module['modname'] == 'forum') {
836 $cm = $modinfo->cms[$forumcm->id];
73ee2fda 837 $formattedtext = format_text($cm->content, FORMAT_HTML,
487bc1b6
JM
838 array('noclean' => true, 'para' => false, 'filter' => false));
839 $this->assertEquals($formattedtext, $module['description']);
ca4154ce 840 $this->assertEquals($forumcm->instance, $module['instance']);
487bc1b6
JM
841 $testexecuted = $testexecuted + 1;
842 } else if ($module['id'] == $labelcm->id and $module['modname'] == 'label') {
843 $cm = $modinfo->cms[$labelcm->id];
73ee2fda 844 $formattedtext = format_text($cm->content, FORMAT_HTML,
487bc1b6
JM
845 array('noclean' => true, 'para' => false, 'filter' => false));
846 $this->assertEquals($formattedtext, $module['description']);
ca4154ce 847 $this->assertEquals($labelcm->instance, $module['instance']);
487bc1b6
JM
848 $testexecuted = $testexecuted + 1;
849 }
850 }
851 $this->assertEquals(2, $testexecuted);
935429e2 852 $this->assertEquals(0, $sections[0]['section']);
fb695f6e 853
8a5346a7 854 // Check that the only return section has the 5 created modules.
935429e2
JL
855 $this->assertCount(4, $sections[0]['modules']);
856 $this->assertCount(1, $sections[1]['modules']);
857 $this->assertCount(1, $sections[2]['modules']);
858 $this->assertCount(0, $sections[3]['modules']); // No modules for the section with availability restrictions.
859 $this->assertNotEmpty($sections[3]['availabilityinfo']);
860 $this->assertEquals(1, $sections[1]['section']);
861 $this->assertEquals(2, $sections[2]['section']);
862 $this->assertEquals(3, $sections[3]['section']);
863 $this->assertContains('<iframe', $sections[2]['summary']);
864 $this->assertContains('</iframe>', $sections[2]['summary']);
865 // The module with the availability restriction met is returning contents.
866 $this->assertNotEmpty($sections[1]['modules'][0]['contents']);
867 // The module with the availability restriction not met is not returning contents.
868 $this->assertArrayNotHasKey('contents', $sections[2]['modules'][0]);
869 $this->assertNotEmpty($sections[2]['modules'][0]['availabilityinfo']);
8a5346a7
JL
870 try {
871 $sections = core_course_external::get_course_contents($course->id,
872 array(array("name" => "invalid", "value" => 1)));
873 $this->fail('Exception expected due to invalid option.');
874 } catch (moodle_exception $e) {
875 $this->assertEquals('errorinvalidparam', $e->errorcode);
876 }
877 }
878
879
880 /**
881 * Test get_course_contents excluding modules
882 */
883 public function test_get_course_contents_excluding_modules() {
884 $this->resetAfterTest(true);
885
886 list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
887
888 // Test exclude modules.
889 $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludemodules", "value" => 1)));
890
891 // We need to execute the return values cleaning process to simulate the web service server.
892 $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
893
935429e2
JL
894 $this->assertEmpty($sections[0]['modules']);
895 $this->assertEmpty($sections[1]['modules']);
8a5346a7
JL
896 }
897
898 /**
899 * Test get_course_contents excluding contents
900 */
901 public function test_get_course_contents_excluding_contents() {
902 $this->resetAfterTest(true);
903
904 list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
905
906 // Test exclude modules.
907 $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludecontents", "value" => 1)));
908
909 // We need to execute the return values cleaning process to simulate the web service server.
910 $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
911
912 foreach ($sections as $section) {
913 foreach ($section['modules'] as $module) {
914 // Only resources return contents.
915 if (isset($module['contents'])) {
916 $this->assertEmpty($module['contents']);
917 }
918 }
919 }
920 }
921
922 /**
923 * Test get_course_contents filtering by section number
924 */
925 public function test_get_course_contents_section_number() {
926 $this->resetAfterTest(true);
927
928 list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
929
930 // Test exclude modules.
931 $sections = core_course_external::get_course_contents($course->id, array(array("name" => "sectionnumber", "value" => 0)));
932
933 // We need to execute the return values cleaning process to simulate the web service server.
934 $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
935
936 $this->assertCount(1, $sections);
937 $this->assertCount(4, $sections[0]['modules']);
938 }
939
940 /**
941 * Test get_course_contents filtering by cmid
942 */
943 public function test_get_course_contents_cmid() {
944 $this->resetAfterTest(true);
945
946 list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
947
948 // Test exclude modules.
949 $sections = core_course_external::get_course_contents($course->id, array(array("name" => "cmid", "value" => $forumcm->id)));
950
951 // We need to execute the return values cleaning process to simulate the web service server.
952 $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
953
935429e2 954 $this->assertCount(4, $sections);
8a5346a7
JL
955 $this->assertCount(1, $sections[0]['modules']);
956 $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
957 }
958
959
960 /**
961 * Test get_course_contents filtering by cmid and section
962 */
963 public function test_get_course_contents_section_cmid() {
964 $this->resetAfterTest(true);
965
966 list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
967
968 // Test exclude modules.
969 $sections = core_course_external::get_course_contents($course->id, array(
970 array("name" => "cmid", "value" => $forumcm->id),
971 array("name" => "sectionnumber", "value" => 0)
972 ));
973
974 // We need to execute the return values cleaning process to simulate the web service server.
975 $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
976
977 $this->assertCount(1, $sections);
978 $this->assertCount(1, $sections[0]['modules']);
979 $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
980 }
981
982 /**
983 * Test get_course_contents filtering by modname
984 */
985 public function test_get_course_contents_modname() {
986 $this->resetAfterTest(true);
987
988 list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
989
990 // Test exclude modules.
991 $sections = core_course_external::get_course_contents($course->id, array(array("name" => "modname", "value" => "forum")));
992
993 // We need to execute the return values cleaning process to simulate the web service server.
994 $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
995
935429e2 996 $this->assertCount(4, $sections);
8a5346a7
JL
997 $this->assertCount(1, $sections[0]['modules']);
998 $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
999 }
1000
1001 /**
1002 * Test get_course_contents filtering by modname
1003 */
1004 public function test_get_course_contents_modid() {
1005 $this->resetAfterTest(true);
1006
1007 list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1008
1009 // Test exclude modules.
1010 $sections = core_course_external::get_course_contents($course->id, array(
1011 array("name" => "modname", "value" => "page"),
1012 array("name" => "modid", "value" => $pagecm->instance),
1013 ));
1014
1015 // We need to execute the return values cleaning process to simulate the web service server.
1016 $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1017
935429e2 1018 $this->assertCount(4, $sections);
8a5346a7
JL
1019 $this->assertCount(1, $sections[0]['modules']);
1020 $this->assertEquals("page", $sections[0]['modules'][0]["modname"]);
1021 $this->assertEquals($pagecm->instance, $sections[0]['modules'][0]["instance"]);
2a7a0216
JM
1022 }
1023
1024 /**
1025 * Test duplicate_course
1026 */
1027 public function test_duplicate_course() {
1028 $this->resetAfterTest(true);
1029
1030 // Create one course with three modules.
1031 $course = self::getDataGenerator()->create_course();
1032 $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course->id));
1033 $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
1034 $forumcontext = context_module::instance($forum->cmid);
1035 $data = $this->getDataGenerator()->create_module('data', array('assessed'=>1, 'scale'=>100, 'course'=>$course->id));
1036 $datacontext = context_module::instance($data->cmid);
1037 $datacm = get_coursemodule_from_instance('page', $data->id);
1038 $page = $this->getDataGenerator()->create_module('page', array('course'=>$course->id));
1039 $pagecontext = context_module::instance($page->cmid);
1040 $pagecm = get_coursemodule_from_instance('page', $page->id);
1041
1042 // Set the required capabilities by the external function.
1043 $coursecontext = context_course::instance($course->id);
1044 $categorycontext = context_coursecat::instance($course->category);
1045 $roleid = $this->assignUserCapability('moodle/course:create', $categorycontext->id);
1046 $this->assignUserCapability('moodle/course:view', $categorycontext->id, $roleid);
1047 $this->assignUserCapability('moodle/restore:restorecourse', $categorycontext->id, $roleid);
1048 $this->assignUserCapability('moodle/backup:backupcourse', $coursecontext->id, $roleid);
1049 $this->assignUserCapability('moodle/backup:configure', $coursecontext->id, $roleid);
1050 // Optional capabilities to copy user data.
1051 $this->assignUserCapability('moodle/backup:userinfo', $coursecontext->id, $roleid);
1052 $this->assignUserCapability('moodle/restore:userinfo', $categorycontext->id, $roleid);
1053
1054 $newcourse['fullname'] = 'Course duplicate';
1055 $newcourse['shortname'] = 'courseduplicate';
1056 $newcourse['categoryid'] = $course->category;
1057 $newcourse['visible'] = true;
1058 $newcourse['options'][] = array('name' => 'users', 'value' => true);
1059
1060 $duplicate = core_course_external::duplicate_course($course->id, $newcourse['fullname'],
1061 $newcourse['shortname'], $newcourse['categoryid'], $newcourse['visible'], $newcourse['options']);
1062
fb695f6e
JM
1063 // We need to execute the return values cleaning process to simulate the web service server.
1064 $duplicate = external_api::clean_returnvalue(core_course_external::duplicate_course_returns(), $duplicate);
1065
2a7a0216
JM
1066 // Check that the course has been duplicated.
1067 $this->assertEquals($newcourse['shortname'], $duplicate['shortname']);
1068 }
791723c3
RT
1069
1070 /**
1071 * Test update_courses
1072 */
1073 public function test_update_courses() {
a182f88f
EL
1074 global $DB, $CFG, $USER, $COURSE;
1075
1076 // Get current $COURSE to be able to restore it later (defaults to $SITE). We need this
1077 // trick because we are both updating and getting (for testing) course information
1078 // in the same request and core_course_external::update_courses()
1079 // is overwriting $COURSE all over the time with OLD values, so later
1080 // use of get_course() fetches those OLD values instead of the updated ones.
1081 // See MDL-39723 for more info.
1082 $origcourse = clone($COURSE);
791723c3
RT
1083
1084 $this->resetAfterTest(true);
1085
1086 // Set the required capabilities by the external function.
1087 $contextid = context_system::instance()->id;
1088 $roleid = $this->assignUserCapability('moodle/course:update', $contextid);
1089 $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1090 $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1091 $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1092 $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1093 $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1094 $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
1095 $this->assignUserCapability('moodle/course:viewhiddencourses', $contextid, $roleid);
1096
1097 // Create category and course.
1098 $category1 = self::getDataGenerator()->create_category();
1099 $category2 = self::getDataGenerator()->create_category();
1100 $originalcourse1 = self::getDataGenerator()->create_course();
1101 self::getDataGenerator()->enrol_user($USER->id, $originalcourse1->id, $roleid);
1102 $originalcourse2 = self::getDataGenerator()->create_course();
1103 self::getDataGenerator()->enrol_user($USER->id, $originalcourse2->id, $roleid);
1104
1105 // Course values to be updated.
1106 $course1['id'] = $originalcourse1->id;
1107 $course1['fullname'] = 'Updated test course 1';
1108 $course1['shortname'] = 'Udestedtestcourse1';
1109 $course1['categoryid'] = $category1->id;
1110 $course2['id'] = $originalcourse2->id;
1111 $course2['fullname'] = 'Updated test course 2';
1112 $course2['shortname'] = 'Updestedtestcourse2';
1113 $course2['categoryid'] = $category2->id;
1114 $course2['idnumber'] = 'Updatedidnumber2';
1115 $course2['summary'] = 'Updaated description for course 2';
1116 $course2['summaryformat'] = FORMAT_HTML;
1117 $course2['format'] = 'topics';
1118 $course2['showgrades'] = 1;
1119 $course2['newsitems'] = 3;
1120 $course2['startdate'] = 1420092000; // 01/01/2015.
fbcdb0d7 1121 $course2['enddate'] = 1422669600; // 01/31/2015.
791723c3
RT
1122 $course2['maxbytes'] = 100000;
1123 $course2['showreports'] = 1;
1124 $course2['visible'] = 0;
1125 $course2['hiddensections'] = 0;
1126 $course2['groupmode'] = 0;
1127 $course2['groupmodeforce'] = 0;
1128 $course2['defaultgroupingid'] = 0;
1129 $course2['enablecompletion'] = 1;
1130 $course2['lang'] = 'en';
644fcbb6 1131 $course2['forcetheme'] = 'bootstrapbase';
791723c3
RT
1132 $courses = array($course1, $course2);
1133
1134 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1135 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1136 $updatedcoursewarnings);
a182f88f 1137 $COURSE = $origcourse; // Restore $COURSE. Instead of using the OLD one set by the previous line.
791723c3
RT
1138
1139 // Check that right number of courses were created.
1140 $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1141
1142 // Check that the courses were correctly created.
1143 foreach ($courses as $course) {
1144 $courseinfo = course_get_format($course['id'])->get_course();
1145 if ($course['id'] == $course2['id']) {
1146 $this->assertEquals($course2['fullname'], $courseinfo->fullname);
1147 $this->assertEquals($course2['shortname'], $courseinfo->shortname);
1148 $this->assertEquals($course2['categoryid'], $courseinfo->category);
1149 $this->assertEquals($course2['idnumber'], $courseinfo->idnumber);
1150 $this->assertEquals($course2['summary'], $courseinfo->summary);
1151 $this->assertEquals($course2['summaryformat'], $courseinfo->summaryformat);
1152 $this->assertEquals($course2['format'], $courseinfo->format);
1153 $this->assertEquals($course2['showgrades'], $courseinfo->showgrades);
1154 $this->assertEquals($course2['newsitems'], $courseinfo->newsitems);
1155 $this->assertEquals($course2['startdate'], $courseinfo->startdate);
fbcdb0d7 1156 $this->assertEquals($course2['enddate'], $courseinfo->enddate);
791723c3
RT
1157 $this->assertEquals($course2['maxbytes'], $courseinfo->maxbytes);
1158 $this->assertEquals($course2['showreports'], $courseinfo->showreports);
1159 $this->assertEquals($course2['visible'], $courseinfo->visible);
1160 $this->assertEquals($course2['hiddensections'], $courseinfo->hiddensections);
1161 $this->assertEquals($course2['groupmode'], $courseinfo->groupmode);
1162 $this->assertEquals($course2['groupmodeforce'], $courseinfo->groupmodeforce);
1163 $this->assertEquals($course2['defaultgroupingid'], $courseinfo->defaultgroupingid);
1164 $this->assertEquals($course2['lang'], $courseinfo->lang);
1165
1166 if (!empty($CFG->allowcoursethemes)) {
1167 $this->assertEquals($course2['forcetheme'], $courseinfo->theme);
1168 }
1169
8be9cffb 1170 $this->assertEquals($course2['enablecompletion'], $courseinfo->enablecompletion);
791723c3
RT
1171 } else if ($course['id'] == $course1['id']) {
1172 $this->assertEquals($course1['fullname'], $courseinfo->fullname);
1173 $this->assertEquals($course1['shortname'], $courseinfo->shortname);
1174 $this->assertEquals($course1['categoryid'], $courseinfo->category);
1175 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1176 $this->assertEquals('topics', $courseinfo->format);
89b909f6 1177 $this->assertEquals(5, course_get_format($course['id'])->get_last_section_number());
791723c3
RT
1178 $this->assertEquals(0, $courseinfo->newsitems);
1179 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1180 } else {
75c597da 1181 throw new moodle_exception('Unexpected shortname');
791723c3
RT
1182 }
1183 }
1184
1185 $courses = array($course1);
1186 // Try update course without update capability.
1187 $user = self::getDataGenerator()->create_user();
1188 $this->setUser($user);
1189 $this->unassignUserCapability('moodle/course:update', $contextid, $roleid);
1190 self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1191 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1192 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1193 $updatedcoursewarnings);
791723c3
RT
1194 $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1195
1196 // Try update course category without capability.
1197 $this->assignUserCapability('moodle/course:update', $contextid, $roleid);
1198 $this->unassignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1199 $user = self::getDataGenerator()->create_user();
1200 $this->setUser($user);
1201 self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1202 $course1['categoryid'] = $category2->id;
1203 $courses = array($course1);
1204 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1205 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1206 $updatedcoursewarnings);
791723c3
RT
1207 $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1208
1209 // Try update course fullname without capability.
1210 $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1211 $this->unassignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1212 $user = self::getDataGenerator()->create_user();
1213 $this->setUser($user);
1214 self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1215 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1216 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1217 $updatedcoursewarnings);
791723c3
RT
1218 $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1219 $course1['fullname'] = 'Testing fullname without permission';
1220 $courses = array($course1);
1221 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1222 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1223 $updatedcoursewarnings);
791723c3
RT
1224 $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1225
1226 // Try update course shortname without capability.
1227 $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1228 $this->unassignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1229 $user = self::getDataGenerator()->create_user();
1230 $this->setUser($user);
1231 self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1232 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1233 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1234 $updatedcoursewarnings);
791723c3
RT
1235 $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1236 $course1['shortname'] = 'Testing shortname without permission';
1237 $courses = array($course1);
1238 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1239 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1240 $updatedcoursewarnings);
791723c3
RT
1241 $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1242
1243 // Try update course idnumber without capability.
1244 $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1245 $this->unassignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1246 $user = self::getDataGenerator()->create_user();
1247 $this->setUser($user);
1248 self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1249 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1250 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1251 $updatedcoursewarnings);
791723c3
RT
1252 $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1253 $course1['idnumber'] = 'NEWIDNUMBER';
1254 $courses = array($course1);
1255 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1256 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1257 $updatedcoursewarnings);
791723c3
RT
1258 $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1259
1260 // Try update course summary without capability.
1261 $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1262 $this->unassignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1263 $user = self::getDataGenerator()->create_user();
1264 $this->setUser($user);
1265 self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1266 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1267 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1268 $updatedcoursewarnings);
791723c3
RT
1269 $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1270 $course1['summary'] = 'New summary';
1271 $courses = array($course1);
1272 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1273 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1274 $updatedcoursewarnings);
791723c3
RT
1275 $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1276
1277 // Try update course with invalid summary format.
1278 $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1279 $user = self::getDataGenerator()->create_user();
1280 $this->setUser($user);
1281 self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1282 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1283 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1284 $updatedcoursewarnings);
791723c3
RT
1285 $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1286 $course1['summaryformat'] = 10;
1287 $courses = array($course1);
1288 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1289 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1290 $updatedcoursewarnings);
791723c3
RT
1291 $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1292
1293 // Try update course visibility without capability.
1294 $this->unassignUserCapability('moodle/course:visibility', $contextid, $roleid);
1295 $user = self::getDataGenerator()->create_user();
1296 $this->setUser($user);
1297 self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1298 $course1['summaryformat'] = FORMAT_MOODLE;
1299 $courses = array($course1);
1300 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1301 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1302 $updatedcoursewarnings);
791723c3
RT
1303 $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1304 $course1['visible'] = 0;
1305 $courses = array($course1);
1306 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1307 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1308 $updatedcoursewarnings);
791723c3
RT
1309 $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1310 }
05fc7ccc 1311
79949c1b
MN
1312 /**
1313 * Test delete course_module.
1314 */
1315 public function test_delete_modules() {
1316 global $DB;
1317
1318 // Ensure we reset the data after this test.
1319 $this->resetAfterTest(true);
1320
1321 // Create a user.
1322 $user = self::getDataGenerator()->create_user();
1323
1324 // Set the tests to run as the user.
1325 self::setUser($user);
1326
1327 // Create a course to add the modules.
1328 $course = self::getDataGenerator()->create_course();
1329
1330 // Create two test modules.
1331 $record = new stdClass();
1332 $record->course = $course->id;
1333 $module1 = self::getDataGenerator()->create_module('forum', $record);
40cb4879 1334 $module2 = self::getDataGenerator()->create_module('assign', $record);
79949c1b
MN
1335
1336 // Check the forum was correctly created.
1337 $this->assertEquals(1, $DB->count_records('forum', array('id' => $module1->id)));
1338
1339 // Check the assignment was correctly created.
40cb4879 1340 $this->assertEquals(1, $DB->count_records('assign', array('id' => $module2->id)));
79949c1b
MN
1341
1342 // Check data exists in the course modules table.
1343 $this->assertEquals(2, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1344 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1345
1346 // Enrol the user in the course.
1347 $enrol = enrol_get_plugin('manual');
1348 $enrolinstances = enrol_get_instances($course->id, true);
1349 foreach ($enrolinstances as $courseenrolinstance) {
1350 if ($courseenrolinstance->enrol == "manual") {
1351 $instance = $courseenrolinstance;
1352 break;
1353 }
1354 }
1355 $enrol->enrol_user($instance, $user->id);
1356
1357 // Assign capabilities to delete module 1.
1358 $modcontext = context_module::instance($module1->cmid);
1359 $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id);
1360
1361 // Assign capabilities to delete module 2.
1362 $modcontext = context_module::instance($module2->cmid);
1363 $newrole = create_role('Role 2', 'role2', 'Role 2 description');
1364 $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id, $newrole);
1365
1366 // Deleting these module instances.
1367 core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1368
1369 // Check the forum was deleted.
1370 $this->assertEquals(0, $DB->count_records('forum', array('id' => $module1->id)));
1371
1372 // Check the assignment was deleted.
40cb4879 1373 $this->assertEquals(0, $DB->count_records('assign', array('id' => $module2->id)));
79949c1b
MN
1374
1375 // Check we retrieve no data in the course modules table.
1376 $this->assertEquals(0, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1377 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1378
1379 // Call with non-existent course module id and ensure exception thrown.
1380 try {
1381 core_course_external::delete_modules(array('1337'));
1382 $this->fail('Exception expected due to missing course module.');
1383 } catch (dml_missing_record_exception $e) {
affdc3b7 1384 $this->assertEquals('invalidcoursemodule', $e->errorcode);
79949c1b
MN
1385 }
1386
1387 // Create two modules.
1388 $module1 = self::getDataGenerator()->create_module('forum', $record);
40cb4879 1389 $module2 = self::getDataGenerator()->create_module('assign', $record);
79949c1b
MN
1390
1391 // Since these modules were recreated the user will not have capabilities
1392 // to delete them, ensure exception is thrown if they try.
1393 try {
1394 core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1395 $this->fail('Exception expected due to missing capability.');
1396 } catch (moodle_exception $e) {
1397 $this->assertEquals('nopermissions', $e->errorcode);
1398 }
1399
1400 // Unenrol user from the course.
1401 $enrol->unenrol_user($instance, $user->id);
1402
1403 // Try and delete modules from the course the user was unenrolled in, make sure exception thrown.
1404 try {
1405 core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1406 $this->fail('Exception expected due to being unenrolled from the course.');
1407 } catch (moodle_exception $e) {
1408 $this->assertEquals('requireloginerror', $e->errorcode);
1409 }
1410 }
fce10644
DP
1411
1412 /**
1413 * Test import_course into an empty course
1414 */
1415 public function test_import_course_empty() {
1416 global $USER;
1417
1418 $this->resetAfterTest(true);
1419
1420 $course1 = self::getDataGenerator()->create_course();
1421 $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course1->id, 'name' => 'Forum test'));
1422 $page = $this->getDataGenerator()->create_module('page', array('course' => $course1->id, 'name' => 'Page test'));
1423
1424 $course2 = self::getDataGenerator()->create_course();
1425
1426 $course1cms = get_fast_modinfo($course1->id)->get_cms();
1427 $course2cms = get_fast_modinfo($course2->id)->get_cms();
1428
1429 // Verify the state of the courses before we do the import.
1430 $this->assertCount(2, $course1cms);
1431 $this->assertEmpty($course2cms);
1432
1433 // Setup the user to run the operation (ugly hack because validate_context() will
1434 // fail as the email is not set by $this->setAdminUser()).
1435 $this->setAdminUser();
0fe86bbd 1436 $USER->email = 'emailtopass@example.com';
fce10644
DP
1437
1438 // Import from course1 to course2.
1439 core_course_external::import_course($course1->id, $course2->id, 0);
1440
1441 // Verify that now we have two modules in both courses.
1442 $course1cms = get_fast_modinfo($course1->id)->get_cms();
1443 $course2cms = get_fast_modinfo($course2->id)->get_cms();
1444 $this->assertCount(2, $course1cms);
1445 $this->assertCount(2, $course2cms);
1446
1447 // Verify that the names transfered across correctly.
1448 foreach ($course2cms as $cm) {
1449 if ($cm->modname === 'page') {
1450 $this->assertEquals($cm->name, $page->name);
1451 } else if ($cm->modname === 'forum') {
1452 $this->assertEquals($cm->name, $forum->name);
1453 } else {
1454 $this->fail('Unknown CM found.');
1455 }
1456 }
fce10644
DP
1457 }
1458
1459 /**
1460 * Test import_course into an filled course
1461 */
1462 public function test_import_course_filled() {
1463 global $USER;
1464
1465 $this->resetAfterTest(true);
1466
1467 // Add forum and page to course1.
1468 $course1 = self::getDataGenerator()->create_course();
1469 $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1470 $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1471
1472 // Add quiz to course 2.
1473 $course2 = self::getDataGenerator()->create_course();
1474 $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1475
1476 $course1cms = get_fast_modinfo($course1->id)->get_cms();
1477 $course2cms = get_fast_modinfo($course2->id)->get_cms();
1478
1479 // Verify the state of the courses before we do the import.
1480 $this->assertCount(2, $course1cms);
1481 $this->assertCount(1, $course2cms);
1482
1483 // Setup the user to run the operation (ugly hack because validate_context() will
1484 // fail as the email is not set by $this->setAdminUser()).
1485 $this->setAdminUser();
0fe86bbd 1486 $USER->email = 'emailtopass@example.com';
fce10644
DP
1487
1488 // Import from course1 to course2 without deleting content.
1489 core_course_external::import_course($course1->id, $course2->id, 0);
1490
1491 $course2cms = get_fast_modinfo($course2->id)->get_cms();
1492
1493 // Verify that now we have three modules in course2.
1494 $this->assertCount(3, $course2cms);
1495
1496 // Verify that the names transfered across correctly.
1497 foreach ($course2cms as $cm) {
1498 if ($cm->modname === 'page') {
1499 $this->assertEquals($cm->name, $page->name);
1500 } else if ($cm->modname === 'forum') {
1501 $this->assertEquals($cm->name, $forum->name);
1502 } else if ($cm->modname === 'quiz') {
1503 $this->assertEquals($cm->name, $quiz->name);
1504 } else {
1505 $this->fail('Unknown CM found.');
1506 }
1507 }
fce10644
DP
1508 }
1509
1510 /**
1511 * Test import_course with only blocks set to backup
1512 */
1513 public function test_import_course_blocksonly() {
1514 global $USER, $DB;
1515
1516 $this->resetAfterTest(true);
1517
1518 // Add forum and page to course1.
1519 $course1 = self::getDataGenerator()->create_course();
1520 $course1ctx = context_course::instance($course1->id);
1521 $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1522 $block = $this->getDataGenerator()->create_block('online_users', array('parentcontextid' => $course1ctx->id));
1523
1524 $course2 = self::getDataGenerator()->create_course();
1525 $course2ctx = context_course::instance($course2->id);
1526 $initialblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1527 $initialcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1528
1529 // Setup the user to run the operation (ugly hack because validate_context() will
1530 // fail as the email is not set by $this->setAdminUser()).
1531 $this->setAdminUser();
0fe86bbd 1532 $USER->email = 'emailtopass@example.com';
fce10644
DP
1533
1534 // Import from course1 to course2 without deleting content, but excluding
1535 // activities.
1536 $options = array(
1537 array('name' => 'activities', 'value' => 0),
1538 array('name' => 'blocks', 'value' => 1),
1539 array('name' => 'filters', 'value' => 0),
1540 );
1541
1542 core_course_external::import_course($course1->id, $course2->id, 0, $options);
1543
1544 $newcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1545 $newblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1546 // Check that course modules haven't changed, but that blocks have.
1547 $this->assertEquals($initialcmcount, $newcmcount);
1548 $this->assertEquals(($initialblockcount + 1), $newblockcount);
fce10644
DP
1549 }
1550
1551 /**
1552 * Test import_course into an filled course, deleting content.
1553 */
1554 public function test_import_course_deletecontent() {
1555 global $USER;
1556 $this->resetAfterTest(true);
1557
1558 // Add forum and page to course1.
1559 $course1 = self::getDataGenerator()->create_course();
1560 $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1561 $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1562
1563 // Add quiz to course 2.
1564 $course2 = self::getDataGenerator()->create_course();
1565 $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1566
1567 $course1cms = get_fast_modinfo($course1->id)->get_cms();
1568 $course2cms = get_fast_modinfo($course2->id)->get_cms();
1569
1570 // Verify the state of the courses before we do the import.
1571 $this->assertCount(2, $course1cms);
1572 $this->assertCount(1, $course2cms);
1573
1574 // Setup the user to run the operation (ugly hack because validate_context() will
1575 // fail as the email is not set by $this->setAdminUser()).
1576 $this->setAdminUser();
0fe86bbd 1577 $USER->email = 'emailtopass@example.com';
fce10644
DP
1578
1579 // Import from course1 to course2, deleting content.
1580 core_course_external::import_course($course1->id, $course2->id, 1);
1581
1582 $course2cms = get_fast_modinfo($course2->id)->get_cms();
1583
1584 // Verify that now we have two modules in course2.
1585 $this->assertCount(2, $course2cms);
1586
1587 // Verify that the course only contains the imported modules.
1588 foreach ($course2cms as $cm) {
1589 if ($cm->modname === 'page') {
1590 $this->assertEquals($cm->name, $page->name);
1591 } else if ($cm->modname === 'forum') {
1592 $this->assertEquals($cm->name, $forum->name);
1593 } else {
1594 $this->fail('Unknown CM found: '.$cm->name);
1595 }
1596 }
fce10644
DP
1597 }
1598
1599 /**
1600 * Ensure import_course handles incorrect deletecontent option correctly.
1601 */
1602 public function test_import_course_invalid_deletecontent_option() {
1603 $this->resetAfterTest(true);
1604
1605 $course1 = self::getDataGenerator()->create_course();
1606 $course2 = self::getDataGenerator()->create_course();
1607
52f3e060
RT
1608 $this->expectException('moodle_exception');
1609 $this->expectExceptionMessage(get_string('invalidextparam', 'webservice', -1));
fce10644
DP
1610 // Import from course1 to course2, with invalid option
1611 core_course_external::import_course($course1->id, $course2->id, -1);;
1612 }
e81f67ca
JL
1613
1614 /**
1615 * Test view_course function
1616 */
1617 public function test_view_course() {
1618
1619 $this->resetAfterTest();
1620
1621 // Course without sections.
1622 $course = $this->getDataGenerator()->create_course(array('numsections' => 5), array('createsections' => true));
1623 $this->setAdminUser();
1624
1625 // Redirect events to the sink, so we can recover them later.
1626 $sink = $this->redirectEvents();
1627
bdf9f4d4
JL
1628 $result = core_course_external::view_course($course->id, 1);
1629 $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
e81f67ca
JL
1630 $events = $sink->get_events();
1631 $event = reset($events);
1632
1633 // Check the event details are correct.
1634 $this->assertInstanceOf('\core\event\course_viewed', $event);
1635 $this->assertEquals(context_course::instance($course->id), $event->get_context());
1636 $this->assertEquals(1, $event->other['coursesectionnumber']);
1637
bdf9f4d4
JL
1638 $result = core_course_external::view_course($course->id);
1639 $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
e81f67ca
JL
1640 $events = $sink->get_events();
1641 $event = array_pop($events);
1642 $sink->close();
1643
1644 // Check the event details are correct.
1645 $this->assertInstanceOf('\core\event\course_viewed', $event);
1646 $this->assertEquals(context_course::instance($course->id), $event->get_context());
1647 $this->assertEmpty($event->other);
1648
1649 }
c5158499
JL
1650
1651 /**
1652 * Test get_course_module
1653 */
1654 public function test_get_course_module() {
1655 global $DB;
1656
1657 $this->resetAfterTest(true);
1658
1659 $this->setAdminUser();
1660 $course = self::getDataGenerator()->create_course();
1661 $record = array(
1662 'course' => $course->id,
796876b0 1663 'name' => 'First Assignment'
c5158499
JL
1664 );
1665 $options = array(
1666 'idnumber' => 'ABC',
1667 'visible' => 0
1668 );
1669 // Hidden activity.
796876b0 1670 $assign = self::getDataGenerator()->create_module('assign', $record, $options);
c5158499 1671
28ff87be
PFO
1672 $outcomescale = 'Distinction, Very Good, Good, Pass, Fail';
1673
1674 // Insert a custom grade scale to be used by an outcome.
1675 $gradescale = new grade_scale();
1676 $gradescale->name = 'gettcoursemodulescale';
1677 $gradescale->courseid = $course->id;
1678 $gradescale->userid = 0;
1679 $gradescale->scale = $outcomescale;
1680 $gradescale->description = 'This scale is used to mark standard assignments.';
1681 $gradescale->insert();
1682
1683 // Insert an outcome.
1684 $data = new stdClass();
1685 $data->courseid = $course->id;
1686 $data->fullname = 'Team work';
1687 $data->shortname = 'Team work';
1688 $data->scaleid = $gradescale->id;
1689 $outcome = new grade_outcome($data, false);
1690 $outcome->insert();
1691
1692 $outcomegradeitem = new grade_item();
1693 $outcomegradeitem->itemname = $outcome->shortname;
1694 $outcomegradeitem->itemtype = 'mod';
1695 $outcomegradeitem->itemmodule = 'assign';
1696 $outcomegradeitem->iteminstance = $assign->id;
1697 $outcomegradeitem->outcomeid = $outcome->id;
1698 $outcomegradeitem->cmid = 0;
1699 $outcomegradeitem->courseid = $course->id;
1700 $outcomegradeitem->aggregationcoef = 0;
1701 $outcomegradeitem->itemnumber = 1; // The activity's original grade item will be 0.
1702 $outcomegradeitem->gradetype = GRADE_TYPE_SCALE;
1703 $outcomegradeitem->scaleid = $outcome->scaleid;
1704 $outcomegradeitem->insert();
1705
1706 $assignmentgradeitem = grade_item::fetch(
1707 array(
1708 'itemtype' => 'mod',
1709 'itemmodule' => 'assign',
1710 'iteminstance' => $assign->id,
1711 'itemnumber' => 0,
1712 'courseid' => $course->id
1713 )
1714 );
1715 $outcomegradeitem->set_parent($assignmentgradeitem->categoryid);
1716 $outcomegradeitem->move_after_sortorder($assignmentgradeitem->sortorder);
1717
c5158499 1718 // Test admin user can see the complete hidden activity.
796876b0 1719 $result = core_course_external::get_course_module($assign->cmid);
c5158499
JL
1720 $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
1721
1722 $this->assertCount(0, $result['warnings']);
1723 // Test we retrieve all the fields.
8341055e 1724 $this->assertCount(28, $result['cm']);
c5158499
JL
1725 $this->assertEquals($record['name'], $result['cm']['name']);
1726 $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
796876b0
JL
1727 $this->assertEquals(100, $result['cm']['grade']);
1728 $this->assertEquals(0.0, $result['cm']['gradepass']);
1729 $this->assertEquals('submissions', $result['cm']['advancedgrading'][0]['area']);
1730 $this->assertEmpty($result['cm']['advancedgrading'][0]['method']);
28ff87be 1731 $this->assertEquals($outcomescale, $result['cm']['outcomes'][0]['scale']);
c5158499
JL
1732
1733 $student = $this->getDataGenerator()->create_user();
1734 $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1735
1736 self::getDataGenerator()->enrol_user($student->id, $course->id, $studentrole->id);
1737 $this->setUser($student);
1738
1739 // The user shouldn't be able to see the activity.
1740 try {
796876b0 1741 core_course_external::get_course_module($assign->cmid);
c5158499
JL
1742 $this->fail('Exception expected due to invalid permissions.');
1743 } catch (moodle_exception $e) {
1744 $this->assertEquals('requireloginerror', $e->errorcode);
1745 }
1746
1747 // Make module visible.
796876b0 1748 set_coursemodule_visible($assign->cmid, 1);
c5158499
JL
1749
1750 // Test student user.
796876b0 1751 $result = core_course_external::get_course_module($assign->cmid);
c5158499
JL
1752 $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
1753
1754 $this->assertCount(0, $result['warnings']);
1755 // Test we retrieve only the few files we can see.
1756 $this->assertCount(11, $result['cm']);
796876b0 1757 $this->assertEquals($assign->cmid, $result['cm']['id']);
c5158499 1758 $this->assertEquals($course->id, $result['cm']['course']);
796876b0
JL
1759 $this->assertEquals('assign', $result['cm']['modname']);
1760 $this->assertEquals($assign->id, $result['cm']['instance']);
c5158499
JL
1761
1762 }
13bb6819
JL
1763
1764 /**
1765 * Test get_course_module_by_instance
1766 */
1767 public function test_get_course_module_by_instance() {
1768 global $DB;
1769
1770 $this->resetAfterTest(true);
1771
1772 $this->setAdminUser();
1773 $course = self::getDataGenerator()->create_course();
1774 $record = array(
1775 'course' => $course->id,
1776 'name' => 'First Chat'
1777 );
1778 $options = array(
1779 'idnumber' => 'ABC',
1780 'visible' => 0
1781 );
1782 // Hidden activity.
1783 $chat = self::getDataGenerator()->create_module('chat', $record, $options);
1784
1785 // Test admin user can see the complete hidden activity.
1786 $result = core_course_external::get_course_module_by_instance('chat', $chat->id);
1787 $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
1788
1789 $this->assertCount(0, $result['warnings']);
1790 // Test we retrieve all the fields.
8341055e 1791 $this->assertCount(23, $result['cm']);
13bb6819
JL
1792 $this->assertEquals($record['name'], $result['cm']['name']);
1793 $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
1794
1795 $student = $this->getDataGenerator()->create_user();
1796 $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1797
1798 self::getDataGenerator()->enrol_user($student->id, $course->id, $studentrole->id);
1799 $this->setUser($student);
1800
1801 // The user shouldn't be able to see the activity.
1802 try {
1803 core_course_external::get_course_module_by_instance('chat', $chat->id);
1804 $this->fail('Exception expected due to invalid permissions.');
1805 } catch (moodle_exception $e) {
1806 $this->assertEquals('requireloginerror', $e->errorcode);
1807 }
1808
1809 // Make module visible.
1810 set_coursemodule_visible($chat->cmid, 1);
1811
1812 // Test student user.
1813 $result = core_course_external::get_course_module_by_instance('chat', $chat->id);
1814 $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
1815
1816 $this->assertCount(0, $result['warnings']);
1817 // Test we retrieve only the few files we can see.
1818 $this->assertCount(11, $result['cm']);
1819 $this->assertEquals($chat->cmid, $result['cm']['id']);
1820 $this->assertEquals($course->id, $result['cm']['course']);
1821 $this->assertEquals('chat', $result['cm']['modname']);
1822 $this->assertEquals($chat->id, $result['cm']['instance']);
1823
1824 // Try with an invalid module name.
1825 try {
1826 core_course_external::get_course_module_by_instance('abc', $chat->id);
1827 $this->fail('Exception expected due to invalid module name.');
1828 } catch (dml_read_exception $e) {
1829 $this->assertEquals('dmlreadexception', $e->errorcode);
1830 }
1831
1832 }
7c4e686f
JL
1833
1834 /**
1835 * Test get_activities_overview
1836 */
1837 public function test_get_activities_overview() {
1838 global $USER;
1839
1840 $this->resetAfterTest();
1841 $course1 = self::getDataGenerator()->create_course();
1842 $course2 = self::getDataGenerator()->create_course();
1843
1844 // Create a viewer user.
1845 $viewer = self::getDataGenerator()->create_user((object) array('trackforums' => 1));
1846 $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
1847 $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
1848
1849 // Create two forums - one in each course.
1850 $record = new stdClass();
1851 $record->course = $course1->id;
1852 $forum1 = self::getDataGenerator()->create_module('forum', (object) array('course' => $course1->id));
1853 $forum2 = self::getDataGenerator()->create_module('forum', (object) array('course' => $course2->id));
1854
1855 $this->setAdminUser();
1856 // A standard post in the forum.
1857 $record = new stdClass();
1858 $record->course = $course1->id;
1859 $record->userid = $USER->id;
1860 $record->forum = $forum1->id;
1861 $this->getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
1862
1863 $this->setUser($viewer->id);
1864 $courses = array($course1->id , $course2->id);
1865
1866 $result = core_course_external::get_activities_overview($courses);
e9dfeec9 1867 $this->assertDebuggingCalledCount(8);
7c4e686f
JL
1868 $result = external_api::clean_returnvalue(core_course_external::get_activities_overview_returns(), $result);
1869
1870 // There should be one entry for course1, and no others.
1871 $this->assertCount(1, $result['courses']);
1872 $this->assertEquals($course1->id, $result['courses'][0]['id']);
1873 // Check expected overview data for the module.
1874 $this->assertEquals('forum', $result['courses'][0]['overviews'][0]['module']);
1875 $this->assertContains('1 total unread', $result['courses'][0]['overviews'][0]['overviewtext']);
1876 }
c115ff6a
JL
1877
1878 /**
1879 * Test get_user_navigation_options
1880 */
1881 public function test_get_user_navigation_options() {
1882 global $USER;
1883
1884 $this->resetAfterTest();
1885 $course1 = self::getDataGenerator()->create_course();
1886 $course2 = self::getDataGenerator()->create_course();
1887
1888 // Create a viewer user.
1889 $viewer = self::getDataGenerator()->create_user();
1890 $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
1891 $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
1892
1893 $this->setUser($viewer->id);
1894 $courses = array($course1->id , $course2->id, SITEID);
1895
1896 $result = core_course_external::get_user_navigation_options($courses);
1897 $result = external_api::clean_returnvalue(core_course_external::get_user_navigation_options_returns(), $result);
1898
1899 $this->assertCount(0, $result['warnings']);
1900 $this->assertCount(3, $result['courses']);
1901
1902 foreach ($result['courses'] as $course) {
1903 $navoptions = new stdClass;
1904 foreach ($course['options'] as $option) {
1905 $navoptions->{$option['name']} = $option['available'];
1906 }
203f51d6 1907 $this->assertCount(9, $course['options']);
c115ff6a 1908 if ($course['id'] == SITEID) {
c115ff6a
JL
1909 $this->assertTrue($navoptions->blogs);
1910 $this->assertFalse($navoptions->notes);
1911 $this->assertFalse($navoptions->participants);
1912 $this->assertTrue($navoptions->badges);
1913 $this->assertTrue($navoptions->tags);
203f51d6 1914 $this->assertFalse($navoptions->grades);
c115ff6a
JL
1915 $this->assertFalse($navoptions->search);
1916 $this->assertTrue($navoptions->calendar);
99061152 1917 $this->assertTrue($navoptions->competencies);
c115ff6a 1918 } else {
c115ff6a
JL
1919 $this->assertTrue($navoptions->blogs);
1920 $this->assertFalse($navoptions->notes);
1921 $this->assertTrue($navoptions->participants);
1922 $this->assertTrue($navoptions->badges);
203f51d6 1923 $this->assertFalse($navoptions->tags);
99061152 1924 $this->assertTrue($navoptions->grades);
203f51d6
DP
1925 $this->assertFalse($navoptions->search);
1926 $this->assertFalse($navoptions->calendar);
99061152 1927 $this->assertTrue($navoptions->competencies);
c115ff6a
JL
1928 }
1929 }
1930 }
b9050b10
JL
1931
1932 /**
1933 * Test get_user_administration_options
1934 */
1935 public function test_get_user_administration_options() {
1936 global $USER;
1937
1938 $this->resetAfterTest();
1939 $course1 = self::getDataGenerator()->create_course();
1940 $course2 = self::getDataGenerator()->create_course();
1941
1942 // Create a viewer user.
1943 $viewer = self::getDataGenerator()->create_user();
1944 $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
1945 $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
1946
1947 $this->setUser($viewer->id);
1948 $courses = array($course1->id , $course2->id, SITEID);
1949
1950 $result = core_course_external::get_user_administration_options($courses);
1951 $result = external_api::clean_returnvalue(core_course_external::get_user_administration_options_returns(), $result);
1952
1953 $this->assertCount(0, $result['warnings']);
1954 $this->assertCount(3, $result['courses']);
1955
1956 foreach ($result['courses'] as $course) {
1957 $adminoptions = new stdClass;
1958 foreach ($course['options'] as $option) {
1959 $adminoptions->{$option['name']} = $option['available'];
1960 }
1961 if ($course['id'] == SITEID) {
0cbc248d 1962 $this->assertCount(16, $course['options']);
b9050b10
JL
1963 $this->assertFalse($adminoptions->update);
1964 $this->assertFalse($adminoptions->filters);
1965 $this->assertFalse($adminoptions->reports);
1966 $this->assertFalse($adminoptions->backup);
1967 $this->assertFalse($adminoptions->restore);
1968 $this->assertFalse($adminoptions->files);
c874d9aa
JL
1969 $this->assertFalse(!isset($adminoptions->tags));
1970 $this->assertFalse($adminoptions->gradebook);
1971 $this->assertFalse($adminoptions->outcomes);
1972 $this->assertFalse($adminoptions->badges);
1973 $this->assertFalse($adminoptions->import);
1974 $this->assertFalse($adminoptions->publish);
1975 $this->assertFalse($adminoptions->reset);
1976 $this->assertFalse($adminoptions->roles);
0cbc248d 1977 $this->assertFalse($adminoptions->editcompletion);
b9050b10 1978 } else {
0cbc248d 1979 $this->assertCount(15, $course['options']);
b9050b10
JL
1980 $this->assertFalse($adminoptions->update);
1981 $this->assertFalse($adminoptions->filters);
1982 $this->assertFalse($adminoptions->reports);
1983 $this->assertFalse($adminoptions->backup);
1984 $this->assertFalse($adminoptions->restore);
1985 $this->assertFalse($adminoptions->files);
1986 $this->assertFalse($adminoptions->tags);
1987 $this->assertFalse($adminoptions->gradebook);
1988 $this->assertFalse($adminoptions->outcomes);
1989 $this->assertTrue($adminoptions->badges);
1990 $this->assertFalse($adminoptions->import);
1991 $this->assertFalse($adminoptions->publish);
1992 $this->assertFalse($adminoptions->reset);
1993 $this->assertFalse($adminoptions->roles);
0cbc248d 1994 $this->assertFalse($adminoptions->editcompletion);
b9050b10
JL
1995 }
1996 }
1997 }
80adabef
JL
1998
1999 /**
2000 * Test get_courses_by_fields
2001 */
2002 public function test_get_courses_by_field() {
2003 global $DB;
2004 $this->resetAfterTest(true);
2005
2006 $category1 = self::getDataGenerator()->create_category();
2007 $category2 = self::getDataGenerator()->create_category(array('parent' => $category1->id));
2008 $course1 = self::getDataGenerator()->create_course(array('category' => $category1->id, 'shortname' => 'c1'));
2009 $course2 = self::getDataGenerator()->create_course(array('visible' => 0, 'category' => $category2->id, 'idnumber' => 'i2'));
2010
2011 $student1 = self::getDataGenerator()->create_user();
2012 $user1 = self::getDataGenerator()->create_user();
2013 $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2014 self::getDataGenerator()->enrol_user($student1->id, $course1->id, $studentrole->id);
2015 self::getDataGenerator()->enrol_user($student1->id, $course2->id, $studentrole->id);
2016
2017 self::setAdminUser();
2018 // As admins, we should be able to retrieve everything.
2019 $result = core_course_external::get_courses_by_field();
2020 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2021 $this->assertCount(3, $result['courses']);
2022 // Expect to receive all the fields.
e45fc71e
JL
2023 $this->assertCount(36, $result['courses'][0]);
2024 $this->assertCount(36, $result['courses'][1]);
2025 $this->assertCount(36, $result['courses'][2]);
80adabef
JL
2026
2027 $result = core_course_external::get_courses_by_field('id', $course1->id);
2028 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2029 $this->assertCount(1, $result['courses']);
2030 $this->assertEquals($course1->id, $result['courses'][0]['id']);
2031 // Expect to receive all the fields.
e45fc71e 2032 $this->assertCount(36, $result['courses'][0]);
80adabef
JL
2033
2034 $result = core_course_external::get_courses_by_field('id', $course2->id);
2035 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2036 $this->assertCount(1, $result['courses']);
2037 $this->assertEquals($course2->id, $result['courses'][0]['id']);
2038
2039 $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2040 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2041 $this->assertCount(2, $result['courses']);
2042
e45fc71e
JL
2043 // Check default filters.
2044 $this->assertCount(3, $result['courses'][0]['filters']);
2045 $this->assertCount(3, $result['courses'][1]['filters']);
2046
80adabef
JL
2047 $result = core_course_external::get_courses_by_field('category', $category1->id);
2048 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2049 $this->assertCount(1, $result['courses']);
2050 $this->assertEquals($course1->id, $result['courses'][0]['id']);
2051
2052 $result = core_course_external::get_courses_by_field('shortname', 'c1');
2053 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2054 $this->assertCount(1, $result['courses']);
2055 $this->assertEquals($course1->id, $result['courses'][0]['id']);
2056
2057 $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2058 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2059 $this->assertCount(1, $result['courses']);
2060 $this->assertEquals($course2->id, $result['courses'][0]['id']);
2061
2062 $result = core_course_external::get_courses_by_field('idnumber', 'x');
2063 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2064 $this->assertCount(0, $result['courses']);
2065
e45fc71e
JL
2066 // Change filter value.
2067 filter_set_local_state('mediaplugin', context_course::instance($course1->id)->id, TEXTFILTER_OFF);
2068
80adabef
JL
2069 self::setUser($student1);
2070 // All visible courses (including front page) for normal student.
2071 $result = core_course_external::get_courses_by_field();
2072 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2073 $this->assertCount(2, $result['courses']);
e45fc71e
JL
2074 $this->assertCount(29, $result['courses'][0]);
2075 $this->assertCount(29, $result['courses'][1]);
80adabef
JL
2076
2077 $result = core_course_external::get_courses_by_field('id', $course1->id);
2078 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2079 $this->assertCount(1, $result['courses']);
2080 $this->assertEquals($course1->id, $result['courses'][0]['id']);
2081 // Expect to receive all the files that a student can see.
e45fc71e
JL
2082 $this->assertCount(29, $result['courses'][0]);
2083
2084 // Check default filters.
2085 $filters = $result['courses'][0]['filters'];
2086 $this->assertCount(3, $filters);
2087 $found = false;
2088 foreach ($filters as $filter) {
2089 if ($filter['filter'] == 'mediaplugin' and $filter['localstate'] == TEXTFILTER_OFF) {
2090 $found = true;
2091 }
2092 }
2093 $this->assertTrue($found);
80adabef
JL
2094
2095 // Course 2 is not visible.
2096 $result = core_course_external::get_courses_by_field('id', $course2->id);
2097 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2098 $this->assertCount(0, $result['courses']);
2099
2100 $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2101 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2102 $this->assertCount(1, $result['courses']);
2103
2104 $result = core_course_external::get_courses_by_field('category', $category1->id);
2105 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2106 $this->assertCount(1, $result['courses']);
2107 $this->assertEquals($course1->id, $result['courses'][0]['id']);
2108
2109 $result = core_course_external::get_courses_by_field('shortname', 'c1');
2110 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2111 $this->assertCount(1, $result['courses']);
2112 $this->assertEquals($course1->id, $result['courses'][0]['id']);
2113
2114 $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2115 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2116 $this->assertCount(0, $result['courses']);
2117
2118 $result = core_course_external::get_courses_by_field('idnumber', 'x');
2119 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2120 $this->assertCount(0, $result['courses']);
2121
2122 self::setUser($user1);
2123 // All visible courses (including front page) for authenticated user.
2124 $result = core_course_external::get_courses_by_field();
2125 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2126 $this->assertCount(2, $result['courses']);
e45fc71e 2127 $this->assertCount(29, $result['courses'][0]); // Site course.
fb41d2f0 2128 $this->assertCount(13, $result['courses'][1]); // Only public information, not enrolled.
80adabef
JL
2129
2130 $result = core_course_external::get_courses_by_field('id', $course1->id);
2131 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2132 $this->assertCount(1, $result['courses']);
2133 $this->assertEquals($course1->id, $result['courses'][0]['id']);
2134 // Expect to receive all the files that a authenticated can see.
fb41d2f0 2135 $this->assertCount(13, $result['courses'][0]);
80adabef
JL
2136
2137 // Course 2 is not visible.
2138 $result = core_course_external::get_courses_by_field('id', $course2->id);
2139 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2140 $this->assertCount(0, $result['courses']);
2141
2142 $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2143 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2144 $this->assertCount(1, $result['courses']);
2145
2146 $result = core_course_external::get_courses_by_field('category', $category1->id);
2147 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2148 $this->assertCount(1, $result['courses']);
2149 $this->assertEquals($course1->id, $result['courses'][0]['id']);
2150
2151 $result = core_course_external::get_courses_by_field('shortname', 'c1');
2152 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2153 $this->assertCount(1, $result['courses']);
2154 $this->assertEquals($course1->id, $result['courses'][0]['id']);
2155
2156 $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2157 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2158 $this->assertCount(0, $result['courses']);
2159
2160 $result = core_course_external::get_courses_by_field('idnumber', 'x');
2161 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2162 $this->assertCount(0, $result['courses']);
2163 }
2164
2165 public function test_get_courses_by_field_invalid_field() {
2166 $this->expectException('invalid_parameter_exception');
2167 $result = core_course_external::get_courses_by_field('zyx', 'x');
2168 }
2169
2170 public function test_get_courses_by_field_invalid_courses() {
2171 $result = core_course_external::get_courses_by_field('id', '-1');
2172 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2173 $this->assertCount(0, $result['courses']);
2174 }
26659f62
JL
2175
2176 public function test_check_updates() {
2177 global $DB;
2178 $this->resetAfterTest(true);
2179 $this->setAdminUser();
2180
2181 // Create different types of activities.
2182 $course = self::getDataGenerator()->create_course();
2183 $tocreate = array('assign', 'book', 'choice', 'folder', 'forum', 'glossary', 'imscp', 'label', 'lti', 'page', 'quiz',
2184 'resource', 'scorm', 'survey', 'url', 'wiki');
2185
2186 $modules = array();
2187 foreach ($tocreate as $modname) {
2188 $modules[$modname]['instance'] = $this->getDataGenerator()->create_module($modname, array('course' => $course->id));
2189 $modules[$modname]['cm'] = get_coursemodule_from_id(false, $modules[$modname]['instance']->cmid);
2190 $modules[$modname]['context'] = context_module::instance($modules[$modname]['instance']->cmid);
2191 }
2192
2193 $student = self::getDataGenerator()->create_user();
2194 $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2195 self::getDataGenerator()->enrol_user($student->id, $course->id, $studentrole->id);
2196 $this->setUser($student);
2197
2198 $since = time();
2199 $this->waitForSecond();
2200 $params = array();
2201 foreach ($modules as $modname => $data) {
2202 $params[$data['cm']->id] = array(
2203 'contextlevel' => 'module',
2204 'id' => $data['cm']->id,
2205 'since' => $since
2206 );
2207 }
2208
2209 // Check there is nothing updated because modules are fresh new.
2210 $result = core_course_external::check_updates($course->id, $params);
2211 $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
25adfbaa 2212 $this->assertCount(0, $result['instances']);
26659f62 2213 $this->assertCount(0, $result['warnings']);
26659f62 2214
879a8f56
JL
2215 // Test with get_updates_since the same data.
2216 $result = core_course_external::get_updates_since($course->id, $since);
2217 $result = external_api::clean_returnvalue(core_course_external::get_updates_since_returns(), $result);
2218 $this->assertCount(0, $result['instances']);
2219 $this->assertCount(0, $result['warnings']);
2220
26659f62
JL
2221 // Update a module after a second.
2222 $this->waitForSecond();
2223 set_coursemodule_name($modules['forum']['cm']->id, 'New forum name');
2224
2225 $found = false;
2226 $result = core_course_external::check_updates($course->id, $params);
2227 $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
25adfbaa 2228 $this->assertCount(1, $result['instances']);
26659f62
JL
2229 $this->assertCount(0, $result['warnings']);
2230 foreach ($result['instances'] as $module) {
2231 foreach ($module['updates'] as $update) {
2232 if ($module['id'] == $modules['forum']['cm']->id and $update['name'] == 'configuration') {
26659f62 2233 $found = true;
879a8f56
JL
2234 }
2235 }
2236 }
2237 $this->assertTrue($found);
2238
2239 // Test with get_updates_since the same data.
2240 $result = core_course_external::get_updates_since($course->id, $since);
2241 $result = external_api::clean_returnvalue(core_course_external::get_updates_since_returns(), $result);
2242 $this->assertCount(1, $result['instances']);
2243 $this->assertCount(0, $result['warnings']);
2244 $found = false;
2245 $this->assertCount(1, $result['instances']);
2246 $this->assertCount(0, $result['warnings']);
2247 foreach ($result['instances'] as $module) {
2248 foreach ($module['updates'] as $update) {
2249 if ($module['id'] == $modules['forum']['cm']->id and $update['name'] == 'configuration') {
2250 $found = true;
26659f62
JL
2251 }
2252 }
2253 }
2254 $this->assertTrue($found);
2255
2256 // Do not retrieve the configuration field.
2257 $filter = array('files');
2258 $found = false;
2259 $result = core_course_external::check_updates($course->id, $params, $filter);
2260 $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
25adfbaa 2261 $this->assertCount(0, $result['instances']);
26659f62 2262 $this->assertCount(0, $result['warnings']);
26659f62
JL
2263 $this->assertFalse($found);
2264
2265 // Add invalid cmid.
2266 $params[] = array(
2267 'contextlevel' => 'module',
2268 'id' => -2,
2269 'since' => $since
2270 );
2271 $result = core_course_external::check_updates($course->id, $params);
2272 $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2273 $this->assertCount(1, $result['warnings']);
2274 $this->assertEquals(-2, $result['warnings'][0]['itemid']);
2275 }
2a7a0216 2276}