MDL-55074 theme_boost: Navigation and blocks
[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
281 // Call without required capability (it will fail cause of the search on idnumber).
282 $this->unassignUserCapability('moodle/category:manage', $context->id, $roleid);
52f3e060 283 $this->expectException('moodle_exception');
2a7a0216
JM
284 $categories = core_course_external::get_categories(array(
285 array('key' => 'id', 'value' => $category1->id),
286 array('key' => 'idnumber', 'value' => $category1->idnumber),
287 array('key' => 'visible', 'value' => 1)), 0);
288 }
289
290 /**
291 * Test update_categories
292 */
293 public function test_update_categories() {
294 global $DB;
295
296 $this->resetAfterTest(true);
297
298 // Set the required capabilities by the external function
299 $contextid = context_system::instance()->id;
300 $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
301
302 // Create base categories.
303 $category1data['idnumber'] = 'idnumbercat1';
304 $category1data['name'] = 'Category 1 for PHPunit test';
305 $category1data['description'] = 'Category 1 description';
306 $category1data['descriptionformat'] = FORMAT_MOODLE;
307 $category1 = self::getDataGenerator()->create_category($category1data);
308 $category2 = self::getDataGenerator()->create_category(
309 array('parent' => $category1->id));
310 $category3 = self::getDataGenerator()->create_category();
311 $category4 = self::getDataGenerator()->create_category(
312 array('parent' => $category3->id));
313 $category5 = self::getDataGenerator()->create_category(
314 array('parent' => $category4->id));
315
316 // We update all category1 attribut.
317 // Then we move cat4 and cat5 parent: cat3 => cat1
318 $categories = array(
319 array('id' => $category1->id,
320 'name' => $category1->name . '_updated',
321 'idnumber' => $category1->idnumber . '_updated',
322 'description' => $category1->description . '_updated',
323 'descriptionformat' => FORMAT_HTML,
324 'theme' => $category1->theme),
325 array('id' => $category4->id, 'parent' => $category1->id));
326
327 core_course_external::update_categories($categories);
328
329 // Check the values were updated.
330 $dbcategories = $DB->get_records_select('course_categories',
331 'id IN (' . $category1->id . ',' . $category2->id . ',' . $category2->id
332 . ',' . $category3->id . ',' . $category4->id . ',' . $category5->id .')');
333 $this->assertEquals($category1->name . '_updated',
334 $dbcategories[$category1->id]->name);
335 $this->assertEquals($category1->idnumber . '_updated',
336 $dbcategories[$category1->id]->idnumber);
337 $this->assertEquals($category1->description . '_updated',
338 $dbcategories[$category1->id]->description);
339 $this->assertEquals(FORMAT_HTML, $dbcategories[$category1->id]->descriptionformat);
340
341 // Check that category4 and category5 have been properly moved.
342 $this->assertEquals('/' . $category1->id . '/' . $category4->id,
343 $dbcategories[$category4->id]->path);
344 $this->assertEquals('/' . $category1->id . '/' . $category4->id . '/' . $category5->id,
345 $dbcategories[$category5->id]->path);
346
347 // Call without required capability.
348 $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
52f3e060 349 $this->expectException('required_capability_exception');
2a7a0216
JM
350 core_course_external::update_categories($categories);
351 }
352
353 /**
354 * Test create_courses
355 */
356 public function test_create_courses() {
357 global $DB;
358
359 $this->resetAfterTest(true);
360
821676f5
JM
361 // Enable course completion.
362 set_config('enablecompletion', 1);
141e7d87
DP
363 // Enable course themes.
364 set_config('allowcoursethemes', 1);
821676f5 365
2a7a0216
JM
366 // Set the required capabilities by the external function
367 $contextid = context_system::instance()->id;
368 $roleid = $this->assignUserCapability('moodle/course:create', $contextid);
369 $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
370
371 $category = self::getDataGenerator()->create_category();
372
373 // Create base categories.
374 $course1['fullname'] = 'Test course 1';
375 $course1['shortname'] = 'Testcourse1';
376 $course1['categoryid'] = $category->id;
377 $course2['fullname'] = 'Test course 2';
378 $course2['shortname'] = 'Testcourse2';
379 $course2['categoryid'] = $category->id;
380 $course2['idnumber'] = 'testcourse2idnumber';
381 $course2['summary'] = 'Description for course 2';
382 $course2['summaryformat'] = FORMAT_MOODLE;
383 $course2['format'] = 'weeks';
384 $course2['showgrades'] = 1;
385 $course2['newsitems'] = 3;
fbcdb0d7
DNA
386 $course2['startdate'] = 1420092000; // 01/01/2015.
387 $course2['enddate'] = 1422669600; // 01/31/2015.
2a7a0216
JM
388 $course2['numsections'] = 4;
389 $course2['maxbytes'] = 100000;
390 $course2['showreports'] = 1;
391 $course2['visible'] = 0;
392 $course2['hiddensections'] = 0;
393 $course2['groupmode'] = 0;
394 $course2['groupmodeforce'] = 0;
395 $course2['defaultgroupingid'] = 0;
396 $course2['enablecompletion'] = 1;
2a7a0216
JM
397 $course2['completionnotify'] = 1;
398 $course2['lang'] = 'en';
644fcbb6 399 $course2['forcetheme'] = 'bootstrapbase';
0e984d98
MG
400 $course3['fullname'] = 'Test course 3';
401 $course3['shortname'] = 'Testcourse3';
402 $course3['categoryid'] = $category->id;
403 $course3['format'] = 'topics';
404 $course3options = array('numsections' => 8,
405 'hiddensections' => 1,
406 'coursedisplay' => 1);
8d8d4da4 407 $course3['courseformatoptions'] = array();
0e984d98 408 foreach ($course3options as $key => $value) {
8d8d4da4 409 $course3['courseformatoptions'][] = array('name' => $key, 'value' => $value);
0e984d98 410 }
821676f5 411 $courses = array($course1, $course2, $course3);
2a7a0216
JM
412
413 $createdcourses = core_course_external::create_courses($courses);
414
fb695f6e
JM
415 // We need to execute the return values cleaning process to simulate the web service server.
416 $createdcourses = external_api::clean_returnvalue(core_course_external::create_courses_returns(), $createdcourses);
417
2a7a0216 418 // Check that right number of courses were created.
821676f5 419 $this->assertEquals(3, count($createdcourses));
2a7a0216
JM
420
421 // Check that the courses were correctly created.
422 foreach ($createdcourses as $createdcourse) {
850acb35 423 $courseinfo = course_get_format($createdcourse['id'])->get_course();
2a7a0216
JM
424
425 if ($createdcourse['shortname'] == $course2['shortname']) {
850acb35
MG
426 $this->assertEquals($courseinfo->fullname, $course2['fullname']);
427 $this->assertEquals($courseinfo->shortname, $course2['shortname']);
428 $this->assertEquals($courseinfo->category, $course2['categoryid']);
429 $this->assertEquals($courseinfo->idnumber, $course2['idnumber']);
430 $this->assertEquals($courseinfo->summary, $course2['summary']);
431 $this->assertEquals($courseinfo->summaryformat, $course2['summaryformat']);
432 $this->assertEquals($courseinfo->format, $course2['format']);
433 $this->assertEquals($courseinfo->showgrades, $course2['showgrades']);
434 $this->assertEquals($courseinfo->newsitems, $course2['newsitems']);
435 $this->assertEquals($courseinfo->startdate, $course2['startdate']);
fbcdb0d7 436 $this->assertEquals($courseinfo->enddate, $course2['enddate']);
850acb35
MG
437 $this->assertEquals($courseinfo->numsections, $course2['numsections']);
438 $this->assertEquals($courseinfo->maxbytes, $course2['maxbytes']);
439 $this->assertEquals($courseinfo->showreports, $course2['showreports']);
440 $this->assertEquals($courseinfo->visible, $course2['visible']);
441 $this->assertEquals($courseinfo->hiddensections, $course2['hiddensections']);
442 $this->assertEquals($courseinfo->groupmode, $course2['groupmode']);
443 $this->assertEquals($courseinfo->groupmodeforce, $course2['groupmodeforce']);
444 $this->assertEquals($courseinfo->defaultgroupingid, $course2['defaultgroupingid']);
445 $this->assertEquals($courseinfo->completionnotify, $course2['completionnotify']);
446 $this->assertEquals($courseinfo->lang, $course2['lang']);
141e7d87 447 $this->assertEquals($courseinfo->theme, $course2['forcetheme']);
2a7a0216 448
821676f5
JM
449 // We enabled completion at the beginning of the test.
450 $this->assertEquals($courseinfo->enablecompletion, $course2['enablecompletion']);
2a7a0216
JM
451
452 } else if ($createdcourse['shortname'] == $course1['shortname']) {
453 $courseconfig = get_config('moodlecourse');
850acb35
MG
454 $this->assertEquals($courseinfo->fullname, $course1['fullname']);
455 $this->assertEquals($courseinfo->shortname, $course1['shortname']);
456 $this->assertEquals($courseinfo->category, $course1['categoryid']);
457 $this->assertEquals($courseinfo->summaryformat, FORMAT_HTML);
458 $this->assertEquals($courseinfo->format, $courseconfig->format);
459 $this->assertEquals($courseinfo->showgrades, $courseconfig->showgrades);
460 $this->assertEquals($courseinfo->newsitems, $courseconfig->newsitems);
461 $this->assertEquals($courseinfo->maxbytes, $courseconfig->maxbytes);
462 $this->assertEquals($courseinfo->showreports, $courseconfig->showreports);
463 $this->assertEquals($courseinfo->groupmode, $courseconfig->groupmode);
464 $this->assertEquals($courseinfo->groupmodeforce, $courseconfig->groupmodeforce);
465 $this->assertEquals($courseinfo->defaultgroupingid, 0);
0e984d98 466 } else if ($createdcourse['shortname'] == $course3['shortname']) {
850acb35
MG
467 $this->assertEquals($courseinfo->fullname, $course3['fullname']);
468 $this->assertEquals($courseinfo->shortname, $course3['shortname']);
469 $this->assertEquals($courseinfo->category, $course3['categoryid']);
470 $this->assertEquals($courseinfo->format, $course3['format']);
471 $this->assertEquals($courseinfo->hiddensections, $course3options['hiddensections']);
472 $this->assertEquals($courseinfo->numsections, $course3options['numsections']);
473 $this->assertEquals($courseinfo->coursedisplay, $course3options['coursedisplay']);
2a7a0216
JM
474 } else {
475 throw moodle_exception('Unexpected shortname');
476 }
477 }
478
479 // Call without required capability
480 $this->unassignUserCapability('moodle/course:create', $contextid, $roleid);
52f3e060 481 $this->expectException('required_capability_exception');
2a7a0216
JM
482 $createdsubcats = core_course_external::create_courses($courses);
483 }
484
485 /**
486 * Test delete_courses
487 */
488 public function test_delete_courses() {
489 global $DB, $USER;
490
491 $this->resetAfterTest(true);
492
493 // Admin can delete a course.
494 $this->setAdminUser();
495 // Validate_context() will fail as the email is not set by $this->setAdminUser().
0fe86bbd 496 $USER->email = 'emailtopass@example.com';
2a7a0216
JM
497
498 $course1 = self::getDataGenerator()->create_course();
499 $course2 = self::getDataGenerator()->create_course();
500 $course3 = self::getDataGenerator()->create_course();
501
502 // Delete courses.
70f37963
JH
503 $result = core_course_external::delete_courses(array($course1->id, $course2->id));
504 $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
505 // Check for 0 warnings.
506 $this->assertEquals(0, count($result['warnings']));
2a7a0216
JM
507
508 // Check $course 1 and 2 are deleted.
509 $notdeletedcount = $DB->count_records_select('course',
510 'id IN ( ' . $course1->id . ',' . $course2->id . ')');
511 $this->assertEquals(0, $notdeletedcount);
512
70f37963
JH
513 // Try to delete non-existent course.
514 $result = core_course_external::delete_courses(array($course1->id));
515 $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
516 // Check for 1 warnings.
517 $this->assertEquals(1, count($result['warnings']));
518
519 // Try to delete Frontpage course.
520 $result = core_course_external::delete_courses(array(0));
521 $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
522 // Check for 1 warnings.
523 $this->assertEquals(1, count($result['warnings']));
524
525 // Fail when the user has access to course (enrolled) but does not have permission or is not admin.
526 $student1 = self::getDataGenerator()->create_user();
527 $studentrole = $DB->get_record('role', array('shortname' => 'student'));
528 $this->getDataGenerator()->enrol_user($student1->id,
529 $course3->id,
530 $studentrole->id);
531 $this->setUser($student1);
532 $result = core_course_external::delete_courses(array($course3->id));
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
2a7a0216
JM
537 // Fail when the user is not allow to access the course (enrolled) or is not admin.
538 $this->setGuestUser();
52f3e060 539 $this->expectException('require_login_exception');
70f37963
JH
540
541 $result = core_course_external::delete_courses(array($course3->id));
542 $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
2a7a0216
JM
543 }
544
545 /**
546 * Test get_courses
547 */
548 public function test_get_courses () {
549 global $DB;
550
551 $this->resetAfterTest(true);
552
7d6c58bc 553 $generatedcourses = array();
2a7a0216 554 $coursedata['idnumber'] = 'idnumbercourse1';
d889b587
JL
555 // Adding tags here to check that format_string is applied.
556 $coursedata['fullname'] = '<b>Course 1 for PHPunit test</b>';
557 $coursedata['shortname'] = '<b>Course 1 for PHPunit test</b>';
2a7a0216
JM
558 $coursedata['summary'] = 'Course 1 description';
559 $coursedata['summaryformat'] = FORMAT_MOODLE;
560 $course1 = self::getDataGenerator()->create_course($coursedata);
7d6c58bc 561 $generatedcourses[$course1->id] = $course1;
2a7a0216 562 $course2 = self::getDataGenerator()->create_course();
7d6c58bc 563 $generatedcourses[$course2->id] = $course2;
0e984d98 564 $course3 = self::getDataGenerator()->create_course(array('format' => 'topics'));
7d6c58bc 565 $generatedcourses[$course3->id] = $course3;
2a7a0216
JM
566
567 // Set the required capabilities by the external function.
568 $context = context_system::instance();
569 $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
570 $this->assignUserCapability('moodle/course:update',
571 context_course::instance($course1->id)->id, $roleid);
572 $this->assignUserCapability('moodle/course:update',
573 context_course::instance($course2->id)->id, $roleid);
574 $this->assignUserCapability('moodle/course:update',
575 context_course::instance($course3->id)->id, $roleid);
576
577 $courses = core_course_external::get_courses(array('ids' =>
578 array($course1->id, $course2->id)));
579
fb695f6e
JM
580 // We need to execute the return values cleaning process to simulate the web service server.
581 $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
582
2a7a0216
JM
583 // Check we retrieve the good total number of categories.
584 $this->assertEquals(2, count($courses));
585
7d6c58bc 586 foreach ($courses as $course) {
d889b587 587 $coursecontext = context_course::instance($course['id']);
7d6c58bc
JM
588 $dbcourse = $generatedcourses[$course['id']];
589 $this->assertEquals($course['idnumber'], $dbcourse->idnumber);
d889b587
JL
590 $this->assertEquals($course['fullname'], external_format_string($dbcourse->fullname, $coursecontext->id));
591 $this->assertEquals($course['displayname'], external_format_string(get_course_display_name_for_list($dbcourse),
592 $coursecontext->id));
46be1d58
MG
593 // Summary was converted to the HTML format.
594 $this->assertEquals($course['summary'], format_text($dbcourse->summary, FORMAT_MOODLE, array('para' => false)));
7d6c58bc 595 $this->assertEquals($course['summaryformat'], FORMAT_HTML);
d889b587 596 $this->assertEquals($course['shortname'], external_format_string($dbcourse->shortname, $coursecontext->id));
7d6c58bc
JM
597 $this->assertEquals($course['categoryid'], $dbcourse->category);
598 $this->assertEquals($course['format'], $dbcourse->format);
599 $this->assertEquals($course['showgrades'], $dbcourse->showgrades);
600 $this->assertEquals($course['newsitems'], $dbcourse->newsitems);
601 $this->assertEquals($course['startdate'], $dbcourse->startdate);
fbcdb0d7 602 $this->assertEquals($course['enddate'], $dbcourse->enddate);
7d6c58bc
JM
603 $this->assertEquals($course['numsections'], $dbcourse->numsections);
604 $this->assertEquals($course['maxbytes'], $dbcourse->maxbytes);
605 $this->assertEquals($course['showreports'], $dbcourse->showreports);
606 $this->assertEquals($course['visible'], $dbcourse->visible);
607 $this->assertEquals($course['hiddensections'], $dbcourse->hiddensections);
608 $this->assertEquals($course['groupmode'], $dbcourse->groupmode);
609 $this->assertEquals($course['groupmodeforce'], $dbcourse->groupmodeforce);
610 $this->assertEquals($course['defaultgroupingid'], $dbcourse->defaultgroupingid);
611 $this->assertEquals($course['completionnotify'], $dbcourse->completionnotify);
612 $this->assertEquals($course['lang'], $dbcourse->lang);
613 $this->assertEquals($course['forcetheme'], $dbcourse->theme);
7d6c58bc 614 $this->assertEquals($course['enablecompletion'], $dbcourse->enablecompletion);
0e984d98 615 if ($dbcourse->format === 'topics') {
8d8d4da4
MG
616 $this->assertEquals($course['courseformatoptions'], array(
617 array('name' => 'numsections', 'value' => $dbcourse->numsections),
618 array('name' => 'hiddensections', 'value' => $dbcourse->hiddensections),
619 array('name' => 'coursedisplay', 'value' => $dbcourse->coursedisplay),
0e984d98
MG
620 ));
621 }
7d6c58bc 622 }
2a7a0216
JM
623
624 // Get all courses in the DB
625 $courses = core_course_external::get_courses(array());
fb695f6e
JM
626
627 // We need to execute the return values cleaning process to simulate the web service server.
628 $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
629
2a7a0216
JM
630 $this->assertEquals($DB->count_records('course'), count($courses));
631 }
632
740c354f
JL
633 /**
634 * Test search_courses
635 */
636 public function test_search_courses () {
637
74fa9f76 638 global $DB;
740c354f
JL
639
640 $this->resetAfterTest(true);
641 $this->setAdminUser();
642 $generatedcourses = array();
643 $coursedata1['fullname'] = 'FIRST COURSE';
644 $course1 = self::getDataGenerator()->create_course($coursedata1);
645 $coursedata2['fullname'] = 'SECOND COURSE';
646 $course2 = self::getDataGenerator()->create_course($coursedata2);
647 // Search by name.
648 $results = core_course_external::search_courses('search', 'FIRST');
649 $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
650 $this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']);
651 $this->assertCount(1, $results['courses']);
652
653 // Create the forum.
654 $record = new stdClass();
655 $record->introformat = FORMAT_HTML;
656 $record->course = $course2->id;
657 // Set Aggregate type = Average of ratings.
658 $forum = self::getDataGenerator()->create_module('forum', $record);
659
660 // Search by module.
661 $results = core_course_external::search_courses('modulelist', 'forum');
662 $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
663 $this->assertEquals(1, $results['total']);
664
665 // Enable coursetag option.
666 set_config('block_tags_showcoursetags', true);
667 // Add tag 'TAG-LABEL ON SECOND COURSE' to Course2.
74fa9f76
MG
668 core_tag_tag::set_item_tags('core', 'course', $course2->id, context_course::instance($course2->id),
669 array('TAG-LABEL ON SECOND COURSE'));
670 $taginstance = $DB->get_record('tag_instance',
671 array('itemtype' => 'course', 'itemid' => $course2->id), '*', MUST_EXIST);
740c354f
JL
672 // Search by tagid.
673 $results = core_course_external::search_courses('tagid', $taginstance->tagid);
674 $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
675 $this->assertEquals($coursedata2['fullname'], $results['courses'][0]['fullname']);
676
677 // Search by block (use news_items default block).
678 $blockid = $DB->get_field('block', 'id', array('name' => 'news_items'));
679 $results = core_course_external::search_courses('blocklist', $blockid);
680 $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
681 $this->assertEquals(2, $results['total']);
682
683 // Now as a normal user.
684 $user = self::getDataGenerator()->create_user();
935ee1c6
EM
685
686 // Add a 3rd, hidden, course we shouldn't see, even when enrolled as student.
687 $coursedata3['fullname'] = 'HIDDEN COURSE';
688 $coursedata3['visible'] = 0;
689 $course3 = self::getDataGenerator()->create_course($coursedata3);
690 $this->getDataGenerator()->enrol_user($user->id, $course3->id, 'student');
691
692 $this->getDataGenerator()->enrol_user($user->id, $course2->id, 'student');
740c354f
JL
693 $this->setUser($user);
694
695 $results = core_course_external::search_courses('search', 'FIRST');
696 $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
697 $this->assertCount(1, $results['courses']);
698 $this->assertEquals(1, $results['total']);
699 $this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']);
700
935ee1c6
EM
701 // Check that we can see both without the limit to enrolled setting.
702 $results = core_course_external::search_courses('search', 'COURSE', 0, 0, array(), 0);
703 $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
704 $this->assertCount(2, $results['courses']);
705 $this->assertEquals(2, $results['total']);
706
707 // Check that we only see our enrolled course when limiting.
708 $results = core_course_external::search_courses('search', 'COURSE', 0, 0, array(), 1);
709 $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
710 $this->assertCount(1, $results['courses']);
711 $this->assertEquals(1, $results['total']);
712 $this->assertEquals($coursedata2['fullname'], $results['courses'][0]['fullname']);
713
740c354f 714 // Search by block (use news_items default block). Should fail (only admins allowed).
52f3e060 715 $this->expectException('required_capability_exception');
740c354f
JL
716 $results = core_course_external::search_courses('blocklist', $blockid);
717
718 }
719
2a7a0216 720 /**
8a5346a7
JL
721 * Create a course with contents
722 * @return array A list with the course object and course modules objects
2a7a0216 723 */
8a5346a7 724 private function prepare_get_course_contents_test() {
6a1131e2 725 global $DB;
2a7a0216 726 $course = self::getDataGenerator()->create_course();
487bc1b6
JM
727 $forumdescription = 'This is the forum description';
728 $forum = $this->getDataGenerator()->create_module('forum',
8a5346a7 729 array('course' => $course->id, 'intro' => $forumdescription),
487bc1b6 730 array('showdescription' => true));
2a7a0216 731 $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
8a5346a7 732 $data = $this->getDataGenerator()->create_module('data', array('assessed' => 1, 'scale' => 100, 'course' => $course->id));
2a7a0216 733 $datacm = get_coursemodule_from_instance('page', $data->id);
8a5346a7 734 $page = $this->getDataGenerator()->create_module('page', array('course' => $course->id));
2a7a0216 735 $pagecm = get_coursemodule_from_instance('page', $page->id);
487bc1b6
JM
736 $labeldescription = 'This is a very long label to test if more than 50 characters are returned.
737 So bla bla bla bla <b>bold bold bold</b> bla bla bla bla.';
738 $label = $this->getDataGenerator()->create_module('label', array('course' => $course->id,
739 'intro' => $labeldescription));
740 $labelcm = get_coursemodule_from_instance('label', $label->id);
e13c152e 741 $url = $this->getDataGenerator()->create_module('url', array('course' => $course->id,
8a5346a7
JL
742 'name' => 'URL: % & $ ../', 'section' => 2));
743 $urlcm = get_coursemodule_from_instance('url', $url->id);
2a7a0216
JM
744
745 // Set the required capabilities by the external function.
746 $context = context_course::instance($course->id);
747 $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
748 $this->assignUserCapability('moodle/course:update', $context->id, $roleid);
12306a9f 749 $this->assignUserCapability('mod/data:view', $context->id, $roleid);
2a7a0216 750
6a1131e2
JL
751 $conditions = array('course' => $course->id, 'section' => 2);
752 $DB->set_field('course_sections', 'summary', 'Text with iframe <iframe src="https://moodle.org"></iframe>', $conditions);
753 rebuild_course_cache($course->id, true);
754
8a5346a7
JL
755 return array($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm);
756 }
757
758 /**
759 * Test get_course_contents
760 */
761 public function test_get_course_contents() {
762 $this->resetAfterTest(true);
2a7a0216 763
8a5346a7
JL
764 list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
765
766 $sections = core_course_external::get_course_contents($course->id, array());
fb695f6e 767 // We need to execute the return values cleaning process to simulate the web service server.
487bc1b6
JM
768 $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
769
770 // Check that forum and label descriptions are correctly returned.
8a5346a7
JL
771 $firstsection = array_shift($sections);
772 $lastsection = array_pop($sections);
773
487bc1b6
JM
774 $modinfo = get_fast_modinfo($course);
775 $testexecuted = 0;
8a5346a7 776 foreach ($firstsection['modules'] as $module) {
487bc1b6
JM
777 if ($module['id'] == $forumcm->id and $module['modname'] == 'forum') {
778 $cm = $modinfo->cms[$forumcm->id];
73ee2fda 779 $formattedtext = format_text($cm->content, FORMAT_HTML,
487bc1b6
JM
780 array('noclean' => true, 'para' => false, 'filter' => false));
781 $this->assertEquals($formattedtext, $module['description']);
ca4154ce 782 $this->assertEquals($forumcm->instance, $module['instance']);
487bc1b6
JM
783 $testexecuted = $testexecuted + 1;
784 } else if ($module['id'] == $labelcm->id and $module['modname'] == 'label') {
785 $cm = $modinfo->cms[$labelcm->id];
73ee2fda 786 $formattedtext = format_text($cm->content, FORMAT_HTML,
487bc1b6
JM
787 array('noclean' => true, 'para' => false, 'filter' => false));
788 $this->assertEquals($formattedtext, $module['description']);
ca4154ce 789 $this->assertEquals($labelcm->instance, $module['instance']);
487bc1b6
JM
790 $testexecuted = $testexecuted + 1;
791 }
792 }
793 $this->assertEquals(2, $testexecuted);
9df9f1f0 794 $this->assertEquals(0, $firstsection['section']);
fb695f6e 795
8a5346a7
JL
796 // Check that the only return section has the 5 created modules.
797 $this->assertCount(4, $firstsection['modules']);
798 $this->assertCount(1, $lastsection['modules']);
9df9f1f0 799 $this->assertEquals(2, $lastsection['section']);
6a1131e2
JL
800 $this->assertContains('<iframe', $lastsection['summary']);
801 $this->assertContains('</iframe>', $lastsection['summary']);
8a5346a7
JL
802
803 try {
804 $sections = core_course_external::get_course_contents($course->id,
805 array(array("name" => "invalid", "value" => 1)));
806 $this->fail('Exception expected due to invalid option.');
807 } catch (moodle_exception $e) {
808 $this->assertEquals('errorinvalidparam', $e->errorcode);
809 }
810 }
811
812
813 /**
814 * Test get_course_contents excluding modules
815 */
816 public function test_get_course_contents_excluding_modules() {
817 $this->resetAfterTest(true);
818
819 list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
820
821 // Test exclude modules.
822 $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludemodules", "value" => 1)));
823
824 // We need to execute the return values cleaning process to simulate the web service server.
825 $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
826
827 $firstsection = array_shift($sections);
828 $lastsection = array_pop($sections);
829
830 $this->assertEmpty($firstsection['modules']);
831 $this->assertEmpty($lastsection['modules']);
832 }
833
834 /**
835 * Test get_course_contents excluding contents
836 */
837 public function test_get_course_contents_excluding_contents() {
838 $this->resetAfterTest(true);
839
840 list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
841
842 // Test exclude modules.
843 $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludecontents", "value" => 1)));
844
845 // We need to execute the return values cleaning process to simulate the web service server.
846 $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
847
848 foreach ($sections as $section) {
849 foreach ($section['modules'] as $module) {
850 // Only resources return contents.
851 if (isset($module['contents'])) {
852 $this->assertEmpty($module['contents']);
853 }
854 }
855 }
856 }
857
858 /**
859 * Test get_course_contents filtering by section number
860 */
861 public function test_get_course_contents_section_number() {
862 $this->resetAfterTest(true);
863
864 list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
865
866 // Test exclude modules.
867 $sections = core_course_external::get_course_contents($course->id, array(array("name" => "sectionnumber", "value" => 0)));
868
869 // We need to execute the return values cleaning process to simulate the web service server.
870 $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
871
872 $this->assertCount(1, $sections);
873 $this->assertCount(4, $sections[0]['modules']);
874 }
875
876 /**
877 * Test get_course_contents filtering by cmid
878 */
879 public function test_get_course_contents_cmid() {
880 $this->resetAfterTest(true);
881
882 list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
883
884 // Test exclude modules.
885 $sections = core_course_external::get_course_contents($course->id, array(array("name" => "cmid", "value" => $forumcm->id)));
886
887 // We need to execute the return values cleaning process to simulate the web service server.
888 $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
889
890 $this->assertCount(2, $sections);
891 $this->assertCount(1, $sections[0]['modules']);
892 $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
893 }
894
895
896 /**
897 * Test get_course_contents filtering by cmid and section
898 */
899 public function test_get_course_contents_section_cmid() {
900 $this->resetAfterTest(true);
901
902 list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
903
904 // Test exclude modules.
905 $sections = core_course_external::get_course_contents($course->id, array(
906 array("name" => "cmid", "value" => $forumcm->id),
907 array("name" => "sectionnumber", "value" => 0)
908 ));
909
910 // We need to execute the return values cleaning process to simulate the web service server.
911 $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
912
913 $this->assertCount(1, $sections);
914 $this->assertCount(1, $sections[0]['modules']);
915 $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
916 }
917
918 /**
919 * Test get_course_contents filtering by modname
920 */
921 public function test_get_course_contents_modname() {
922 $this->resetAfterTest(true);
923
924 list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
925
926 // Test exclude modules.
927 $sections = core_course_external::get_course_contents($course->id, array(array("name" => "modname", "value" => "forum")));
928
929 // We need to execute the return values cleaning process to simulate the web service server.
930 $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
931
932 $this->assertCount(2, $sections);
933 $this->assertCount(1, $sections[0]['modules']);
934 $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
935 }
936
937 /**
938 * Test get_course_contents filtering by modname
939 */
940 public function test_get_course_contents_modid() {
941 $this->resetAfterTest(true);
942
943 list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
944
945 // Test exclude modules.
946 $sections = core_course_external::get_course_contents($course->id, array(
947 array("name" => "modname", "value" => "page"),
948 array("name" => "modid", "value" => $pagecm->instance),
949 ));
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
954 $this->assertCount(2, $sections);
955 $this->assertCount(1, $sections[0]['modules']);
956 $this->assertEquals("page", $sections[0]['modules'][0]["modname"]);
957 $this->assertEquals($pagecm->instance, $sections[0]['modules'][0]["instance"]);
2a7a0216
JM
958 }
959
960 /**
961 * Test duplicate_course
962 */
963 public function test_duplicate_course() {
964 $this->resetAfterTest(true);
965
966 // Create one course with three modules.
967 $course = self::getDataGenerator()->create_course();
968 $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course->id));
969 $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
970 $forumcontext = context_module::instance($forum->cmid);
971 $data = $this->getDataGenerator()->create_module('data', array('assessed'=>1, 'scale'=>100, 'course'=>$course->id));
972 $datacontext = context_module::instance($data->cmid);
973 $datacm = get_coursemodule_from_instance('page', $data->id);
974 $page = $this->getDataGenerator()->create_module('page', array('course'=>$course->id));
975 $pagecontext = context_module::instance($page->cmid);
976 $pagecm = get_coursemodule_from_instance('page', $page->id);
977
978 // Set the required capabilities by the external function.
979 $coursecontext = context_course::instance($course->id);
980 $categorycontext = context_coursecat::instance($course->category);
981 $roleid = $this->assignUserCapability('moodle/course:create', $categorycontext->id);
982 $this->assignUserCapability('moodle/course:view', $categorycontext->id, $roleid);
983 $this->assignUserCapability('moodle/restore:restorecourse', $categorycontext->id, $roleid);
984 $this->assignUserCapability('moodle/backup:backupcourse', $coursecontext->id, $roleid);
985 $this->assignUserCapability('moodle/backup:configure', $coursecontext->id, $roleid);
986 // Optional capabilities to copy user data.
987 $this->assignUserCapability('moodle/backup:userinfo', $coursecontext->id, $roleid);
988 $this->assignUserCapability('moodle/restore:userinfo', $categorycontext->id, $roleid);
989
990 $newcourse['fullname'] = 'Course duplicate';
991 $newcourse['shortname'] = 'courseduplicate';
992 $newcourse['categoryid'] = $course->category;
993 $newcourse['visible'] = true;
994 $newcourse['options'][] = array('name' => 'users', 'value' => true);
995
996 $duplicate = core_course_external::duplicate_course($course->id, $newcourse['fullname'],
997 $newcourse['shortname'], $newcourse['categoryid'], $newcourse['visible'], $newcourse['options']);
998
fb695f6e
JM
999 // We need to execute the return values cleaning process to simulate the web service server.
1000 $duplicate = external_api::clean_returnvalue(core_course_external::duplicate_course_returns(), $duplicate);
1001
2a7a0216
JM
1002 // Check that the course has been duplicated.
1003 $this->assertEquals($newcourse['shortname'], $duplicate['shortname']);
1004 }
791723c3
RT
1005
1006 /**
1007 * Test update_courses
1008 */
1009 public function test_update_courses() {
a182f88f
EL
1010 global $DB, $CFG, $USER, $COURSE;
1011
1012 // Get current $COURSE to be able to restore it later (defaults to $SITE). We need this
1013 // trick because we are both updating and getting (for testing) course information
1014 // in the same request and core_course_external::update_courses()
1015 // is overwriting $COURSE all over the time with OLD values, so later
1016 // use of get_course() fetches those OLD values instead of the updated ones.
1017 // See MDL-39723 for more info.
1018 $origcourse = clone($COURSE);
791723c3
RT
1019
1020 $this->resetAfterTest(true);
1021
1022 // Set the required capabilities by the external function.
1023 $contextid = context_system::instance()->id;
1024 $roleid = $this->assignUserCapability('moodle/course:update', $contextid);
1025 $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1026 $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1027 $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1028 $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1029 $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1030 $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
1031 $this->assignUserCapability('moodle/course:viewhiddencourses', $contextid, $roleid);
1032
1033 // Create category and course.
1034 $category1 = self::getDataGenerator()->create_category();
1035 $category2 = self::getDataGenerator()->create_category();
1036 $originalcourse1 = self::getDataGenerator()->create_course();
1037 self::getDataGenerator()->enrol_user($USER->id, $originalcourse1->id, $roleid);
1038 $originalcourse2 = self::getDataGenerator()->create_course();
1039 self::getDataGenerator()->enrol_user($USER->id, $originalcourse2->id, $roleid);
1040
1041 // Course values to be updated.
1042 $course1['id'] = $originalcourse1->id;
1043 $course1['fullname'] = 'Updated test course 1';
1044 $course1['shortname'] = 'Udestedtestcourse1';
1045 $course1['categoryid'] = $category1->id;
1046 $course2['id'] = $originalcourse2->id;
1047 $course2['fullname'] = 'Updated test course 2';
1048 $course2['shortname'] = 'Updestedtestcourse2';
1049 $course2['categoryid'] = $category2->id;
1050 $course2['idnumber'] = 'Updatedidnumber2';
1051 $course2['summary'] = 'Updaated description for course 2';
1052 $course2['summaryformat'] = FORMAT_HTML;
1053 $course2['format'] = 'topics';
1054 $course2['showgrades'] = 1;
1055 $course2['newsitems'] = 3;
1056 $course2['startdate'] = 1420092000; // 01/01/2015.
fbcdb0d7 1057 $course2['enddate'] = 1422669600; // 01/31/2015.
791723c3
RT
1058 $course2['numsections'] = 4;
1059 $course2['maxbytes'] = 100000;
1060 $course2['showreports'] = 1;
1061 $course2['visible'] = 0;
1062 $course2['hiddensections'] = 0;
1063 $course2['groupmode'] = 0;
1064 $course2['groupmodeforce'] = 0;
1065 $course2['defaultgroupingid'] = 0;
1066 $course2['enablecompletion'] = 1;
1067 $course2['lang'] = 'en';
644fcbb6 1068 $course2['forcetheme'] = 'bootstrapbase';
791723c3
RT
1069 $courses = array($course1, $course2);
1070
1071 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1072 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1073 $updatedcoursewarnings);
a182f88f 1074 $COURSE = $origcourse; // Restore $COURSE. Instead of using the OLD one set by the previous line.
791723c3
RT
1075
1076 // Check that right number of courses were created.
1077 $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1078
1079 // Check that the courses were correctly created.
1080 foreach ($courses as $course) {
1081 $courseinfo = course_get_format($course['id'])->get_course();
1082 if ($course['id'] == $course2['id']) {
1083 $this->assertEquals($course2['fullname'], $courseinfo->fullname);
1084 $this->assertEquals($course2['shortname'], $courseinfo->shortname);
1085 $this->assertEquals($course2['categoryid'], $courseinfo->category);
1086 $this->assertEquals($course2['idnumber'], $courseinfo->idnumber);
1087 $this->assertEquals($course2['summary'], $courseinfo->summary);
1088 $this->assertEquals($course2['summaryformat'], $courseinfo->summaryformat);
1089 $this->assertEquals($course2['format'], $courseinfo->format);
1090 $this->assertEquals($course2['showgrades'], $courseinfo->showgrades);
1091 $this->assertEquals($course2['newsitems'], $courseinfo->newsitems);
1092 $this->assertEquals($course2['startdate'], $courseinfo->startdate);
fbcdb0d7 1093 $this->assertEquals($course2['enddate'], $courseinfo->enddate);
791723c3
RT
1094 $this->assertEquals($course2['numsections'], $courseinfo->numsections);
1095 $this->assertEquals($course2['maxbytes'], $courseinfo->maxbytes);
1096 $this->assertEquals($course2['showreports'], $courseinfo->showreports);
1097 $this->assertEquals($course2['visible'], $courseinfo->visible);
1098 $this->assertEquals($course2['hiddensections'], $courseinfo->hiddensections);
1099 $this->assertEquals($course2['groupmode'], $courseinfo->groupmode);
1100 $this->assertEquals($course2['groupmodeforce'], $courseinfo->groupmodeforce);
1101 $this->assertEquals($course2['defaultgroupingid'], $courseinfo->defaultgroupingid);
1102 $this->assertEquals($course2['lang'], $courseinfo->lang);
1103
1104 if (!empty($CFG->allowcoursethemes)) {
1105 $this->assertEquals($course2['forcetheme'], $courseinfo->theme);
1106 }
1107
8be9cffb 1108 $this->assertEquals($course2['enablecompletion'], $courseinfo->enablecompletion);
791723c3
RT
1109 } else if ($course['id'] == $course1['id']) {
1110 $this->assertEquals($course1['fullname'], $courseinfo->fullname);
1111 $this->assertEquals($course1['shortname'], $courseinfo->shortname);
1112 $this->assertEquals($course1['categoryid'], $courseinfo->category);
1113 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1114 $this->assertEquals('topics', $courseinfo->format);
1115 $this->assertEquals(5, $courseinfo->numsections);
1116 $this->assertEquals(0, $courseinfo->newsitems);
1117 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1118 } else {
1119 throw moodle_exception('Unexpected shortname');
1120 }
1121 }
1122
1123 $courses = array($course1);
1124 // Try update course without update capability.
1125 $user = self::getDataGenerator()->create_user();
1126 $this->setUser($user);
1127 $this->unassignUserCapability('moodle/course:update', $contextid, $roleid);
1128 self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1129 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1130 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1131 $updatedcoursewarnings);
791723c3
RT
1132 $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1133
1134 // Try update course category without capability.
1135 $this->assignUserCapability('moodle/course:update', $contextid, $roleid);
1136 $this->unassignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1137 $user = self::getDataGenerator()->create_user();
1138 $this->setUser($user);
1139 self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1140 $course1['categoryid'] = $category2->id;
1141 $courses = array($course1);
1142 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1143 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1144 $updatedcoursewarnings);
791723c3
RT
1145 $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1146
1147 // Try update course fullname without capability.
1148 $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1149 $this->unassignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1150 $user = self::getDataGenerator()->create_user();
1151 $this->setUser($user);
1152 self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1153 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1154 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1155 $updatedcoursewarnings);
791723c3
RT
1156 $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1157 $course1['fullname'] = 'Testing fullname without permission';
1158 $courses = array($course1);
1159 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1160 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1161 $updatedcoursewarnings);
791723c3
RT
1162 $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1163
1164 // Try update course shortname without capability.
1165 $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1166 $this->unassignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1167 $user = self::getDataGenerator()->create_user();
1168 $this->setUser($user);
1169 self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1170 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1171 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1172 $updatedcoursewarnings);
791723c3
RT
1173 $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1174 $course1['shortname'] = 'Testing shortname without permission';
1175 $courses = array($course1);
1176 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1177 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1178 $updatedcoursewarnings);
791723c3
RT
1179 $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1180
1181 // Try update course idnumber without capability.
1182 $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1183 $this->unassignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1184 $user = self::getDataGenerator()->create_user();
1185 $this->setUser($user);
1186 self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1187 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1188 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1189 $updatedcoursewarnings);
791723c3
RT
1190 $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1191 $course1['idnumber'] = 'NEWIDNUMBER';
1192 $courses = array($course1);
1193 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1194 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1195 $updatedcoursewarnings);
791723c3
RT
1196 $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1197
1198 // Try update course summary without capability.
1199 $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1200 $this->unassignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1201 $user = self::getDataGenerator()->create_user();
1202 $this->setUser($user);
1203 self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
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(0, count($updatedcoursewarnings['warnings']));
1208 $course1['summary'] = 'New summary';
1209 $courses = array($course1);
1210 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1211 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1212 $updatedcoursewarnings);
791723c3
RT
1213 $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1214
1215 // Try update course with invalid summary format.
1216 $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1217 $user = self::getDataGenerator()->create_user();
1218 $this->setUser($user);
1219 self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1220 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1221 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1222 $updatedcoursewarnings);
791723c3
RT
1223 $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1224 $course1['summaryformat'] = 10;
1225 $courses = array($course1);
1226 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1227 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1228 $updatedcoursewarnings);
791723c3
RT
1229 $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1230
1231 // Try update course visibility without capability.
1232 $this->unassignUserCapability('moodle/course:visibility', $contextid, $roleid);
1233 $user = self::getDataGenerator()->create_user();
1234 $this->setUser($user);
1235 self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1236 $course1['summaryformat'] = FORMAT_MOODLE;
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(0, count($updatedcoursewarnings['warnings']));
1242 $course1['visible'] = 0;
1243 $courses = array($course1);
1244 $updatedcoursewarnings = core_course_external::update_courses($courses);
bdf9f4d4
JL
1245 $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1246 $updatedcoursewarnings);
791723c3
RT
1247 $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1248 }
05fc7ccc 1249
79949c1b
MN
1250 /**
1251 * Test delete course_module.
1252 */
1253 public function test_delete_modules() {
1254 global $DB;
1255
1256 // Ensure we reset the data after this test.
1257 $this->resetAfterTest(true);
1258
1259 // Create a user.
1260 $user = self::getDataGenerator()->create_user();
1261
1262 // Set the tests to run as the user.
1263 self::setUser($user);
1264
1265 // Create a course to add the modules.
1266 $course = self::getDataGenerator()->create_course();
1267
1268 // Create two test modules.
1269 $record = new stdClass();
1270 $record->course = $course->id;
1271 $module1 = self::getDataGenerator()->create_module('forum', $record);
40cb4879 1272 $module2 = self::getDataGenerator()->create_module('assign', $record);
79949c1b
MN
1273
1274 // Check the forum was correctly created.
1275 $this->assertEquals(1, $DB->count_records('forum', array('id' => $module1->id)));
1276
1277 // Check the assignment was correctly created.
40cb4879 1278 $this->assertEquals(1, $DB->count_records('assign', array('id' => $module2->id)));
79949c1b
MN
1279
1280 // Check data exists in the course modules table.
1281 $this->assertEquals(2, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1282 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1283
1284 // Enrol the user in the course.
1285 $enrol = enrol_get_plugin('manual');
1286 $enrolinstances = enrol_get_instances($course->id, true);
1287 foreach ($enrolinstances as $courseenrolinstance) {
1288 if ($courseenrolinstance->enrol == "manual") {
1289 $instance = $courseenrolinstance;
1290 break;
1291 }
1292 }
1293 $enrol->enrol_user($instance, $user->id);
1294
1295 // Assign capabilities to delete module 1.
1296 $modcontext = context_module::instance($module1->cmid);
1297 $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id);
1298
1299 // Assign capabilities to delete module 2.
1300 $modcontext = context_module::instance($module2->cmid);
1301 $newrole = create_role('Role 2', 'role2', 'Role 2 description');
1302 $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id, $newrole);
1303
1304 // Deleting these module instances.
1305 core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1306
1307 // Check the forum was deleted.
1308 $this->assertEquals(0, $DB->count_records('forum', array('id' => $module1->id)));
1309
1310 // Check the assignment was deleted.
40cb4879 1311 $this->assertEquals(0, $DB->count_records('assign', array('id' => $module2->id)));
79949c1b
MN
1312
1313 // Check we retrieve no data in the course modules table.
1314 $this->assertEquals(0, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1315 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1316
1317 // Call with non-existent course module id and ensure exception thrown.
1318 try {
1319 core_course_external::delete_modules(array('1337'));
1320 $this->fail('Exception expected due to missing course module.');
1321 } catch (dml_missing_record_exception $e) {
affdc3b7 1322 $this->assertEquals('invalidcoursemodule', $e->errorcode);
79949c1b
MN
1323 }
1324
1325 // Create two modules.
1326 $module1 = self::getDataGenerator()->create_module('forum', $record);
40cb4879 1327 $module2 = self::getDataGenerator()->create_module('assign', $record);
79949c1b
MN
1328
1329 // Since these modules were recreated the user will not have capabilities
1330 // to delete them, ensure exception is thrown if they try.
1331 try {
1332 core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1333 $this->fail('Exception expected due to missing capability.');
1334 } catch (moodle_exception $e) {
1335 $this->assertEquals('nopermissions', $e->errorcode);
1336 }
1337
1338 // Unenrol user from the course.
1339 $enrol->unenrol_user($instance, $user->id);
1340
1341 // Try and delete modules from the course the user was unenrolled in, make sure exception thrown.
1342 try {
1343 core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1344 $this->fail('Exception expected due to being unenrolled from the course.');
1345 } catch (moodle_exception $e) {
1346 $this->assertEquals('requireloginerror', $e->errorcode);
1347 }
1348 }
fce10644
DP
1349
1350 /**
1351 * Test import_course into an empty course
1352 */
1353 public function test_import_course_empty() {
1354 global $USER;
1355
1356 $this->resetAfterTest(true);
1357
1358 $course1 = self::getDataGenerator()->create_course();
1359 $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course1->id, 'name' => 'Forum test'));
1360 $page = $this->getDataGenerator()->create_module('page', array('course' => $course1->id, 'name' => 'Page test'));
1361
1362 $course2 = self::getDataGenerator()->create_course();
1363
1364 $course1cms = get_fast_modinfo($course1->id)->get_cms();
1365 $course2cms = get_fast_modinfo($course2->id)->get_cms();
1366
1367 // Verify the state of the courses before we do the import.
1368 $this->assertCount(2, $course1cms);
1369 $this->assertEmpty($course2cms);
1370
1371 // Setup the user to run the operation (ugly hack because validate_context() will
1372 // fail as the email is not set by $this->setAdminUser()).
1373 $this->setAdminUser();
0fe86bbd 1374 $USER->email = 'emailtopass@example.com';
fce10644
DP
1375
1376 // Import from course1 to course2.
1377 core_course_external::import_course($course1->id, $course2->id, 0);
1378
1379 // Verify that now we have two modules in both courses.
1380 $course1cms = get_fast_modinfo($course1->id)->get_cms();
1381 $course2cms = get_fast_modinfo($course2->id)->get_cms();
1382 $this->assertCount(2, $course1cms);
1383 $this->assertCount(2, $course2cms);
1384
1385 // Verify that the names transfered across correctly.
1386 foreach ($course2cms as $cm) {
1387 if ($cm->modname === 'page') {
1388 $this->assertEquals($cm->name, $page->name);
1389 } else if ($cm->modname === 'forum') {
1390 $this->assertEquals($cm->name, $forum->name);
1391 } else {
1392 $this->fail('Unknown CM found.');
1393 }
1394 }
fce10644
DP
1395 }
1396
1397 /**
1398 * Test import_course into an filled course
1399 */
1400 public function test_import_course_filled() {
1401 global $USER;
1402
1403 $this->resetAfterTest(true);
1404
1405 // Add forum and page to course1.
1406 $course1 = self::getDataGenerator()->create_course();
1407 $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1408 $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1409
1410 // Add quiz to course 2.
1411 $course2 = self::getDataGenerator()->create_course();
1412 $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1413
1414 $course1cms = get_fast_modinfo($course1->id)->get_cms();
1415 $course2cms = get_fast_modinfo($course2->id)->get_cms();
1416
1417 // Verify the state of the courses before we do the import.
1418 $this->assertCount(2, $course1cms);
1419 $this->assertCount(1, $course2cms);
1420
1421 // Setup the user to run the operation (ugly hack because validate_context() will
1422 // fail as the email is not set by $this->setAdminUser()).
1423 $this->setAdminUser();
0fe86bbd 1424 $USER->email = 'emailtopass@example.com';
fce10644
DP
1425
1426 // Import from course1 to course2 without deleting content.
1427 core_course_external::import_course($course1->id, $course2->id, 0);
1428
1429 $course2cms = get_fast_modinfo($course2->id)->get_cms();
1430
1431 // Verify that now we have three modules in course2.
1432 $this->assertCount(3, $course2cms);
1433
1434 // Verify that the names transfered across correctly.
1435 foreach ($course2cms as $cm) {
1436 if ($cm->modname === 'page') {
1437 $this->assertEquals($cm->name, $page->name);
1438 } else if ($cm->modname === 'forum') {
1439 $this->assertEquals($cm->name, $forum->name);
1440 } else if ($cm->modname === 'quiz') {
1441 $this->assertEquals($cm->name, $quiz->name);
1442 } else {
1443 $this->fail('Unknown CM found.');
1444 }
1445 }
fce10644
DP
1446 }
1447
1448 /**
1449 * Test import_course with only blocks set to backup
1450 */
1451 public function test_import_course_blocksonly() {
1452 global $USER, $DB;
1453
1454 $this->resetAfterTest(true);
1455
1456 // Add forum and page to course1.
1457 $course1 = self::getDataGenerator()->create_course();
1458 $course1ctx = context_course::instance($course1->id);
1459 $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1460 $block = $this->getDataGenerator()->create_block('online_users', array('parentcontextid' => $course1ctx->id));
1461
1462 $course2 = self::getDataGenerator()->create_course();
1463 $course2ctx = context_course::instance($course2->id);
1464 $initialblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1465 $initialcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1466
1467 // Setup the user to run the operation (ugly hack because validate_context() will
1468 // fail as the email is not set by $this->setAdminUser()).
1469 $this->setAdminUser();
0fe86bbd 1470 $USER->email = 'emailtopass@example.com';
fce10644
DP
1471
1472 // Import from course1 to course2 without deleting content, but excluding
1473 // activities.
1474 $options = array(
1475 array('name' => 'activities', 'value' => 0),
1476 array('name' => 'blocks', 'value' => 1),
1477 array('name' => 'filters', 'value' => 0),
1478 );
1479
1480 core_course_external::import_course($course1->id, $course2->id, 0, $options);
1481
1482 $newcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1483 $newblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1484 // Check that course modules haven't changed, but that blocks have.
1485 $this->assertEquals($initialcmcount, $newcmcount);
1486 $this->assertEquals(($initialblockcount + 1), $newblockcount);
fce10644
DP
1487 }
1488
1489 /**
1490 * Test import_course into an filled course, deleting content.
1491 */
1492 public function test_import_course_deletecontent() {
1493 global $USER;
1494 $this->resetAfterTest(true);
1495
1496 // Add forum and page to course1.
1497 $course1 = self::getDataGenerator()->create_course();
1498 $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1499 $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1500
1501 // Add quiz to course 2.
1502 $course2 = self::getDataGenerator()->create_course();
1503 $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1504
1505 $course1cms = get_fast_modinfo($course1->id)->get_cms();
1506 $course2cms = get_fast_modinfo($course2->id)->get_cms();
1507
1508 // Verify the state of the courses before we do the import.
1509 $this->assertCount(2, $course1cms);
1510 $this->assertCount(1, $course2cms);
1511
1512 // Setup the user to run the operation (ugly hack because validate_context() will
1513 // fail as the email is not set by $this->setAdminUser()).
1514 $this->setAdminUser();
0fe86bbd 1515 $USER->email = 'emailtopass@example.com';
fce10644
DP
1516
1517 // Import from course1 to course2, deleting content.
1518 core_course_external::import_course($course1->id, $course2->id, 1);
1519
1520 $course2cms = get_fast_modinfo($course2->id)->get_cms();
1521
1522 // Verify that now we have two modules in course2.
1523 $this->assertCount(2, $course2cms);
1524
1525 // Verify that the course only contains the imported modules.
1526 foreach ($course2cms as $cm) {
1527 if ($cm->modname === 'page') {
1528 $this->assertEquals($cm->name, $page->name);
1529 } else if ($cm->modname === 'forum') {
1530 $this->assertEquals($cm->name, $forum->name);
1531 } else {
1532 $this->fail('Unknown CM found: '.$cm->name);
1533 }
1534 }
fce10644
DP
1535 }
1536
1537 /**
1538 * Ensure import_course handles incorrect deletecontent option correctly.
1539 */
1540 public function test_import_course_invalid_deletecontent_option() {
1541 $this->resetAfterTest(true);
1542
1543 $course1 = self::getDataGenerator()->create_course();
1544 $course2 = self::getDataGenerator()->create_course();
1545
52f3e060
RT
1546 $this->expectException('moodle_exception');
1547 $this->expectExceptionMessage(get_string('invalidextparam', 'webservice', -1));
fce10644
DP
1548 // Import from course1 to course2, with invalid option
1549 core_course_external::import_course($course1->id, $course2->id, -1);;
1550 }
e81f67ca
JL
1551
1552 /**
1553 * Test view_course function
1554 */
1555 public function test_view_course() {
1556
1557 $this->resetAfterTest();
1558
1559 // Course without sections.
1560 $course = $this->getDataGenerator()->create_course(array('numsections' => 5), array('createsections' => true));
1561 $this->setAdminUser();
1562
1563 // Redirect events to the sink, so we can recover them later.
1564 $sink = $this->redirectEvents();
1565
bdf9f4d4
JL
1566 $result = core_course_external::view_course($course->id, 1);
1567 $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
e81f67ca
JL
1568 $events = $sink->get_events();
1569 $event = reset($events);
1570
1571 // Check the event details are correct.
1572 $this->assertInstanceOf('\core\event\course_viewed', $event);
1573 $this->assertEquals(context_course::instance($course->id), $event->get_context());
1574 $this->assertEquals(1, $event->other['coursesectionnumber']);
1575
bdf9f4d4
JL
1576 $result = core_course_external::view_course($course->id);
1577 $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
e81f67ca
JL
1578 $events = $sink->get_events();
1579 $event = array_pop($events);
1580 $sink->close();
1581
1582 // Check the event details are correct.
1583 $this->assertInstanceOf('\core\event\course_viewed', $event);
1584 $this->assertEquals(context_course::instance($course->id), $event->get_context());
1585 $this->assertEmpty($event->other);
1586
1587 }
c5158499
JL
1588
1589 /**
1590 * Test get_course_module
1591 */
1592 public function test_get_course_module() {
1593 global $DB;
1594
1595 $this->resetAfterTest(true);
1596
1597 $this->setAdminUser();
1598 $course = self::getDataGenerator()->create_course();
1599 $record = array(
1600 'course' => $course->id,
796876b0 1601 'name' => 'First Assignment'
c5158499
JL
1602 );
1603 $options = array(
1604 'idnumber' => 'ABC',
1605 'visible' => 0
1606 );
1607 // Hidden activity.
796876b0 1608 $assign = self::getDataGenerator()->create_module('assign', $record, $options);
c5158499
JL
1609
1610 // Test admin user can see the complete hidden activity.
796876b0 1611 $result = core_course_external::get_course_module($assign->cmid);
c5158499
JL
1612 $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
1613
1614 $this->assertCount(0, $result['warnings']);
1615 // Test we retrieve all the fields.
796876b0 1616 $this->assertCount(26, $result['cm']);
c5158499
JL
1617 $this->assertEquals($record['name'], $result['cm']['name']);
1618 $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
796876b0
JL
1619 $this->assertEquals(100, $result['cm']['grade']);
1620 $this->assertEquals(0.0, $result['cm']['gradepass']);
1621 $this->assertEquals('submissions', $result['cm']['advancedgrading'][0]['area']);
1622 $this->assertEmpty($result['cm']['advancedgrading'][0]['method']);
1623 $this->assertArrayNotHasKey('outcomes', $result['cm']);
c5158499
JL
1624
1625 $student = $this->getDataGenerator()->create_user();
1626 $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1627
1628 self::getDataGenerator()->enrol_user($student->id, $course->id, $studentrole->id);
1629 $this->setUser($student);
1630
1631 // The user shouldn't be able to see the activity.
1632 try {
796876b0 1633 core_course_external::get_course_module($assign->cmid);
c5158499
JL
1634 $this->fail('Exception expected due to invalid permissions.');
1635 } catch (moodle_exception $e) {
1636 $this->assertEquals('requireloginerror', $e->errorcode);
1637 }
1638
1639 // Make module visible.
796876b0 1640 set_coursemodule_visible($assign->cmid, 1);
c5158499
JL
1641
1642 // Test student user.
796876b0 1643 $result = core_course_external::get_course_module($assign->cmid);
c5158499
JL
1644 $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
1645
1646 $this->assertCount(0, $result['warnings']);
1647 // Test we retrieve only the few files we can see.
1648 $this->assertCount(11, $result['cm']);
796876b0 1649 $this->assertEquals($assign->cmid, $result['cm']['id']);
c5158499 1650 $this->assertEquals($course->id, $result['cm']['course']);
796876b0
JL
1651 $this->assertEquals('assign', $result['cm']['modname']);
1652 $this->assertEquals($assign->id, $result['cm']['instance']);
c5158499
JL
1653
1654 }
13bb6819
JL
1655
1656 /**
1657 * Test get_course_module_by_instance
1658 */
1659 public function test_get_course_module_by_instance() {
1660 global $DB;
1661
1662 $this->resetAfterTest(true);
1663
1664 $this->setAdminUser();
1665 $course = self::getDataGenerator()->create_course();
1666 $record = array(
1667 'course' => $course->id,
1668 'name' => 'First Chat'
1669 );
1670 $options = array(
1671 'idnumber' => 'ABC',
1672 'visible' => 0
1673 );
1674 // Hidden activity.
1675 $chat = self::getDataGenerator()->create_module('chat', $record, $options);
1676
1677 // Test admin user can see the complete hidden activity.
1678 $result = core_course_external::get_course_module_by_instance('chat', $chat->id);
1679 $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
1680
1681 $this->assertCount(0, $result['warnings']);
1682 // Test we retrieve all the fields.
1683 $this->assertCount(22, $result['cm']);
1684 $this->assertEquals($record['name'], $result['cm']['name']);
1685 $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
1686
1687 $student = $this->getDataGenerator()->create_user();
1688 $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1689
1690 self::getDataGenerator()->enrol_user($student->id, $course->id, $studentrole->id);
1691 $this->setUser($student);
1692
1693 // The user shouldn't be able to see the activity.
1694 try {
1695 core_course_external::get_course_module_by_instance('chat', $chat->id);
1696 $this->fail('Exception expected due to invalid permissions.');
1697 } catch (moodle_exception $e) {
1698 $this->assertEquals('requireloginerror', $e->errorcode);
1699 }
1700
1701 // Make module visible.
1702 set_coursemodule_visible($chat->cmid, 1);
1703
1704 // Test student user.
1705 $result = core_course_external::get_course_module_by_instance('chat', $chat->id);
1706 $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
1707
1708 $this->assertCount(0, $result['warnings']);
1709 // Test we retrieve only the few files we can see.
1710 $this->assertCount(11, $result['cm']);
1711 $this->assertEquals($chat->cmid, $result['cm']['id']);
1712 $this->assertEquals($course->id, $result['cm']['course']);
1713 $this->assertEquals('chat', $result['cm']['modname']);
1714 $this->assertEquals($chat->id, $result['cm']['instance']);
1715
1716 // Try with an invalid module name.
1717 try {
1718 core_course_external::get_course_module_by_instance('abc', $chat->id);
1719 $this->fail('Exception expected due to invalid module name.');
1720 } catch (dml_read_exception $e) {
1721 $this->assertEquals('dmlreadexception', $e->errorcode);
1722 }
1723
1724 }
7c4e686f
JL
1725
1726 /**
1727 * Test get_activities_overview
1728 */
1729 public function test_get_activities_overview() {
1730 global $USER;
1731
1732 $this->resetAfterTest();
1733 $course1 = self::getDataGenerator()->create_course();
1734 $course2 = self::getDataGenerator()->create_course();
1735
1736 // Create a viewer user.
1737 $viewer = self::getDataGenerator()->create_user((object) array('trackforums' => 1));
1738 $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
1739 $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
1740
1741 // Create two forums - one in each course.
1742 $record = new stdClass();
1743 $record->course = $course1->id;
1744 $forum1 = self::getDataGenerator()->create_module('forum', (object) array('course' => $course1->id));
1745 $forum2 = self::getDataGenerator()->create_module('forum', (object) array('course' => $course2->id));
1746
1747 $this->setAdminUser();
1748 // A standard post in the forum.
1749 $record = new stdClass();
1750 $record->course = $course1->id;
1751 $record->userid = $USER->id;
1752 $record->forum = $forum1->id;
1753 $this->getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
1754
1755 $this->setUser($viewer->id);
1756 $courses = array($course1->id , $course2->id);
1757
1758 $result = core_course_external::get_activities_overview($courses);
1759 $result = external_api::clean_returnvalue(core_course_external::get_activities_overview_returns(), $result);
1760
1761 // There should be one entry for course1, and no others.
1762 $this->assertCount(1, $result['courses']);
1763 $this->assertEquals($course1->id, $result['courses'][0]['id']);
1764 // Check expected overview data for the module.
1765 $this->assertEquals('forum', $result['courses'][0]['overviews'][0]['module']);
1766 $this->assertContains('1 total unread', $result['courses'][0]['overviews'][0]['overviewtext']);
1767 }
c115ff6a
JL
1768
1769 /**
1770 * Test get_user_navigation_options
1771 */
1772 public function test_get_user_navigation_options() {
1773 global $USER;
1774
1775 $this->resetAfterTest();
1776 $course1 = self::getDataGenerator()->create_course();
1777 $course2 = self::getDataGenerator()->create_course();
1778
1779 // Create a viewer user.
1780 $viewer = self::getDataGenerator()->create_user();
1781 $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
1782 $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
1783
1784 $this->setUser($viewer->id);
1785 $courses = array($course1->id , $course2->id, SITEID);
1786
1787 $result = core_course_external::get_user_navigation_options($courses);
1788 $result = external_api::clean_returnvalue(core_course_external::get_user_navigation_options_returns(), $result);
1789
1790 $this->assertCount(0, $result['warnings']);
1791 $this->assertCount(3, $result['courses']);
1792
1793 foreach ($result['courses'] as $course) {
1794 $navoptions = new stdClass;
1795 foreach ($course['options'] as $option) {
1796 $navoptions->{$option['name']} = $option['available'];
1797 }
1798 if ($course['id'] == SITEID) {
99061152 1799 $this->assertCount(8, $course['options']);
c115ff6a
JL
1800 $this->assertTrue($navoptions->blogs);
1801 $this->assertFalse($navoptions->notes);
1802 $this->assertFalse($navoptions->participants);
1803 $this->assertTrue($navoptions->badges);
1804 $this->assertTrue($navoptions->tags);
1805 $this->assertFalse($navoptions->search);
1806 $this->assertTrue($navoptions->calendar);
99061152 1807 $this->assertTrue($navoptions->competencies);
c115ff6a 1808 } else {
99061152 1809 $this->assertCount(6, $course['options']);
c115ff6a
JL
1810 $this->assertTrue($navoptions->blogs);
1811 $this->assertFalse($navoptions->notes);
1812 $this->assertTrue($navoptions->participants);
1813 $this->assertTrue($navoptions->badges);
99061152
DW
1814 $this->assertTrue($navoptions->grades);
1815 $this->assertTrue($navoptions->competencies);
c115ff6a
JL
1816 }
1817 }
1818 }
b9050b10
JL
1819
1820 /**
1821 * Test get_user_administration_options
1822 */
1823 public function test_get_user_administration_options() {
1824 global $USER;
1825
1826 $this->resetAfterTest();
1827 $course1 = self::getDataGenerator()->create_course();
1828 $course2 = self::getDataGenerator()->create_course();
1829
1830 // Create a viewer user.
1831 $viewer = self::getDataGenerator()->create_user();
1832 $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
1833 $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
1834
1835 $this->setUser($viewer->id);
1836 $courses = array($course1->id , $course2->id, SITEID);
1837
1838 $result = core_course_external::get_user_administration_options($courses);
1839 $result = external_api::clean_returnvalue(core_course_external::get_user_administration_options_returns(), $result);
1840
1841 $this->assertCount(0, $result['warnings']);
1842 $this->assertCount(3, $result['courses']);
1843
1844 foreach ($result['courses'] as $course) {
1845 $adminoptions = new stdClass;
1846 foreach ($course['options'] as $option) {
1847 $adminoptions->{$option['name']} = $option['available'];
1848 }
1849 if ($course['id'] == SITEID) {
c874d9aa 1850 $this->assertCount(15, $course['options']);
b9050b10
JL
1851 $this->assertFalse($adminoptions->update);
1852 $this->assertFalse($adminoptions->filters);
1853 $this->assertFalse($adminoptions->reports);
1854 $this->assertFalse($adminoptions->backup);
1855 $this->assertFalse($adminoptions->restore);
1856 $this->assertFalse($adminoptions->files);
c874d9aa
JL
1857 $this->assertFalse(!isset($adminoptions->tags));
1858 $this->assertFalse($adminoptions->gradebook);
1859 $this->assertFalse($adminoptions->outcomes);
1860 $this->assertFalse($adminoptions->badges);
1861 $this->assertFalse($adminoptions->import);
1862 $this->assertFalse($adminoptions->publish);
1863 $this->assertFalse($adminoptions->reset);
1864 $this->assertFalse($adminoptions->roles);
1865 $this->assertFalse($adminoptions->grades);
b9050b10
JL
1866 } else {
1867 $this->assertCount(15, $course['options']);
1868 $this->assertFalse($adminoptions->update);
1869 $this->assertFalse($adminoptions->filters);
1870 $this->assertFalse($adminoptions->reports);
1871 $this->assertFalse($adminoptions->backup);
1872 $this->assertFalse($adminoptions->restore);
1873 $this->assertFalse($adminoptions->files);
1874 $this->assertFalse($adminoptions->tags);
1875 $this->assertFalse($adminoptions->gradebook);
1876 $this->assertFalse($adminoptions->outcomes);
1877 $this->assertTrue($adminoptions->badges);
1878 $this->assertFalse($adminoptions->import);
1879 $this->assertFalse($adminoptions->publish);
1880 $this->assertFalse($adminoptions->reset);
1881 $this->assertFalse($adminoptions->roles);
1882 $this->assertTrue($adminoptions->grades);
1883 }
1884 }
1885 }
80adabef
JL
1886
1887 /**
1888 * Test get_courses_by_fields
1889 */
1890 public function test_get_courses_by_field() {
1891 global $DB;
1892 $this->resetAfterTest(true);
1893
1894 $category1 = self::getDataGenerator()->create_category();
1895 $category2 = self::getDataGenerator()->create_category(array('parent' => $category1->id));
1896 $course1 = self::getDataGenerator()->create_course(array('category' => $category1->id, 'shortname' => 'c1'));
1897 $course2 = self::getDataGenerator()->create_course(array('visible' => 0, 'category' => $category2->id, 'idnumber' => 'i2'));
1898
1899 $student1 = self::getDataGenerator()->create_user();
1900 $user1 = self::getDataGenerator()->create_user();
1901 $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1902 self::getDataGenerator()->enrol_user($student1->id, $course1->id, $studentrole->id);
1903 self::getDataGenerator()->enrol_user($student1->id, $course2->id, $studentrole->id);
1904
1905 self::setAdminUser();
1906 // As admins, we should be able to retrieve everything.
1907 $result = core_course_external::get_courses_by_field();
1908 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1909 $this->assertCount(3, $result['courses']);
1910 // Expect to receive all the fields.
1911 $this->assertCount(35, $result['courses'][0]);
1912 $this->assertCount(35, $result['courses'][1]);
1913 $this->assertCount(35, $result['courses'][2]);
1914
1915 $result = core_course_external::get_courses_by_field('id', $course1->id);
1916 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1917 $this->assertCount(1, $result['courses']);
1918 $this->assertEquals($course1->id, $result['courses'][0]['id']);
1919 // Expect to receive all the fields.
1920 $this->assertCount(35, $result['courses'][0]);
1921
1922 $result = core_course_external::get_courses_by_field('id', $course2->id);
1923 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1924 $this->assertCount(1, $result['courses']);
1925 $this->assertEquals($course2->id, $result['courses'][0]['id']);
1926
1927 $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
1928 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1929 $this->assertCount(2, $result['courses']);
1930
1931 $result = core_course_external::get_courses_by_field('category', $category1->id);
1932 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1933 $this->assertCount(1, $result['courses']);
1934 $this->assertEquals($course1->id, $result['courses'][0]['id']);
1935
1936 $result = core_course_external::get_courses_by_field('shortname', 'c1');
1937 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1938 $this->assertCount(1, $result['courses']);
1939 $this->assertEquals($course1->id, $result['courses'][0]['id']);
1940
1941 $result = core_course_external::get_courses_by_field('idnumber', 'i2');
1942 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1943 $this->assertCount(1, $result['courses']);
1944 $this->assertEquals($course2->id, $result['courses'][0]['id']);
1945
1946 $result = core_course_external::get_courses_by_field('idnumber', 'x');
1947 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1948 $this->assertCount(0, $result['courses']);
1949
1950 self::setUser($student1);
1951 // All visible courses (including front page) for normal student.
1952 $result = core_course_external::get_courses_by_field();
1953 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1954 $this->assertCount(2, $result['courses']);
1955 $this->assertCount(28, $result['courses'][0]);
1956 $this->assertCount(28, $result['courses'][1]);
1957
1958 $result = core_course_external::get_courses_by_field('id', $course1->id);
1959 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1960 $this->assertCount(1, $result['courses']);
1961 $this->assertEquals($course1->id, $result['courses'][0]['id']);
1962 // Expect to receive all the files that a student can see.
1963 $this->assertCount(28, $result['courses'][0]);
1964
1965 // Course 2 is not visible.
1966 $result = core_course_external::get_courses_by_field('id', $course2->id);
1967 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1968 $this->assertCount(0, $result['courses']);
1969
1970 $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
1971 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1972 $this->assertCount(1, $result['courses']);
1973
1974 $result = core_course_external::get_courses_by_field('category', $category1->id);
1975 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1976 $this->assertCount(1, $result['courses']);
1977 $this->assertEquals($course1->id, $result['courses'][0]['id']);
1978
1979 $result = core_course_external::get_courses_by_field('shortname', 'c1');
1980 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1981 $this->assertCount(1, $result['courses']);
1982 $this->assertEquals($course1->id, $result['courses'][0]['id']);
1983
1984 $result = core_course_external::get_courses_by_field('idnumber', 'i2');
1985 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1986 $this->assertCount(0, $result['courses']);
1987
1988 $result = core_course_external::get_courses_by_field('idnumber', 'x');
1989 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1990 $this->assertCount(0, $result['courses']);
1991
1992 self::setUser($user1);
1993 // All visible courses (including front page) for authenticated user.
1994 $result = core_course_external::get_courses_by_field();
1995 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
1996 $this->assertCount(2, $result['courses']);
1997 $this->assertCount(28, $result['courses'][0]); // Site course.
1998 $this->assertCount(12, $result['courses'][1]); // Only public information, not enrolled.
1999
2000 $result = core_course_external::get_courses_by_field('id', $course1->id);
2001 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2002 $this->assertCount(1, $result['courses']);
2003 $this->assertEquals($course1->id, $result['courses'][0]['id']);
2004 // Expect to receive all the files that a authenticated can see.
2005 $this->assertCount(12, $result['courses'][0]);
2006
2007 // Course 2 is not visible.
2008 $result = core_course_external::get_courses_by_field('id', $course2->id);
2009 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2010 $this->assertCount(0, $result['courses']);
2011
2012 $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2013 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2014 $this->assertCount(1, $result['courses']);
2015
2016 $result = core_course_external::get_courses_by_field('category', $category1->id);
2017 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2018 $this->assertCount(1, $result['courses']);
2019 $this->assertEquals($course1->id, $result['courses'][0]['id']);
2020
2021 $result = core_course_external::get_courses_by_field('shortname', 'c1');
2022 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2023 $this->assertCount(1, $result['courses']);
2024 $this->assertEquals($course1->id, $result['courses'][0]['id']);
2025
2026 $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2027 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2028 $this->assertCount(0, $result['courses']);
2029
2030 $result = core_course_external::get_courses_by_field('idnumber', 'x');
2031 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2032 $this->assertCount(0, $result['courses']);
2033 }
2034
2035 public function test_get_courses_by_field_invalid_field() {
2036 $this->expectException('invalid_parameter_exception');
2037 $result = core_course_external::get_courses_by_field('zyx', 'x');
2038 }
2039
2040 public function test_get_courses_by_field_invalid_courses() {
2041 $result = core_course_external::get_courses_by_field('id', '-1');
2042 $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2043 $this->assertCount(0, $result['courses']);
2044 }
2a7a0216 2045}