Merge branch 'MDL-58794-master' of git://github.com/junpataleta/moodle
[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         $tomorrow = time() + DAYSECS;
789         // Module with availability restrictions not met.
790         $url = $this->getDataGenerator()->create_module('url',
791             array('course' => $course->id, 'name' => 'URL: % & $ ../', 'section' => 2),
792             array('availability' => '{"op":"&","c":[{"type":"date","d":">=","t":' . $tomorrow . '}],"showc":[true]}'));
793         $urlcm = get_coursemodule_from_instance('url', $url->id);
794         // Module for the last section.
795         $this->getDataGenerator()->create_module('url',
796             array('course' => $course->id, 'name' => 'URL for last section', 'section' => 3));
797         // Module for section 1 with availability restrictions met.
798         $yesterday = time() - DAYSECS;
799         $this->getDataGenerator()->create_module('url',
800             array('course' => $course->id, 'name' => 'URL restrictions met', 'section' => 1),
801             array('availability' => '{"op":"&","c":[{"type":"date","d":">=","t":'. $yesterday .'}],"showc":[true]}'));
803         // Set the required capabilities by the external function.
804         $context = context_course::instance($course->id);
805         $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
806         $this->assignUserCapability('moodle/course:update', $context->id, $roleid);
807         $this->assignUserCapability('mod/data:view', $context->id, $roleid);
809         $conditions = array('course' => $course->id, 'section' => 2);
810         $DB->set_field('course_sections', 'summary', 'Text with iframe <iframe src="https://moodle.org"></iframe>', $conditions);
812         // Add date availability condition not met for last section.
813         $availability = '{"op":"&","c":[{"type":"date","d":">=","t":' . $tomorrow . '}],"showc":[true]}';
814         $DB->set_field('course_sections', 'availability', $availability,
815                 array('course' => $course->id, 'section' => 3));
816         rebuild_course_cache($course->id, true);
818         return array($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm);
819     }
821     /**
822      * Test get_course_contents
823      */
824     public function test_get_course_contents() {
825         $this->resetAfterTest(true);
827         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
829         $sections = core_course_external::get_course_contents($course->id, array());
830         // We need to execute the return values cleaning process to simulate the web service server.
831         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
833         $modinfo = get_fast_modinfo($course);
834         $testexecuted = 0;
835         foreach ($sections[0]['modules'] as $module) {
836             if ($module['id'] == $forumcm->id and $module['modname'] == 'forum') {
837                 $cm = $modinfo->cms[$forumcm->id];
838                 $formattedtext = format_text($cm->content, FORMAT_HTML,
839                     array('noclean' => true, 'para' => false, 'filter' => false));
840                 $this->assertEquals($formattedtext, $module['description']);
841                 $this->assertEquals($forumcm->instance, $module['instance']);
842                 $testexecuted = $testexecuted + 1;
843             } else if ($module['id'] == $labelcm->id and $module['modname'] == 'label') {
844                 $cm = $modinfo->cms[$labelcm->id];
845                 $formattedtext = format_text($cm->content, FORMAT_HTML,
846                     array('noclean' => true, 'para' => false, 'filter' => false));
847                 $this->assertEquals($formattedtext, $module['description']);
848                 $this->assertEquals($labelcm->instance, $module['instance']);
849                 $testexecuted = $testexecuted + 1;
850             }
851         }
852         $this->assertEquals(2, $testexecuted);
853         $this->assertEquals(0, $sections[0]['section']);
855         // Check that the only return section has the 5 created modules.
856         $this->assertCount(4, $sections[0]['modules']);
857         $this->assertCount(1, $sections[1]['modules']);
858         $this->assertCount(1, $sections[2]['modules']);
859         $this->assertCount(0, $sections[3]['modules']); // No modules for the section with availability restrictions.
860         $this->assertNotEmpty($sections[3]['availabilityinfo']);
861         $this->assertEquals(1, $sections[1]['section']);
862         $this->assertEquals(2, $sections[2]['section']);
863         $this->assertEquals(3, $sections[3]['section']);
864         $this->assertContains('<iframe', $sections[2]['summary']);
865         $this->assertContains('</iframe>', $sections[2]['summary']);
866         // The module with the availability restriction met is returning contents.
867         $this->assertNotEmpty($sections[1]['modules'][0]['contents']);
868         // The module with the availability restriction not met is not returning contents.
869         $this->assertArrayNotHasKey('contents', $sections[2]['modules'][0]);
870         $this->assertNotEmpty($sections[2]['modules'][0]['availabilityinfo']);
871         try {
872             $sections = core_course_external::get_course_contents($course->id,
873                                                                     array(array("name" => "invalid", "value" => 1)));
874             $this->fail('Exception expected due to invalid option.');
875         } catch (moodle_exception $e) {
876             $this->assertEquals('errorinvalidparam', $e->errorcode);
877         }
878     }
881     /**
882      * Test get_course_contents excluding modules
883      */
884     public function test_get_course_contents_excluding_modules() {
885         $this->resetAfterTest(true);
887         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
889         // Test exclude modules.
890         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludemodules", "value" => 1)));
892         // We need to execute the return values cleaning process to simulate the web service server.
893         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
895         $this->assertEmpty($sections[0]['modules']);
896         $this->assertEmpty($sections[1]['modules']);
897     }
899     /**
900      * Test get_course_contents excluding contents
901      */
902     public function test_get_course_contents_excluding_contents() {
903         $this->resetAfterTest(true);
905         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
907         // Test exclude modules.
908         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludecontents", "value" => 1)));
910         // We need to execute the return values cleaning process to simulate the web service server.
911         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
913         foreach ($sections as $section) {
914             foreach ($section['modules'] as $module) {
915                 // Only resources return contents.
916                 if (isset($module['contents'])) {
917                     $this->assertEmpty($module['contents']);
918                 }
919             }
920         }
921     }
923     /**
924      * Test get_course_contents filtering by section number
925      */
926     public function test_get_course_contents_section_number() {
927         $this->resetAfterTest(true);
929         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
931         // Test exclude modules.
932         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "sectionnumber", "value" => 0)));
934         // We need to execute the return values cleaning process to simulate the web service server.
935         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
937         $this->assertCount(1, $sections);
938         $this->assertCount(4, $sections[0]['modules']);
939     }
941     /**
942      * Test get_course_contents filtering by cmid
943      */
944     public function test_get_course_contents_cmid() {
945         $this->resetAfterTest(true);
947         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
949         // Test exclude modules.
950         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "cmid", "value" => $forumcm->id)));
952         // We need to execute the return values cleaning process to simulate the web service server.
953         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
955         $this->assertCount(4, $sections);
956         $this->assertCount(1, $sections[0]['modules']);
957         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
958     }
961     /**
962      * Test get_course_contents filtering by cmid and section
963      */
964     public function test_get_course_contents_section_cmid() {
965         $this->resetAfterTest(true);
967         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
969         // Test exclude modules.
970         $sections = core_course_external::get_course_contents($course->id, array(
971                                                                         array("name" => "cmid", "value" => $forumcm->id),
972                                                                         array("name" => "sectionnumber", "value" => 0)
973                                                                         ));
975         // We need to execute the return values cleaning process to simulate the web service server.
976         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
978         $this->assertCount(1, $sections);
979         $this->assertCount(1, $sections[0]['modules']);
980         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
981     }
983     /**
984      * Test get_course_contents filtering by modname
985      */
986     public function test_get_course_contents_modname() {
987         $this->resetAfterTest(true);
989         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
991         // Test exclude modules.
992         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "modname", "value" => "forum")));
994         // We need to execute the return values cleaning process to simulate the web service server.
995         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
997         $this->assertCount(4, $sections);
998         $this->assertCount(1, $sections[0]['modules']);
999         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
1000     }
1002     /**
1003      * Test get_course_contents filtering by modname
1004      */
1005     public function test_get_course_contents_modid() {
1006         $this->resetAfterTest(true);
1008         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1010         // Test exclude modules.
1011         $sections = core_course_external::get_course_contents($course->id, array(
1012                                                                             array("name" => "modname", "value" => "page"),
1013                                                                             array("name" => "modid", "value" => $pagecm->instance),
1014                                                                             ));
1016         // We need to execute the return values cleaning process to simulate the web service server.
1017         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1019         $this->assertCount(4, $sections);
1020         $this->assertCount(1, $sections[0]['modules']);
1021         $this->assertEquals("page", $sections[0]['modules'][0]["modname"]);
1022         $this->assertEquals($pagecm->instance, $sections[0]['modules'][0]["instance"]);
1023     }
1025     /**
1026      * Test duplicate_course
1027      */
1028     public function test_duplicate_course() {
1029         $this->resetAfterTest(true);
1031         // Create one course with three modules.
1032         $course  = self::getDataGenerator()->create_course();
1033         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course->id));
1034         $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
1035         $forumcontext = context_module::instance($forum->cmid);
1036         $data = $this->getDataGenerator()->create_module('data', array('assessed'=>1, 'scale'=>100, 'course'=>$course->id));
1037         $datacontext = context_module::instance($data->cmid);
1038         $datacm = get_coursemodule_from_instance('page', $data->id);
1039         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course->id));
1040         $pagecontext = context_module::instance($page->cmid);
1041         $pagecm = get_coursemodule_from_instance('page', $page->id);
1043         // Set the required capabilities by the external function.
1044         $coursecontext = context_course::instance($course->id);
1045         $categorycontext = context_coursecat::instance($course->category);
1046         $roleid = $this->assignUserCapability('moodle/course:create', $categorycontext->id);
1047         $this->assignUserCapability('moodle/course:view', $categorycontext->id, $roleid);
1048         $this->assignUserCapability('moodle/restore:restorecourse', $categorycontext->id, $roleid);
1049         $this->assignUserCapability('moodle/backup:backupcourse', $coursecontext->id, $roleid);
1050         $this->assignUserCapability('moodle/backup:configure', $coursecontext->id, $roleid);
1051         // Optional capabilities to copy user data.
1052         $this->assignUserCapability('moodle/backup:userinfo', $coursecontext->id, $roleid);
1053         $this->assignUserCapability('moodle/restore:userinfo', $categorycontext->id, $roleid);
1055         $newcourse['fullname'] = 'Course duplicate';
1056         $newcourse['shortname'] = 'courseduplicate';
1057         $newcourse['categoryid'] = $course->category;
1058         $newcourse['visible'] = true;
1059         $newcourse['options'][] = array('name' => 'users', 'value' => true);
1061         $duplicate = core_course_external::duplicate_course($course->id, $newcourse['fullname'],
1062                 $newcourse['shortname'], $newcourse['categoryid'], $newcourse['visible'], $newcourse['options']);
1064         // We need to execute the return values cleaning process to simulate the web service server.
1065         $duplicate = external_api::clean_returnvalue(core_course_external::duplicate_course_returns(), $duplicate);
1067         // Check that the course has been duplicated.
1068         $this->assertEquals($newcourse['shortname'], $duplicate['shortname']);
1069     }
1071     /**
1072      * Test update_courses
1073      */
1074     public function test_update_courses() {
1075         global $DB, $CFG, $USER, $COURSE;
1077         // Get current $COURSE to be able to restore it later (defaults to $SITE). We need this
1078         // trick because we are both updating and getting (for testing) course information
1079         // in the same request and core_course_external::update_courses()
1080         // is overwriting $COURSE all over the time with OLD values, so later
1081         // use of get_course() fetches those OLD values instead of the updated ones.
1082         // See MDL-39723 for more info.
1083         $origcourse = clone($COURSE);
1085         $this->resetAfterTest(true);
1087         // Set the required capabilities by the external function.
1088         $contextid = context_system::instance()->id;
1089         $roleid = $this->assignUserCapability('moodle/course:update', $contextid);
1090         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1091         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1092         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1093         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1094         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1095         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
1096         $this->assignUserCapability('moodle/course:viewhiddencourses', $contextid, $roleid);
1098         // Create category and course.
1099         $category1  = self::getDataGenerator()->create_category();
1100         $category2  = self::getDataGenerator()->create_category();
1101         $originalcourse1 = self::getDataGenerator()->create_course();
1102         self::getDataGenerator()->enrol_user($USER->id, $originalcourse1->id, $roleid);
1103         $originalcourse2 = self::getDataGenerator()->create_course();
1104         self::getDataGenerator()->enrol_user($USER->id, $originalcourse2->id, $roleid);
1106         // Course values to be updated.
1107         $course1['id'] = $originalcourse1->id;
1108         $course1['fullname'] = 'Updated test course 1';
1109         $course1['shortname'] = 'Udestedtestcourse1';
1110         $course1['categoryid'] = $category1->id;
1111         $course2['id'] = $originalcourse2->id;
1112         $course2['fullname'] = 'Updated test course 2';
1113         $course2['shortname'] = 'Updestedtestcourse2';
1114         $course2['categoryid'] = $category2->id;
1115         $course2['idnumber'] = 'Updatedidnumber2';
1116         $course2['summary'] = 'Updaated description for course 2';
1117         $course2['summaryformat'] = FORMAT_HTML;
1118         $course2['format'] = 'topics';
1119         $course2['showgrades'] = 1;
1120         $course2['newsitems'] = 3;
1121         $course2['startdate'] = 1420092000; // 01/01/2015.
1122         $course2['enddate'] = 1422669600; // 01/31/2015.
1123         $course2['maxbytes'] = 100000;
1124         $course2['showreports'] = 1;
1125         $course2['visible'] = 0;
1126         $course2['hiddensections'] = 0;
1127         $course2['groupmode'] = 0;
1128         $course2['groupmodeforce'] = 0;
1129         $course2['defaultgroupingid'] = 0;
1130         $course2['enablecompletion'] = 1;
1131         $course2['lang'] = 'en';
1132         $course2['forcetheme'] = 'bootstrapbase';
1133         $courses = array($course1, $course2);
1135         $updatedcoursewarnings = core_course_external::update_courses($courses);
1136         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1137                                                                     $updatedcoursewarnings);
1138         $COURSE = $origcourse; // Restore $COURSE. Instead of using the OLD one set by the previous line.
1140         // Check that right number of courses were created.
1141         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1143         // Check that the courses were correctly created.
1144         foreach ($courses as $course) {
1145             $courseinfo = course_get_format($course['id'])->get_course();
1146             if ($course['id'] == $course2['id']) {
1147                 $this->assertEquals($course2['fullname'], $courseinfo->fullname);
1148                 $this->assertEquals($course2['shortname'], $courseinfo->shortname);
1149                 $this->assertEquals($course2['categoryid'], $courseinfo->category);
1150                 $this->assertEquals($course2['idnumber'], $courseinfo->idnumber);
1151                 $this->assertEquals($course2['summary'], $courseinfo->summary);
1152                 $this->assertEquals($course2['summaryformat'], $courseinfo->summaryformat);
1153                 $this->assertEquals($course2['format'], $courseinfo->format);
1154                 $this->assertEquals($course2['showgrades'], $courseinfo->showgrades);
1155                 $this->assertEquals($course2['newsitems'], $courseinfo->newsitems);
1156                 $this->assertEquals($course2['startdate'], $courseinfo->startdate);
1157                 $this->assertEquals($course2['enddate'], $courseinfo->enddate);
1158                 $this->assertEquals($course2['maxbytes'], $courseinfo->maxbytes);
1159                 $this->assertEquals($course2['showreports'], $courseinfo->showreports);
1160                 $this->assertEquals($course2['visible'], $courseinfo->visible);
1161                 $this->assertEquals($course2['hiddensections'], $courseinfo->hiddensections);
1162                 $this->assertEquals($course2['groupmode'], $courseinfo->groupmode);
1163                 $this->assertEquals($course2['groupmodeforce'], $courseinfo->groupmodeforce);
1164                 $this->assertEquals($course2['defaultgroupingid'], $courseinfo->defaultgroupingid);
1165                 $this->assertEquals($course2['lang'], $courseinfo->lang);
1167                 if (!empty($CFG->allowcoursethemes)) {
1168                     $this->assertEquals($course2['forcetheme'], $courseinfo->theme);
1169                 }
1171                 $this->assertEquals($course2['enablecompletion'], $courseinfo->enablecompletion);
1172             } else if ($course['id'] == $course1['id']) {
1173                 $this->assertEquals($course1['fullname'], $courseinfo->fullname);
1174                 $this->assertEquals($course1['shortname'], $courseinfo->shortname);
1175                 $this->assertEquals($course1['categoryid'], $courseinfo->category);
1176                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1177                 $this->assertEquals('topics', $courseinfo->format);
1178                 $this->assertEquals(5, course_get_format($course['id'])->get_last_section_number());
1179                 $this->assertEquals(0, $courseinfo->newsitems);
1180                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1181             } else {
1182                 throw new moodle_exception('Unexpected shortname');
1183             }
1184         }
1186         $courses = array($course1);
1187         // Try update course without update capability.
1188         $user = self::getDataGenerator()->create_user();
1189         $this->setUser($user);
1190         $this->unassignUserCapability('moodle/course:update', $contextid, $roleid);
1191         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1192         $updatedcoursewarnings = core_course_external::update_courses($courses);
1193         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1194                                                                     $updatedcoursewarnings);
1195         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1197         // Try update course category without capability.
1198         $this->assignUserCapability('moodle/course:update', $contextid, $roleid);
1199         $this->unassignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1200         $user = self::getDataGenerator()->create_user();
1201         $this->setUser($user);
1202         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1203         $course1['categoryid'] = $category2->id;
1204         $courses = array($course1);
1205         $updatedcoursewarnings = core_course_external::update_courses($courses);
1206         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1207                                                                     $updatedcoursewarnings);
1208         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1210         // Try update course fullname without capability.
1211         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1212         $this->unassignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1213         $user = self::getDataGenerator()->create_user();
1214         $this->setUser($user);
1215         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1216         $updatedcoursewarnings = core_course_external::update_courses($courses);
1217         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1218                                                                     $updatedcoursewarnings);
1219         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1220         $course1['fullname'] = 'Testing fullname without permission';
1221         $courses = array($course1);
1222         $updatedcoursewarnings = core_course_external::update_courses($courses);
1223         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1224                                                                     $updatedcoursewarnings);
1225         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1227         // Try update course shortname without capability.
1228         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1229         $this->unassignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1230         $user = self::getDataGenerator()->create_user();
1231         $this->setUser($user);
1232         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1233         $updatedcoursewarnings = core_course_external::update_courses($courses);
1234         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1235                                                                     $updatedcoursewarnings);
1236         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1237         $course1['shortname'] = 'Testing shortname without permission';
1238         $courses = array($course1);
1239         $updatedcoursewarnings = core_course_external::update_courses($courses);
1240         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1241                                                                     $updatedcoursewarnings);
1242         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1244         // Try update course idnumber without capability.
1245         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1246         $this->unassignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1247         $user = self::getDataGenerator()->create_user();
1248         $this->setUser($user);
1249         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1250         $updatedcoursewarnings = core_course_external::update_courses($courses);
1251         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1252                                                                     $updatedcoursewarnings);
1253         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1254         $course1['idnumber'] = 'NEWIDNUMBER';
1255         $courses = array($course1);
1256         $updatedcoursewarnings = core_course_external::update_courses($courses);
1257         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1258                                                                     $updatedcoursewarnings);
1259         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1261         // Try update course summary without capability.
1262         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1263         $this->unassignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1264         $user = self::getDataGenerator()->create_user();
1265         $this->setUser($user);
1266         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1267         $updatedcoursewarnings = core_course_external::update_courses($courses);
1268         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1269                                                                     $updatedcoursewarnings);
1270         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1271         $course1['summary'] = 'New summary';
1272         $courses = array($course1);
1273         $updatedcoursewarnings = core_course_external::update_courses($courses);
1274         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1275                                                                     $updatedcoursewarnings);
1276         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1278         // Try update course with invalid summary format.
1279         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1280         $user = self::getDataGenerator()->create_user();
1281         $this->setUser($user);
1282         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1283         $updatedcoursewarnings = core_course_external::update_courses($courses);
1284         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1285                                                                     $updatedcoursewarnings);
1286         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1287         $course1['summaryformat'] = 10;
1288         $courses = array($course1);
1289         $updatedcoursewarnings = core_course_external::update_courses($courses);
1290         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1291                                                                     $updatedcoursewarnings);
1292         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1294         // Try update course visibility without capability.
1295         $this->unassignUserCapability('moodle/course:visibility', $contextid, $roleid);
1296         $user = self::getDataGenerator()->create_user();
1297         $this->setUser($user);
1298         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1299         $course1['summaryformat'] = FORMAT_MOODLE;
1300         $courses = array($course1);
1301         $updatedcoursewarnings = core_course_external::update_courses($courses);
1302         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1303                                                                     $updatedcoursewarnings);
1304         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1305         $course1['visible'] = 0;
1306         $courses = array($course1);
1307         $updatedcoursewarnings = core_course_external::update_courses($courses);
1308         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1309                                                                     $updatedcoursewarnings);
1310         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1311     }
1313     /**
1314      * Test delete course_module.
1315      */
1316     public function test_delete_modules() {
1317         global $DB;
1319         // Ensure we reset the data after this test.
1320         $this->resetAfterTest(true);
1322         // Create a user.
1323         $user = self::getDataGenerator()->create_user();
1325         // Set the tests to run as the user.
1326         self::setUser($user);
1328         // Create a course to add the modules.
1329         $course = self::getDataGenerator()->create_course();
1331         // Create two test modules.
1332         $record = new stdClass();
1333         $record->course = $course->id;
1334         $module1 = self::getDataGenerator()->create_module('forum', $record);
1335         $module2 = self::getDataGenerator()->create_module('assign', $record);
1337         // Check the forum was correctly created.
1338         $this->assertEquals(1, $DB->count_records('forum', array('id' => $module1->id)));
1340         // Check the assignment was correctly created.
1341         $this->assertEquals(1, $DB->count_records('assign', array('id' => $module2->id)));
1343         // Check data exists in the course modules table.
1344         $this->assertEquals(2, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1345                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1347         // Enrol the user in the course.
1348         $enrol = enrol_get_plugin('manual');
1349         $enrolinstances = enrol_get_instances($course->id, true);
1350         foreach ($enrolinstances as $courseenrolinstance) {
1351             if ($courseenrolinstance->enrol == "manual") {
1352                 $instance = $courseenrolinstance;
1353                 break;
1354             }
1355         }
1356         $enrol->enrol_user($instance, $user->id);
1358         // Assign capabilities to delete module 1.
1359         $modcontext = context_module::instance($module1->cmid);
1360         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id);
1362         // Assign capabilities to delete module 2.
1363         $modcontext = context_module::instance($module2->cmid);
1364         $newrole = create_role('Role 2', 'role2', 'Role 2 description');
1365         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id, $newrole);
1367         // Deleting these module instances.
1368         core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1370         // Check the forum was deleted.
1371         $this->assertEquals(0, $DB->count_records('forum', array('id' => $module1->id)));
1373         // Check the assignment was deleted.
1374         $this->assertEquals(0, $DB->count_records('assign', array('id' => $module2->id)));
1376         // Check we retrieve no data in the course modules table.
1377         $this->assertEquals(0, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1378                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1380         // Call with non-existent course module id and ensure exception thrown.
1381         try {
1382             core_course_external::delete_modules(array('1337'));
1383             $this->fail('Exception expected due to missing course module.');
1384         } catch (dml_missing_record_exception $e) {
1385             $this->assertEquals('invalidcoursemodule', $e->errorcode);
1386         }
1388         // Create two modules.
1389         $module1 = self::getDataGenerator()->create_module('forum', $record);
1390         $module2 = self::getDataGenerator()->create_module('assign', $record);
1392         // Since these modules were recreated the user will not have capabilities
1393         // to delete them, ensure exception is thrown if they try.
1394         try {
1395             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1396             $this->fail('Exception expected due to missing capability.');
1397         } catch (moodle_exception $e) {
1398             $this->assertEquals('nopermissions', $e->errorcode);
1399         }
1401         // Unenrol user from the course.
1402         $enrol->unenrol_user($instance, $user->id);
1404         // Try and delete modules from the course the user was unenrolled in, make sure exception thrown.
1405         try {
1406             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1407             $this->fail('Exception expected due to being unenrolled from the course.');
1408         } catch (moodle_exception $e) {
1409             $this->assertEquals('requireloginerror', $e->errorcode);
1410         }
1411     }
1413     /**
1414      * Test import_course into an empty course
1415      */
1416     public function test_import_course_empty() {
1417         global $USER;
1419         $this->resetAfterTest(true);
1421         $course1  = self::getDataGenerator()->create_course();
1422         $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course1->id, 'name' => 'Forum test'));
1423         $page = $this->getDataGenerator()->create_module('page', array('course' => $course1->id, 'name' => 'Page test'));
1425         $course2  = self::getDataGenerator()->create_course();
1427         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1428         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1430         // Verify the state of the courses before we do the import.
1431         $this->assertCount(2, $course1cms);
1432         $this->assertEmpty($course2cms);
1434         // Setup the user to run the operation (ugly hack because validate_context() will
1435         // fail as the email is not set by $this->setAdminUser()).
1436         $this->setAdminUser();
1437         $USER->email = 'emailtopass@example.com';
1439         // Import from course1 to course2.
1440         core_course_external::import_course($course1->id, $course2->id, 0);
1442         // Verify that now we have two modules in both courses.
1443         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1444         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1445         $this->assertCount(2, $course1cms);
1446         $this->assertCount(2, $course2cms);
1448         // Verify that the names transfered across correctly.
1449         foreach ($course2cms as $cm) {
1450             if ($cm->modname === 'page') {
1451                 $this->assertEquals($cm->name, $page->name);
1452             } else if ($cm->modname === 'forum') {
1453                 $this->assertEquals($cm->name, $forum->name);
1454             } else {
1455                 $this->fail('Unknown CM found.');
1456             }
1457         }
1458     }
1460     /**
1461      * Test import_course into an filled course
1462      */
1463     public function test_import_course_filled() {
1464         global $USER;
1466         $this->resetAfterTest(true);
1468         // Add forum and page to course1.
1469         $course1  = self::getDataGenerator()->create_course();
1470         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1471         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1473         // Add quiz to course 2.
1474         $course2  = self::getDataGenerator()->create_course();
1475         $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1477         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1478         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1480         // Verify the state of the courses before we do the import.
1481         $this->assertCount(2, $course1cms);
1482         $this->assertCount(1, $course2cms);
1484         // Setup the user to run the operation (ugly hack because validate_context() will
1485         // fail as the email is not set by $this->setAdminUser()).
1486         $this->setAdminUser();
1487         $USER->email = 'emailtopass@example.com';
1489         // Import from course1 to course2 without deleting content.
1490         core_course_external::import_course($course1->id, $course2->id, 0);
1492         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1494         // Verify that now we have three modules in course2.
1495         $this->assertCount(3, $course2cms);
1497         // Verify that the names transfered across correctly.
1498         foreach ($course2cms as $cm) {
1499             if ($cm->modname === 'page') {
1500                 $this->assertEquals($cm->name, $page->name);
1501             } else if ($cm->modname === 'forum') {
1502                 $this->assertEquals($cm->name, $forum->name);
1503             } else if ($cm->modname === 'quiz') {
1504                 $this->assertEquals($cm->name, $quiz->name);
1505             } else {
1506                 $this->fail('Unknown CM found.');
1507             }
1508         }
1509     }
1511     /**
1512      * Test import_course with only blocks set to backup
1513      */
1514     public function test_import_course_blocksonly() {
1515         global $USER, $DB;
1517         $this->resetAfterTest(true);
1519         // Add forum and page to course1.
1520         $course1  = self::getDataGenerator()->create_course();
1521         $course1ctx = context_course::instance($course1->id);
1522         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1523         $block = $this->getDataGenerator()->create_block('online_users', array('parentcontextid' => $course1ctx->id));
1525         $course2  = self::getDataGenerator()->create_course();
1526         $course2ctx = context_course::instance($course2->id);
1527         $initialblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1528         $initialcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1530         // Setup the user to run the operation (ugly hack because validate_context() will
1531         // fail as the email is not set by $this->setAdminUser()).
1532         $this->setAdminUser();
1533         $USER->email = 'emailtopass@example.com';
1535         // Import from course1 to course2 without deleting content, but excluding
1536         // activities.
1537         $options = array(
1538             array('name' => 'activities', 'value' => 0),
1539             array('name' => 'blocks', 'value' => 1),
1540             array('name' => 'filters', 'value' => 0),
1541         );
1543         core_course_external::import_course($course1->id, $course2->id, 0, $options);
1545         $newcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1546         $newblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1547         // Check that course modules haven't changed, but that blocks have.
1548         $this->assertEquals($initialcmcount, $newcmcount);
1549         $this->assertEquals(($initialblockcount + 1), $newblockcount);
1550     }
1552     /**
1553      * Test import_course into an filled course, deleting content.
1554      */
1555     public function test_import_course_deletecontent() {
1556         global $USER;
1557         $this->resetAfterTest(true);
1559         // Add forum and page to course1.
1560         $course1  = self::getDataGenerator()->create_course();
1561         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1562         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1564         // Add quiz to course 2.
1565         $course2  = self::getDataGenerator()->create_course();
1566         $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1568         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1569         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1571         // Verify the state of the courses before we do the import.
1572         $this->assertCount(2, $course1cms);
1573         $this->assertCount(1, $course2cms);
1575         // Setup the user to run the operation (ugly hack because validate_context() will
1576         // fail as the email is not set by $this->setAdminUser()).
1577         $this->setAdminUser();
1578         $USER->email = 'emailtopass@example.com';
1580         // Import from course1 to course2,  deleting content.
1581         core_course_external::import_course($course1->id, $course2->id, 1);
1583         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1585         // Verify that now we have two modules in course2.
1586         $this->assertCount(2, $course2cms);
1588         // Verify that the course only contains the imported modules.
1589         foreach ($course2cms as $cm) {
1590             if ($cm->modname === 'page') {
1591                 $this->assertEquals($cm->name, $page->name);
1592             } else if ($cm->modname === 'forum') {
1593                 $this->assertEquals($cm->name, $forum->name);
1594             } else {
1595                 $this->fail('Unknown CM found: '.$cm->name);
1596             }
1597         }
1598     }
1600     /**
1601      * Ensure import_course handles incorrect deletecontent option correctly.
1602      */
1603     public function test_import_course_invalid_deletecontent_option() {
1604         $this->resetAfterTest(true);
1606         $course1  = self::getDataGenerator()->create_course();
1607         $course2  = self::getDataGenerator()->create_course();
1609         $this->expectException('moodle_exception');
1610         $this->expectExceptionMessage(get_string('invalidextparam', 'webservice', -1));
1611         // Import from course1 to course2, with invalid option
1612         core_course_external::import_course($course1->id, $course2->id, -1);;
1613     }
1615     /**
1616      * Test view_course function
1617      */
1618     public function test_view_course() {
1620         $this->resetAfterTest();
1622         // Course without sections.
1623         $course = $this->getDataGenerator()->create_course(array('numsections' => 5), array('createsections' => true));
1624         $this->setAdminUser();
1626         // Redirect events to the sink, so we can recover them later.
1627         $sink = $this->redirectEvents();
1629         $result = core_course_external::view_course($course->id, 1);
1630         $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
1631         $events = $sink->get_events();
1632         $event = reset($events);
1634         // Check the event details are correct.
1635         $this->assertInstanceOf('\core\event\course_viewed', $event);
1636         $this->assertEquals(context_course::instance($course->id), $event->get_context());
1637         $this->assertEquals(1, $event->other['coursesectionnumber']);
1639         $result = core_course_external::view_course($course->id);
1640         $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
1641         $events = $sink->get_events();
1642         $event = array_pop($events);
1643         $sink->close();
1645         // Check the event details are correct.
1646         $this->assertInstanceOf('\core\event\course_viewed', $event);
1647         $this->assertEquals(context_course::instance($course->id), $event->get_context());
1648         $this->assertEmpty($event->other);
1650     }
1652     /**
1653      * Test get_course_module
1654      */
1655     public function test_get_course_module() {
1656         global $DB;
1658         $this->resetAfterTest(true);
1660         $this->setAdminUser();
1661         $course = self::getDataGenerator()->create_course();
1662         $record = array(
1663             'course' => $course->id,
1664             'name' => 'First Assignment'
1665         );
1666         $options = array(
1667             'idnumber' => 'ABC',
1668             'visible' => 0
1669         );
1670         // Hidden activity.
1671         $assign = self::getDataGenerator()->create_module('assign', $record, $options);
1673         $outcomescale = 'Distinction, Very Good, Good, Pass, Fail';
1675         // Insert a custom grade scale to be used by an outcome.
1676         $gradescale = new grade_scale();
1677         $gradescale->name        = 'gettcoursemodulescale';
1678         $gradescale->courseid    = $course->id;
1679         $gradescale->userid      = 0;
1680         $gradescale->scale       = $outcomescale;
1681         $gradescale->description = 'This scale is used to mark standard assignments.';
1682         $gradescale->insert();
1684         // Insert an outcome.
1685         $data = new stdClass();
1686         $data->courseid = $course->id;
1687         $data->fullname = 'Team work';
1688         $data->shortname = 'Team work';
1689         $data->scaleid = $gradescale->id;
1690         $outcome = new grade_outcome($data, false);
1691         $outcome->insert();
1693         $outcomegradeitem = new grade_item();
1694         $outcomegradeitem->itemname = $outcome->shortname;
1695         $outcomegradeitem->itemtype = 'mod';
1696         $outcomegradeitem->itemmodule = 'assign';
1697         $outcomegradeitem->iteminstance = $assign->id;
1698         $outcomegradeitem->outcomeid = $outcome->id;
1699         $outcomegradeitem->cmid = 0;
1700         $outcomegradeitem->courseid = $course->id;
1701         $outcomegradeitem->aggregationcoef = 0;
1702         $outcomegradeitem->itemnumber = 1; // The activity's original grade item will be 0.
1703         $outcomegradeitem->gradetype = GRADE_TYPE_SCALE;
1704         $outcomegradeitem->scaleid = $outcome->scaleid;
1705         $outcomegradeitem->insert();
1707         $assignmentgradeitem = grade_item::fetch(
1708             array(
1709                 'itemtype' => 'mod',
1710                 'itemmodule' => 'assign',
1711                 'iteminstance' => $assign->id,
1712                 'itemnumber' => 0,
1713                 'courseid' => $course->id
1714             )
1715         );
1716         $outcomegradeitem->set_parent($assignmentgradeitem->categoryid);
1717         $outcomegradeitem->move_after_sortorder($assignmentgradeitem->sortorder);
1719         // Test admin user can see the complete hidden activity.
1720         $result = core_course_external::get_course_module($assign->cmid);
1721         $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
1723         $this->assertCount(0, $result['warnings']);
1724         // Test we retrieve all the fields.
1725         $this->assertCount(28, $result['cm']);
1726         $this->assertEquals($record['name'], $result['cm']['name']);
1727         $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
1728         $this->assertEquals(100, $result['cm']['grade']);
1729         $this->assertEquals(0.0, $result['cm']['gradepass']);
1730         $this->assertEquals('submissions', $result['cm']['advancedgrading'][0]['area']);
1731         $this->assertEmpty($result['cm']['advancedgrading'][0]['method']);
1732         $this->assertEquals($outcomescale, $result['cm']['outcomes'][0]['scale']);
1734         $student = $this->getDataGenerator()->create_user();
1735         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1737         self::getDataGenerator()->enrol_user($student->id,  $course->id, $studentrole->id);
1738         $this->setUser($student);
1740         // The user shouldn't be able to see the activity.
1741         try {
1742             core_course_external::get_course_module($assign->cmid);
1743             $this->fail('Exception expected due to invalid permissions.');
1744         } catch (moodle_exception $e) {
1745             $this->assertEquals('requireloginerror', $e->errorcode);
1746         }
1748         // Make module visible.
1749         set_coursemodule_visible($assign->cmid, 1);
1751         // Test student user.
1752         $result = core_course_external::get_course_module($assign->cmid);
1753         $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
1755         $this->assertCount(0, $result['warnings']);
1756         // Test we retrieve only the few files we can see.
1757         $this->assertCount(11, $result['cm']);
1758         $this->assertEquals($assign->cmid, $result['cm']['id']);
1759         $this->assertEquals($course->id, $result['cm']['course']);
1760         $this->assertEquals('assign', $result['cm']['modname']);
1761         $this->assertEquals($assign->id, $result['cm']['instance']);
1763     }
1765     /**
1766      * Test get_course_module_by_instance
1767      */
1768     public function test_get_course_module_by_instance() {
1769         global $DB;
1771         $this->resetAfterTest(true);
1773         $this->setAdminUser();
1774         $course = self::getDataGenerator()->create_course();
1775         $record = array(
1776             'course' => $course->id,
1777             'name' => 'First Chat'
1778         );
1779         $options = array(
1780             'idnumber' => 'ABC',
1781             'visible' => 0
1782         );
1783         // Hidden activity.
1784         $chat = self::getDataGenerator()->create_module('chat', $record, $options);
1786         // Test admin user can see the complete hidden activity.
1787         $result = core_course_external::get_course_module_by_instance('chat', $chat->id);
1788         $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
1790         $this->assertCount(0, $result['warnings']);
1791         // Test we retrieve all the fields.
1792         $this->assertCount(23, $result['cm']);
1793         $this->assertEquals($record['name'], $result['cm']['name']);
1794         $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
1796         $student = $this->getDataGenerator()->create_user();
1797         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1799         self::getDataGenerator()->enrol_user($student->id,  $course->id, $studentrole->id);
1800         $this->setUser($student);
1802         // The user shouldn't be able to see the activity.
1803         try {
1804             core_course_external::get_course_module_by_instance('chat', $chat->id);
1805             $this->fail('Exception expected due to invalid permissions.');
1806         } catch (moodle_exception $e) {
1807             $this->assertEquals('requireloginerror', $e->errorcode);
1808         }
1810         // Make module visible.
1811         set_coursemodule_visible($chat->cmid, 1);
1813         // Test student user.
1814         $result = core_course_external::get_course_module_by_instance('chat', $chat->id);
1815         $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
1817         $this->assertCount(0, $result['warnings']);
1818         // Test we retrieve only the few files we can see.
1819         $this->assertCount(11, $result['cm']);
1820         $this->assertEquals($chat->cmid, $result['cm']['id']);
1821         $this->assertEquals($course->id, $result['cm']['course']);
1822         $this->assertEquals('chat', $result['cm']['modname']);
1823         $this->assertEquals($chat->id, $result['cm']['instance']);
1825         // Try with an invalid module name.
1826         try {
1827             core_course_external::get_course_module_by_instance('abc', $chat->id);
1828             $this->fail('Exception expected due to invalid module name.');
1829         } catch (dml_read_exception $e) {
1830             $this->assertEquals('dmlreadexception', $e->errorcode);
1831         }
1833     }
1835     /**
1836      * Test get_activities_overview
1837      */
1838     public function test_get_activities_overview() {
1839         global $USER;
1841         $this->resetAfterTest();
1842         $course1 = self::getDataGenerator()->create_course();
1843         $course2 = self::getDataGenerator()->create_course();
1845         // Create a viewer user.
1846         $viewer = self::getDataGenerator()->create_user((object) array('trackforums' => 1));
1847         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
1848         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
1850         // Create two forums - one in each course.
1851         $record = new stdClass();
1852         $record->course = $course1->id;
1853         $forum1 = self::getDataGenerator()->create_module('forum', (object) array('course' => $course1->id));
1854         $forum2 = self::getDataGenerator()->create_module('forum', (object) array('course' => $course2->id));
1856         $this->setAdminUser();
1857         // A standard post in the forum.
1858         $record = new stdClass();
1859         $record->course = $course1->id;
1860         $record->userid = $USER->id;
1861         $record->forum = $forum1->id;
1862         $this->getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
1864         $this->setUser($viewer->id);
1865         $courses = array($course1->id , $course2->id);
1867         $result = core_course_external::get_activities_overview($courses);
1868         $this->assertDebuggingCalledCount(8);
1869         $result = external_api::clean_returnvalue(core_course_external::get_activities_overview_returns(), $result);
1871         // There should be one entry for course1, and no others.
1872         $this->assertCount(1, $result['courses']);
1873         $this->assertEquals($course1->id, $result['courses'][0]['id']);
1874         // Check expected overview data for the module.
1875         $this->assertEquals('forum', $result['courses'][0]['overviews'][0]['module']);
1876         $this->assertContains('1 total unread', $result['courses'][0]['overviews'][0]['overviewtext']);
1877     }
1879     /**
1880      * Test get_user_navigation_options
1881      */
1882     public function test_get_user_navigation_options() {
1883         global $USER;
1885         $this->resetAfterTest();
1886         $course1 = self::getDataGenerator()->create_course();
1887         $course2 = self::getDataGenerator()->create_course();
1889         // Create a viewer user.
1890         $viewer = self::getDataGenerator()->create_user();
1891         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
1892         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
1894         $this->setUser($viewer->id);
1895         $courses = array($course1->id , $course2->id, SITEID);
1897         $result = core_course_external::get_user_navigation_options($courses);
1898         $result = external_api::clean_returnvalue(core_course_external::get_user_navigation_options_returns(), $result);
1900         $this->assertCount(0, $result['warnings']);
1901         $this->assertCount(3, $result['courses']);
1903         foreach ($result['courses'] as $course) {
1904             $navoptions = new stdClass;
1905             foreach ($course['options'] as $option) {
1906                 $navoptions->{$option['name']} = $option['available'];
1907             }
1908             $this->assertCount(9, $course['options']);
1909             if ($course['id'] == SITEID) {
1910                 $this->assertTrue($navoptions->blogs);
1911                 $this->assertFalse($navoptions->notes);
1912                 $this->assertFalse($navoptions->participants);
1913                 $this->assertTrue($navoptions->badges);
1914                 $this->assertTrue($navoptions->tags);
1915                 $this->assertFalse($navoptions->grades);
1916                 $this->assertFalse($navoptions->search);
1917                 $this->assertTrue($navoptions->calendar);
1918                 $this->assertTrue($navoptions->competencies);
1919             } else {
1920                 $this->assertTrue($navoptions->blogs);
1921                 $this->assertFalse($navoptions->notes);
1922                 $this->assertTrue($navoptions->participants);
1923                 $this->assertTrue($navoptions->badges);
1924                 $this->assertFalse($navoptions->tags);
1925                 $this->assertTrue($navoptions->grades);
1926                 $this->assertFalse($navoptions->search);
1927                 $this->assertFalse($navoptions->calendar);
1928                 $this->assertTrue($navoptions->competencies);
1929             }
1930         }
1931     }
1933     /**
1934      * Test get_user_administration_options
1935      */
1936     public function test_get_user_administration_options() {
1937         global $USER;
1939         $this->resetAfterTest();
1940         $course1 = self::getDataGenerator()->create_course();
1941         $course2 = self::getDataGenerator()->create_course();
1943         // Create a viewer user.
1944         $viewer = self::getDataGenerator()->create_user();
1945         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
1946         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
1948         $this->setUser($viewer->id);
1949         $courses = array($course1->id , $course2->id, SITEID);
1951         $result = core_course_external::get_user_administration_options($courses);
1952         $result = external_api::clean_returnvalue(core_course_external::get_user_administration_options_returns(), $result);
1954         $this->assertCount(0, $result['warnings']);
1955         $this->assertCount(3, $result['courses']);
1957         foreach ($result['courses'] as $course) {
1958             $adminoptions = new stdClass;
1959             foreach ($course['options'] as $option) {
1960                 $adminoptions->{$option['name']} = $option['available'];
1961             }
1962             if ($course['id'] == SITEID) {
1963                 $this->assertCount(16, $course['options']);
1964                 $this->assertFalse($adminoptions->update);
1965                 $this->assertFalse($adminoptions->filters);
1966                 $this->assertFalse($adminoptions->reports);
1967                 $this->assertFalse($adminoptions->backup);
1968                 $this->assertFalse($adminoptions->restore);
1969                 $this->assertFalse($adminoptions->files);
1970                 $this->assertFalse(!isset($adminoptions->tags));
1971                 $this->assertFalse($adminoptions->gradebook);
1972                 $this->assertFalse($adminoptions->outcomes);
1973                 $this->assertFalse($adminoptions->badges);
1974                 $this->assertFalse($adminoptions->import);
1975                 $this->assertFalse($adminoptions->publish);
1976                 $this->assertFalse($adminoptions->reset);
1977                 $this->assertFalse($adminoptions->roles);
1978                 $this->assertFalse($adminoptions->editcompletion);
1979             } else {
1980                 $this->assertCount(15, $course['options']);
1981                 $this->assertFalse($adminoptions->update);
1982                 $this->assertFalse($adminoptions->filters);
1983                 $this->assertFalse($adminoptions->reports);
1984                 $this->assertFalse($adminoptions->backup);
1985                 $this->assertFalse($adminoptions->restore);
1986                 $this->assertFalse($adminoptions->files);
1987                 $this->assertFalse($adminoptions->tags);
1988                 $this->assertFalse($adminoptions->gradebook);
1989                 $this->assertFalse($adminoptions->outcomes);
1990                 $this->assertTrue($adminoptions->badges);
1991                 $this->assertFalse($adminoptions->import);
1992                 $this->assertFalse($adminoptions->publish);
1993                 $this->assertFalse($adminoptions->reset);
1994                 $this->assertFalse($adminoptions->roles);
1995                 $this->assertFalse($adminoptions->editcompletion);
1996             }
1997         }
1998     }
2000     /**
2001      * Test get_courses_by_fields
2002      */
2003     public function test_get_courses_by_field() {
2004         global $DB;
2005         $this->resetAfterTest(true);
2007         $category1 = self::getDataGenerator()->create_category();
2008         $category2 = self::getDataGenerator()->create_category(array('parent' => $category1->id));
2009         $course1 = self::getDataGenerator()->create_course(array('category' => $category1->id, 'shortname' => 'c1'));
2010         $course2 = self::getDataGenerator()->create_course(array('visible' => 0, 'category' => $category2->id, 'idnumber' => 'i2'));
2012         $student1 = self::getDataGenerator()->create_user();
2013         $user1 = self::getDataGenerator()->create_user();
2014         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2015         self::getDataGenerator()->enrol_user($student1->id, $course1->id, $studentrole->id);
2016         self::getDataGenerator()->enrol_user($student1->id, $course2->id, $studentrole->id);
2018         self::setAdminUser();
2019         // As admins, we should be able to retrieve everything.
2020         $result = core_course_external::get_courses_by_field();
2021         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2022         $this->assertCount(3, $result['courses']);
2023         // Expect to receive all the fields.
2024         $this->assertCount(37, $result['courses'][0]);
2025         $this->assertCount(37, $result['courses'][1]);
2026         $this->assertCount(37, $result['courses'][2]);
2028         $result = core_course_external::get_courses_by_field('id', $course1->id);
2029         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2030         $this->assertCount(1, $result['courses']);
2031         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2032         // Expect to receive all the fields.
2033         $this->assertCount(37, $result['courses'][0]);
2035         $result = core_course_external::get_courses_by_field('id', $course2->id);
2036         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2037         $this->assertCount(1, $result['courses']);
2038         $this->assertEquals($course2->id, $result['courses'][0]['id']);
2040         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2041         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2042         $this->assertCount(2, $result['courses']);
2044         // Check default filters.
2045         $this->assertCount(3, $result['courses'][0]['filters']);
2046         $this->assertCount(3, $result['courses'][1]['filters']);
2048         $result = core_course_external::get_courses_by_field('category', $category1->id);
2049         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2050         $this->assertCount(1, $result['courses']);
2051         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2053         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2054         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2055         $this->assertCount(1, $result['courses']);
2056         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2058         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2059         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2060         $this->assertCount(1, $result['courses']);
2061         $this->assertEquals($course2->id, $result['courses'][0]['id']);
2063         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2064         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2065         $this->assertCount(0, $result['courses']);
2067         // Change filter value.
2068         filter_set_local_state('mediaplugin', context_course::instance($course1->id)->id, TEXTFILTER_OFF);
2070         self::setUser($student1);
2071         // All visible courses  (including front page) for normal student.
2072         $result = core_course_external::get_courses_by_field();
2073         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2074         $this->assertCount(2, $result['courses']);
2075         $this->assertCount(30, $result['courses'][0]);
2076         $this->assertCount(30, $result['courses'][1]);
2078         $result = core_course_external::get_courses_by_field('id', $course1->id);
2079         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2080         $this->assertCount(1, $result['courses']);
2081         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2082         // Expect to receive all the files that a student can see.
2083         $this->assertCount(30, $result['courses'][0]);
2085         // Check default filters.
2086         $filters = $result['courses'][0]['filters'];
2087         $this->assertCount(3, $filters);
2088         $found = false;
2089         foreach ($filters as $filter) {
2090             if ($filter['filter'] == 'mediaplugin' and $filter['localstate'] == TEXTFILTER_OFF) {
2091                 $found = true;
2092             }
2093         }
2094         $this->assertTrue($found);
2096         // Course 2 is not visible.
2097         $result = core_course_external::get_courses_by_field('id', $course2->id);
2098         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2099         $this->assertCount(0, $result['courses']);
2101         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2102         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2103         $this->assertCount(1, $result['courses']);
2105         $result = core_course_external::get_courses_by_field('category', $category1->id);
2106         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2107         $this->assertCount(1, $result['courses']);
2108         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2110         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2111         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2112         $this->assertCount(1, $result['courses']);
2113         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2115         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2116         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2117         $this->assertCount(0, $result['courses']);
2119         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2120         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2121         $this->assertCount(0, $result['courses']);
2123         self::setUser($user1);
2124         // All visible courses (including front page) for authenticated user.
2125         $result = core_course_external::get_courses_by_field();
2126         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2127         $this->assertCount(2, $result['courses']);
2128         $this->assertCount(30, $result['courses'][0]);  // Site course.
2129         $this->assertCount(13, $result['courses'][1]);  // Only public information, not enrolled.
2131         $result = core_course_external::get_courses_by_field('id', $course1->id);
2132         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2133         $this->assertCount(1, $result['courses']);
2134         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2135         // Expect to receive all the files that a authenticated can see.
2136         $this->assertCount(13, $result['courses'][0]);
2138         // Course 2 is not visible.
2139         $result = core_course_external::get_courses_by_field('id', $course2->id);
2140         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2141         $this->assertCount(0, $result['courses']);
2143         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2144         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2145         $this->assertCount(1, $result['courses']);
2147         $result = core_course_external::get_courses_by_field('category', $category1->id);
2148         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2149         $this->assertCount(1, $result['courses']);
2150         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2152         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2153         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2154         $this->assertCount(1, $result['courses']);
2155         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2157         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2158         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2159         $this->assertCount(0, $result['courses']);
2161         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2162         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2163         $this->assertCount(0, $result['courses']);
2164     }
2166     public function test_get_courses_by_field_invalid_field() {
2167         $this->expectException('invalid_parameter_exception');
2168         $result = core_course_external::get_courses_by_field('zyx', 'x');
2169     }
2171     public function test_get_courses_by_field_invalid_courses() {
2172         $result = core_course_external::get_courses_by_field('id', '-1');
2173         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2174         $this->assertCount(0, $result['courses']);
2175     }
2177     public function test_check_updates() {
2178         global $DB;
2179         $this->resetAfterTest(true);
2180         $this->setAdminUser();
2182         // Create different types of activities.
2183         $course  = self::getDataGenerator()->create_course();
2184         $tocreate = array('assign', 'book', 'choice', 'folder', 'forum', 'glossary', 'imscp', 'label', 'lti', 'page', 'quiz',
2185                             'resource', 'scorm', 'survey', 'url', 'wiki');
2187         $modules = array();
2188         foreach ($tocreate as $modname) {
2189             $modules[$modname]['instance'] = $this->getDataGenerator()->create_module($modname, array('course' => $course->id));
2190             $modules[$modname]['cm'] = get_coursemodule_from_id(false, $modules[$modname]['instance']->cmid);
2191             $modules[$modname]['context'] = context_module::instance($modules[$modname]['instance']->cmid);
2192         }
2194         $student = self::getDataGenerator()->create_user();
2195         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2196         self::getDataGenerator()->enrol_user($student->id, $course->id, $studentrole->id);
2197         $this->setUser($student);
2199         $since = time();
2200         $this->waitForSecond();
2201         $params = array();
2202         foreach ($modules as $modname => $data) {
2203             $params[$data['cm']->id] = array(
2204                 'contextlevel' => 'module',
2205                 'id' => $data['cm']->id,
2206                 'since' => $since
2207             );
2208         }
2210         // Check there is nothing updated because modules are fresh new.
2211         $result = core_course_external::check_updates($course->id, $params);
2212         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2213         $this->assertCount(0, $result['instances']);
2214         $this->assertCount(0, $result['warnings']);
2216         // Test with get_updates_since the same data.
2217         $result = core_course_external::get_updates_since($course->id, $since);
2218         $result = external_api::clean_returnvalue(core_course_external::get_updates_since_returns(), $result);
2219         $this->assertCount(0, $result['instances']);
2220         $this->assertCount(0, $result['warnings']);
2222         // Update a module after a second.
2223         $this->waitForSecond();
2224         set_coursemodule_name($modules['forum']['cm']->id, 'New forum name');
2226         $found = false;
2227         $result = core_course_external::check_updates($course->id, $params);
2228         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2229         $this->assertCount(1, $result['instances']);
2230         $this->assertCount(0, $result['warnings']);
2231         foreach ($result['instances'] as $module) {
2232             foreach ($module['updates'] as $update) {
2233                 if ($module['id'] == $modules['forum']['cm']->id and $update['name'] == 'configuration') {
2234                     $found = true;
2235                 }
2236             }
2237         }
2238         $this->assertTrue($found);
2240         // Test with get_updates_since the same data.
2241         $result = core_course_external::get_updates_since($course->id, $since);
2242         $result = external_api::clean_returnvalue(core_course_external::get_updates_since_returns(), $result);
2243         $this->assertCount(1, $result['instances']);
2244         $this->assertCount(0, $result['warnings']);
2245         $found = false;
2246         $this->assertCount(1, $result['instances']);
2247         $this->assertCount(0, $result['warnings']);
2248         foreach ($result['instances'] as $module) {
2249             foreach ($module['updates'] as $update) {
2250                 if ($module['id'] == $modules['forum']['cm']->id and $update['name'] == 'configuration') {
2251                     $found = true;
2252                 }
2253             }
2254         }
2255         $this->assertTrue($found);
2257         // Do not retrieve the configuration field.
2258         $filter = array('files');
2259         $found = false;
2260         $result = core_course_external::check_updates($course->id, $params, $filter);
2261         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2262         $this->assertCount(0, $result['instances']);
2263         $this->assertCount(0, $result['warnings']);
2264         $this->assertFalse($found);
2266         // Add invalid cmid.
2267         $params[] = array(
2268             'contextlevel' => 'module',
2269             'id' => -2,
2270             'since' => $since
2271         );
2272         $result = core_course_external::check_updates($course->id, $params);
2273         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2274         $this->assertCount(1, $result['warnings']);
2275         $this->assertEquals(-2, $result['warnings'][0]['itemid']);
2276     }