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