2b6e4bdb63a875bca9cf007e111636c31b9fa116
[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 numsections
366      */
367     public function test_create_course_numsections() {
368         global $DB;
370         $this->resetAfterTest(true);
372         // Set the required capabilities by the external function.
373         $contextid = context_system::instance()->id;
374         $roleid = $this->assignUserCapability('moodle/course:create', $contextid);
375         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
377         $numsections = 10;
378         $category  = self::getDataGenerator()->create_category();
380         // Create base categories.
381         $course1['fullname'] = 'Test course 1';
382         $course1['shortname'] = 'Testcourse1';
383         $course1['categoryid'] = $category->id;
384         $course1['courseformatoptions'][] = array('name' => 'numsections', 'value' => $numsections);
386         $courses = array($course1);
388         $createdcourses = core_course_external::create_courses($courses);
389         foreach ($createdcourses as $createdcourse) {
390             $existingsections = $DB->get_records('course_sections', array('course' => $createdcourse['id']));
391             $modinfo = get_fast_modinfo($createdcourse['id']);
392             $sections = $modinfo->get_section_info_all();
393             $this->assertEquals(count($sections), $numsections + 1); // Includes generic section.
394             $this->assertEquals(count($existingsections), $numsections + 1); // Includes generic section.
395         }
396     }
398     /**
399      * Test create_courses
400      */
401     public function test_create_courses() {
402         global $DB;
404         $this->resetAfterTest(true);
406         // Enable course completion.
407         set_config('enablecompletion', 1);
408         // Enable course themes.
409         set_config('allowcoursethemes', 1);
411         // Set the required capabilities by the external function
412         $contextid = context_system::instance()->id;
413         $roleid = $this->assignUserCapability('moodle/course:create', $contextid);
414         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
416         $category  = self::getDataGenerator()->create_category();
418         // Create base categories.
419         $course1['fullname'] = 'Test course 1';
420         $course1['shortname'] = 'Testcourse1';
421         $course1['categoryid'] = $category->id;
422         $course2['fullname'] = 'Test course 2';
423         $course2['shortname'] = 'Testcourse2';
424         $course2['categoryid'] = $category->id;
425         $course2['idnumber'] = 'testcourse2idnumber';
426         $course2['summary'] = 'Description for course 2';
427         $course2['summaryformat'] = FORMAT_MOODLE;
428         $course2['format'] = 'weeks';
429         $course2['showgrades'] = 1;
430         $course2['newsitems'] = 3;
431         $course2['startdate'] = 1420092000; // 01/01/2015.
432         $course2['enddate'] = 1422669600; // 01/31/2015.
433         $course2['numsections'] = 4;
434         $course2['maxbytes'] = 100000;
435         $course2['showreports'] = 1;
436         $course2['visible'] = 0;
437         $course2['hiddensections'] = 0;
438         $course2['groupmode'] = 0;
439         $course2['groupmodeforce'] = 0;
440         $course2['defaultgroupingid'] = 0;
441         $course2['enablecompletion'] = 1;
442         $course2['completionnotify'] = 1;
443         $course2['lang'] = 'en';
444         $course2['forcetheme'] = 'bootstrapbase';
445         $course2['courseformatoptions'][] = array('name' => 'automaticenddate', 'value' => 0);
446         $course3['fullname'] = 'Test course 3';
447         $course3['shortname'] = 'Testcourse3';
448         $course3['categoryid'] = $category->id;
449         $course3['format'] = 'topics';
450         $course3options = array('numsections' => 8,
451             'hiddensections' => 1,
452             'coursedisplay' => 1);
453         $course3['courseformatoptions'] = array();
454         foreach ($course3options as $key => $value) {
455             $course3['courseformatoptions'][] = array('name' => $key, 'value' => $value);
456         }
457         $courses = array($course1, $course2, $course3);
459         $createdcourses = core_course_external::create_courses($courses);
461         // We need to execute the return values cleaning process to simulate the web service server.
462         $createdcourses = external_api::clean_returnvalue(core_course_external::create_courses_returns(), $createdcourses);
464         // Check that right number of courses were created.
465         $this->assertEquals(3, count($createdcourses));
467         // Check that the courses were correctly created.
468         foreach ($createdcourses as $createdcourse) {
469             $courseinfo = course_get_format($createdcourse['id'])->get_course();
471             if ($createdcourse['shortname'] == $course2['shortname']) {
472                 $this->assertEquals($courseinfo->fullname, $course2['fullname']);
473                 $this->assertEquals($courseinfo->shortname, $course2['shortname']);
474                 $this->assertEquals($courseinfo->category, $course2['categoryid']);
475                 $this->assertEquals($courseinfo->idnumber, $course2['idnumber']);
476                 $this->assertEquals($courseinfo->summary, $course2['summary']);
477                 $this->assertEquals($courseinfo->summaryformat, $course2['summaryformat']);
478                 $this->assertEquals($courseinfo->format, $course2['format']);
479                 $this->assertEquals($courseinfo->showgrades, $course2['showgrades']);
480                 $this->assertEquals($courseinfo->newsitems, $course2['newsitems']);
481                 $this->assertEquals($courseinfo->startdate, $course2['startdate']);
482                 $this->assertEquals($courseinfo->enddate, $course2['enddate']);
483                 $this->assertEquals(course_get_format($createdcourse['id'])->get_last_section_number(), $course2['numsections']);
484                 $this->assertEquals($courseinfo->maxbytes, $course2['maxbytes']);
485                 $this->assertEquals($courseinfo->showreports, $course2['showreports']);
486                 $this->assertEquals($courseinfo->visible, $course2['visible']);
487                 $this->assertEquals($courseinfo->hiddensections, $course2['hiddensections']);
488                 $this->assertEquals($courseinfo->groupmode, $course2['groupmode']);
489                 $this->assertEquals($courseinfo->groupmodeforce, $course2['groupmodeforce']);
490                 $this->assertEquals($courseinfo->defaultgroupingid, $course2['defaultgroupingid']);
491                 $this->assertEquals($courseinfo->completionnotify, $course2['completionnotify']);
492                 $this->assertEquals($courseinfo->lang, $course2['lang']);
493                 $this->assertEquals($courseinfo->theme, $course2['forcetheme']);
495                 // We enabled completion at the beginning of the test.
496                 $this->assertEquals($courseinfo->enablecompletion, $course2['enablecompletion']);
498             } else if ($createdcourse['shortname'] == $course1['shortname']) {
499                 $courseconfig = get_config('moodlecourse');
500                 $this->assertEquals($courseinfo->fullname, $course1['fullname']);
501                 $this->assertEquals($courseinfo->shortname, $course1['shortname']);
502                 $this->assertEquals($courseinfo->category, $course1['categoryid']);
503                 $this->assertEquals($courseinfo->summaryformat, FORMAT_HTML);
504                 $this->assertEquals($courseinfo->format, $courseconfig->format);
505                 $this->assertEquals($courseinfo->showgrades, $courseconfig->showgrades);
506                 $this->assertEquals($courseinfo->newsitems, $courseconfig->newsitems);
507                 $this->assertEquals($courseinfo->maxbytes, $courseconfig->maxbytes);
508                 $this->assertEquals($courseinfo->showreports, $courseconfig->showreports);
509                 $this->assertEquals($courseinfo->groupmode, $courseconfig->groupmode);
510                 $this->assertEquals($courseinfo->groupmodeforce, $courseconfig->groupmodeforce);
511                 $this->assertEquals($courseinfo->defaultgroupingid, 0);
512             } else if ($createdcourse['shortname'] == $course3['shortname']) {
513                 $this->assertEquals($courseinfo->fullname, $course3['fullname']);
514                 $this->assertEquals($courseinfo->shortname, $course3['shortname']);
515                 $this->assertEquals($courseinfo->category, $course3['categoryid']);
516                 $this->assertEquals($courseinfo->format, $course3['format']);
517                 $this->assertEquals($courseinfo->hiddensections, $course3options['hiddensections']);
518                 $this->assertEquals(course_get_format($createdcourse['id'])->get_last_section_number(),
519                     $course3options['numsections']);
520                 $this->assertEquals($courseinfo->coursedisplay, $course3options['coursedisplay']);
521             } else {
522                 throw new moodle_exception('Unexpected shortname');
523             }
524         }
526         // Call without required capability
527         $this->unassignUserCapability('moodle/course:create', $contextid, $roleid);
528         $this->expectException('required_capability_exception');
529         $createdsubcats = core_course_external::create_courses($courses);
530     }
532     /**
533      * Test delete_courses
534      */
535     public function test_delete_courses() {
536         global $DB, $USER;
538         $this->resetAfterTest(true);
540         // Admin can delete a course.
541         $this->setAdminUser();
542         // Validate_context() will fail as the email is not set by $this->setAdminUser().
543         $USER->email = 'emailtopass@example.com';
545         $course1  = self::getDataGenerator()->create_course();
546         $course2  = self::getDataGenerator()->create_course();
547         $course3  = self::getDataGenerator()->create_course();
549         // Delete courses.
550         $result = core_course_external::delete_courses(array($course1->id, $course2->id));
551         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
552         // Check for 0 warnings.
553         $this->assertEquals(0, count($result['warnings']));
555         // Check $course 1 and 2 are deleted.
556         $notdeletedcount = $DB->count_records_select('course',
557             'id IN ( ' . $course1->id . ',' . $course2->id . ')');
558         $this->assertEquals(0, $notdeletedcount);
560         // Try to delete non-existent course.
561         $result = core_course_external::delete_courses(array($course1->id));
562         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
563         // Check for 1 warnings.
564         $this->assertEquals(1, count($result['warnings']));
566         // Try to delete Frontpage course.
567         $result = core_course_external::delete_courses(array(0));
568         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
569         // Check for 1 warnings.
570         $this->assertEquals(1, count($result['warnings']));
572          // Fail when the user has access to course (enrolled) but does not have permission or is not admin.
573         $student1 = self::getDataGenerator()->create_user();
574         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
575         $this->getDataGenerator()->enrol_user($student1->id,
576                                               $course3->id,
577                                               $studentrole->id);
578         $this->setUser($student1);
579         $result = core_course_external::delete_courses(array($course3->id));
580         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
581         // Check for 1 warnings.
582         $this->assertEquals(1, count($result['warnings']));
584          // Fail when the user is not allow to access the course (enrolled) or is not admin.
585         $this->setGuestUser();
586         $this->expectException('require_login_exception');
588         $result = core_course_external::delete_courses(array($course3->id));
589         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
590     }
592     /**
593      * Test get_courses
594      */
595     public function test_get_courses () {
596         global $DB;
598         $this->resetAfterTest(true);
600         $generatedcourses = array();
601         $coursedata['idnumber'] = 'idnumbercourse1';
602         // Adding tags here to check that format_string is applied.
603         $coursedata['fullname'] = '<b>Course 1 for PHPunit test</b>';
604         $coursedata['shortname'] = '<b>Course 1 for PHPunit test</b>';
605         $coursedata['summary'] = 'Course 1 description';
606         $coursedata['summaryformat'] = FORMAT_MOODLE;
607         $course1  = self::getDataGenerator()->create_course($coursedata);
609         $generatedcourses[$course1->id] = $course1;
610         $course2  = self::getDataGenerator()->create_course();
611         $generatedcourses[$course2->id] = $course2;
612         $course3  = self::getDataGenerator()->create_course(array('format' => 'topics'));
613         $generatedcourses[$course3->id] = $course3;
615         // Set the required capabilities by the external function.
616         $context = context_system::instance();
617         $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
618         $this->assignUserCapability('moodle/course:update',
619                 context_course::instance($course1->id)->id, $roleid);
620         $this->assignUserCapability('moodle/course:update',
621                 context_course::instance($course2->id)->id, $roleid);
622         $this->assignUserCapability('moodle/course:update',
623                 context_course::instance($course3->id)->id, $roleid);
625         $courses = core_course_external::get_courses(array('ids' =>
626             array($course1->id, $course2->id)));
628         // We need to execute the return values cleaning process to simulate the web service server.
629         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
631         // Check we retrieve the good total number of categories.
632         $this->assertEquals(2, count($courses));
634         foreach ($courses as $course) {
635             $coursecontext = context_course::instance($course['id']);
636             $dbcourse = $generatedcourses[$course['id']];
637             $this->assertEquals($course['idnumber'], $dbcourse->idnumber);
638             $this->assertEquals($course['fullname'], external_format_string($dbcourse->fullname, $coursecontext->id));
639             $this->assertEquals($course['displayname'], external_format_string(get_course_display_name_for_list($dbcourse),
640                 $coursecontext->id));
641             // Summary was converted to the HTML format.
642             $this->assertEquals($course['summary'], format_text($dbcourse->summary, FORMAT_MOODLE, array('para' => false)));
643             $this->assertEquals($course['summaryformat'], FORMAT_HTML);
644             $this->assertEquals($course['shortname'], external_format_string($dbcourse->shortname, $coursecontext->id));
645             $this->assertEquals($course['categoryid'], $dbcourse->category);
646             $this->assertEquals($course['format'], $dbcourse->format);
647             $this->assertEquals($course['showgrades'], $dbcourse->showgrades);
648             $this->assertEquals($course['newsitems'], $dbcourse->newsitems);
649             $this->assertEquals($course['startdate'], $dbcourse->startdate);
650             $this->assertEquals($course['enddate'], $dbcourse->enddate);
651             $this->assertEquals($course['numsections'], course_get_format($dbcourse)->get_last_section_number());
652             $this->assertEquals($course['maxbytes'], $dbcourse->maxbytes);
653             $this->assertEquals($course['showreports'], $dbcourse->showreports);
654             $this->assertEquals($course['visible'], $dbcourse->visible);
655             $this->assertEquals($course['hiddensections'], $dbcourse->hiddensections);
656             $this->assertEquals($course['groupmode'], $dbcourse->groupmode);
657             $this->assertEquals($course['groupmodeforce'], $dbcourse->groupmodeforce);
658             $this->assertEquals($course['defaultgroupingid'], $dbcourse->defaultgroupingid);
659             $this->assertEquals($course['completionnotify'], $dbcourse->completionnotify);
660             $this->assertEquals($course['lang'], $dbcourse->lang);
661             $this->assertEquals($course['forcetheme'], $dbcourse->theme);
662             $this->assertEquals($course['enablecompletion'], $dbcourse->enablecompletion);
663             if ($dbcourse->format === 'topics') {
664                 $this->assertEquals($course['courseformatoptions'], array(
665                     array('name' => 'hiddensections', 'value' => $dbcourse->hiddensections),
666                     array('name' => 'coursedisplay', 'value' => $dbcourse->coursedisplay),
667                 ));
668             }
669         }
671         // Get all courses in the DB
672         $courses = core_course_external::get_courses(array());
674         // We need to execute the return values cleaning process to simulate the web service server.
675         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
677         $this->assertEquals($DB->count_records('course'), count($courses));
678     }
680     /**
681      * Test get_courses without capability
682      */
683     public function test_get_courses_without_capability() {
684         $this->resetAfterTest(true);
686         $course1 = $this->getDataGenerator()->create_course();
687         $this->setUser($this->getDataGenerator()->create_user());
689         // No permissions are required to get the site course.
690         $courses = core_course_external::get_courses(array('ids' => [SITEID]));
691         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
693         $this->assertEquals(1, count($courses));
694         $this->assertEquals('PHPUnit test site', $courses[0]['fullname']);
695         $this->assertEquals('site', $courses[0]['format']);
697         // Requesting course without being enrolled or capability to view it will throw an exception.
698         try {
699             core_course_external::get_courses(array('ids' => [$course1->id]));
700             $this->fail('Exception expected');
701         } catch (moodle_exception $e) {
702             $this->assertEquals(1, preg_match('/Course or activity not accessible. \(Not enrolled\)/', $e->getMessage()));
703         }
704     }
706     /**
707      * Test search_courses
708      */
709     public function test_search_courses () {
711         global $DB;
713         $this->resetAfterTest(true);
714         $this->setAdminUser();
715         $generatedcourses = array();
716         $coursedata1['fullname'] = 'FIRST COURSE';
717         $course1  = self::getDataGenerator()->create_course($coursedata1);
719         $page = new moodle_page();
720         $page->set_course($course1);
721         $page->blocks->add_blocks([BLOCK_POS_LEFT => ['news_items'], BLOCK_POS_RIGHT => []], 'course-view-*');
723         $coursedata2['fullname'] = 'SECOND COURSE';
724         $course2  = self::getDataGenerator()->create_course($coursedata2);
726         $page = new moodle_page();
727         $page->set_course($course2);
728         $page->blocks->add_blocks([BLOCK_POS_LEFT => ['news_items'], BLOCK_POS_RIGHT => []], 'course-view-*');
729         // Search by name.
730         $results = core_course_external::search_courses('search', 'FIRST');
731         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
732         $this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']);
733         $this->assertCount(1, $results['courses']);
735         // Create the forum.
736         $record = new stdClass();
737         $record->introformat = FORMAT_HTML;
738         $record->course = $course2->id;
739         // Set Aggregate type = Average of ratings.
740         $forum = self::getDataGenerator()->create_module('forum', $record);
742         // Search by module.
743         $results = core_course_external::search_courses('modulelist', 'forum');
744         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
745         $this->assertEquals(1, $results['total']);
747         // Enable coursetag option.
748         set_config('block_tags_showcoursetags', true);
749         // Add tag 'TAG-LABEL ON SECOND COURSE' to Course2.
750         core_tag_tag::set_item_tags('core', 'course', $course2->id, context_course::instance($course2->id),
751                 array('TAG-LABEL ON SECOND COURSE'));
752         $taginstance = $DB->get_record('tag_instance',
753                 array('itemtype' => 'course', 'itemid' => $course2->id), '*', MUST_EXIST);
754         // Search by tagid.
755         $results = core_course_external::search_courses('tagid', $taginstance->tagid);
756         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
757         $this->assertEquals($coursedata2['fullname'], $results['courses'][0]['fullname']);
759         // Search by block (use news_items default block).
760         $blockid = $DB->get_field('block', 'id', array('name' => 'news_items'));
761         $results = core_course_external::search_courses('blocklist', $blockid);
762         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
763         $this->assertEquals(2, $results['total']);
765         // Now as a normal user.
766         $user = self::getDataGenerator()->create_user();
768         // Add a 3rd, hidden, course we shouldn't see, even when enrolled as student.
769         $coursedata3['fullname'] = 'HIDDEN COURSE';
770         $coursedata3['visible'] = 0;
771         $course3  = self::getDataGenerator()->create_course($coursedata3);
772         $this->getDataGenerator()->enrol_user($user->id, $course3->id, 'student');
774         $this->getDataGenerator()->enrol_user($user->id, $course2->id, 'student');
775         $this->setUser($user);
777         $results = core_course_external::search_courses('search', 'FIRST');
778         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
779         $this->assertCount(1, $results['courses']);
780         $this->assertEquals(1, $results['total']);
781         $this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']);
783         // Check that we can see both without the limit to enrolled setting.
784         $results = core_course_external::search_courses('search', 'COURSE', 0, 0, array(), 0);
785         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
786         $this->assertCount(2, $results['courses']);
787         $this->assertEquals(2, $results['total']);
789         // Check that we only see our enrolled course when limiting.
790         $results = core_course_external::search_courses('search', 'COURSE', 0, 0, array(), 1);
791         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
792         $this->assertCount(1, $results['courses']);
793         $this->assertEquals(1, $results['total']);
794         $this->assertEquals($coursedata2['fullname'], $results['courses'][0]['fullname']);
796         // Search by block (use news_items default block). Should fail (only admins allowed).
797         $this->expectException('required_capability_exception');
798         $results = core_course_external::search_courses('blocklist', $blockid);
800     }
802     /**
803      * Create a course with contents
804      * @return array A list with the course object and course modules objects
805      */
806     private function prepare_get_course_contents_test() {
807         global $DB;
808         $course  = self::getDataGenerator()->create_course(['numsections' => 3]);
809         $forumdescription = 'This is the forum description';
810         $forum = $this->getDataGenerator()->create_module('forum',
811             array('course' => $course->id, 'intro' => $forumdescription),
812             array('showdescription' => true));
813         $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
814         $data = $this->getDataGenerator()->create_module('data', array('assessed' => 1, 'scale' => 100, 'course' => $course->id));
815         $datacm = get_coursemodule_from_instance('page', $data->id);
816         $page = $this->getDataGenerator()->create_module('page', array('course' => $course->id));
817         $pagecm = get_coursemodule_from_instance('page', $page->id);
818         $labeldescription = 'This is a very long label to test if more than 50 characters are returned.
819                 So bla bla bla bla <b>bold bold bold</b> bla bla bla bla.';
820         $label = $this->getDataGenerator()->create_module('label', array('course' => $course->id,
821             'intro' => $labeldescription));
822         $labelcm = get_coursemodule_from_instance('label', $label->id);
823         $tomorrow = time() + DAYSECS;
824         // Module with availability restrictions not met.
825         $url = $this->getDataGenerator()->create_module('url',
826             array('course' => $course->id, 'name' => 'URL: % & $ ../', 'section' => 2),
827             array('availability' => '{"op":"&","c":[{"type":"date","d":">=","t":' . $tomorrow . '}],"showc":[true]}'));
828         $urlcm = get_coursemodule_from_instance('url', $url->id);
829         // Module for the last section.
830         $this->getDataGenerator()->create_module('url',
831             array('course' => $course->id, 'name' => 'URL for last section', 'section' => 3));
832         // Module for section 1 with availability restrictions met.
833         $yesterday = time() - DAYSECS;
834         $this->getDataGenerator()->create_module('url',
835             array('course' => $course->id, 'name' => 'URL restrictions met', 'section' => 1),
836             array('availability' => '{"op":"&","c":[{"type":"date","d":">=","t":'. $yesterday .'}],"showc":[true]}'));
838         // Set the required capabilities by the external function.
839         $context = context_course::instance($course->id);
840         $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
841         $this->assignUserCapability('moodle/course:update', $context->id, $roleid);
842         $this->assignUserCapability('mod/data:view', $context->id, $roleid);
844         $conditions = array('course' => $course->id, 'section' => 2);
845         $DB->set_field('course_sections', 'summary', 'Text with iframe <iframe src="https://moodle.org"></iframe>', $conditions);
847         // Add date availability condition not met for last section.
848         $availability = '{"op":"&","c":[{"type":"date","d":">=","t":' . $tomorrow . '}],"showc":[true]}';
849         $DB->set_field('course_sections', 'availability', $availability,
850                 array('course' => $course->id, 'section' => 3));
851         rebuild_course_cache($course->id, true);
853         return array($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm);
854     }
856     /**
857      * Test get_course_contents
858      */
859     public function test_get_course_contents() {
860         $this->resetAfterTest(true);
862         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
864         $sections = core_course_external::get_course_contents($course->id, array());
865         // We need to execute the return values cleaning process to simulate the web service server.
866         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
868         $modinfo = get_fast_modinfo($course);
869         $testexecuted = 0;
870         foreach ($sections[0]['modules'] as $module) {
871             if ($module['id'] == $forumcm->id and $module['modname'] == 'forum') {
872                 $cm = $modinfo->cms[$forumcm->id];
873                 $formattedtext = format_text($cm->content, FORMAT_HTML,
874                     array('noclean' => true, 'para' => false, 'filter' => false));
875                 $this->assertEquals($formattedtext, $module['description']);
876                 $this->assertEquals($forumcm->instance, $module['instance']);
877                 $testexecuted = $testexecuted + 1;
878             } else if ($module['id'] == $labelcm->id and $module['modname'] == 'label') {
879                 $cm = $modinfo->cms[$labelcm->id];
880                 $formattedtext = format_text($cm->content, FORMAT_HTML,
881                     array('noclean' => true, 'para' => false, 'filter' => false));
882                 $this->assertEquals($formattedtext, $module['description']);
883                 $this->assertEquals($labelcm->instance, $module['instance']);
884                 $testexecuted = $testexecuted + 1;
885             }
886         }
887         $this->assertEquals(2, $testexecuted);
888         $this->assertEquals(0, $sections[0]['section']);
890         // Check that the only return section has the 5 created modules.
891         $this->assertCount(4, $sections[0]['modules']);
892         $this->assertCount(1, $sections[1]['modules']);
893         $this->assertCount(1, $sections[2]['modules']);
894         $this->assertCount(0, $sections[3]['modules']); // No modules for the section with availability restrictions.
895         $this->assertNotEmpty($sections[3]['availabilityinfo']);
896         $this->assertEquals(1, $sections[1]['section']);
897         $this->assertEquals(2, $sections[2]['section']);
898         $this->assertEquals(3, $sections[3]['section']);
899         $this->assertContains('<iframe', $sections[2]['summary']);
900         $this->assertContains('</iframe>', $sections[2]['summary']);
901         // The module with the availability restriction met is returning contents.
902         $this->assertNotEmpty($sections[1]['modules'][0]['contents']);
903         // The module with the availability restriction not met is not returning contents.
904         $this->assertArrayNotHasKey('contents', $sections[2]['modules'][0]);
905         $this->assertNotEmpty($sections[2]['modules'][0]['availabilityinfo']);
906         try {
907             $sections = core_course_external::get_course_contents($course->id,
908                                                                     array(array("name" => "invalid", "value" => 1)));
909             $this->fail('Exception expected due to invalid option.');
910         } catch (moodle_exception $e) {
911             $this->assertEquals('errorinvalidparam', $e->errorcode);
912         }
913     }
916     /**
917      * Test get_course_contents excluding modules
918      */
919     public function test_get_course_contents_excluding_modules() {
920         $this->resetAfterTest(true);
922         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
924         // Test exclude modules.
925         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludemodules", "value" => 1)));
927         // We need to execute the return values cleaning process to simulate the web service server.
928         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
930         $this->assertEmpty($sections[0]['modules']);
931         $this->assertEmpty($sections[1]['modules']);
932     }
934     /**
935      * Test get_course_contents excluding contents
936      */
937     public function test_get_course_contents_excluding_contents() {
938         $this->resetAfterTest(true);
940         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
942         // Test exclude modules.
943         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludecontents", "value" => 1)));
945         // We need to execute the return values cleaning process to simulate the web service server.
946         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
948         foreach ($sections as $section) {
949             foreach ($section['modules'] as $module) {
950                 // Only resources return contents.
951                 if (isset($module['contents'])) {
952                     $this->assertEmpty($module['contents']);
953                 }
954             }
955         }
956     }
958     /**
959      * Test get_course_contents filtering by section number
960      */
961     public function test_get_course_contents_section_number() {
962         $this->resetAfterTest(true);
964         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
966         // Test exclude modules.
967         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "sectionnumber", "value" => 0)));
969         // We need to execute the return values cleaning process to simulate the web service server.
970         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
972         $this->assertCount(1, $sections);
973         $this->assertCount(4, $sections[0]['modules']);
974     }
976     /**
977      * Test get_course_contents filtering by cmid
978      */
979     public function test_get_course_contents_cmid() {
980         $this->resetAfterTest(true);
982         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
984         // Test exclude modules.
985         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "cmid", "value" => $forumcm->id)));
987         // We need to execute the return values cleaning process to simulate the web service server.
988         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
990         $this->assertCount(4, $sections);
991         $this->assertCount(1, $sections[0]['modules']);
992         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
993     }
996     /**
997      * Test get_course_contents filtering by cmid and section
998      */
999     public function test_get_course_contents_section_cmid() {
1000         $this->resetAfterTest(true);
1002         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1004         // Test exclude modules.
1005         $sections = core_course_external::get_course_contents($course->id, array(
1006                                                                         array("name" => "cmid", "value" => $forumcm->id),
1007                                                                         array("name" => "sectionnumber", "value" => 0)
1008                                                                         ));
1010         // We need to execute the return values cleaning process to simulate the web service server.
1011         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1013         $this->assertCount(1, $sections);
1014         $this->assertCount(1, $sections[0]['modules']);
1015         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
1016     }
1018     /**
1019      * Test get_course_contents filtering by modname
1020      */
1021     public function test_get_course_contents_modname() {
1022         $this->resetAfterTest(true);
1024         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1026         // Test exclude modules.
1027         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "modname", "value" => "forum")));
1029         // We need to execute the return values cleaning process to simulate the web service server.
1030         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1032         $this->assertCount(4, $sections);
1033         $this->assertCount(1, $sections[0]['modules']);
1034         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
1035     }
1037     /**
1038      * Test get_course_contents filtering by modname
1039      */
1040     public function test_get_course_contents_modid() {
1041         $this->resetAfterTest(true);
1043         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1045         // Test exclude modules.
1046         $sections = core_course_external::get_course_contents($course->id, array(
1047                                                                             array("name" => "modname", "value" => "page"),
1048                                                                             array("name" => "modid", "value" => $pagecm->instance),
1049                                                                             ));
1051         // We need to execute the return values cleaning process to simulate the web service server.
1052         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1054         $this->assertCount(4, $sections);
1055         $this->assertCount(1, $sections[0]['modules']);
1056         $this->assertEquals("page", $sections[0]['modules'][0]["modname"]);
1057         $this->assertEquals($pagecm->instance, $sections[0]['modules'][0]["instance"]);
1058     }
1060     /**
1061      * Test duplicate_course
1062      */
1063     public function test_duplicate_course() {
1064         $this->resetAfterTest(true);
1066         // Create one course with three modules.
1067         $course  = self::getDataGenerator()->create_course();
1068         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course->id));
1069         $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
1070         $forumcontext = context_module::instance($forum->cmid);
1071         $data = $this->getDataGenerator()->create_module('data', array('assessed'=>1, 'scale'=>100, 'course'=>$course->id));
1072         $datacontext = context_module::instance($data->cmid);
1073         $datacm = get_coursemodule_from_instance('page', $data->id);
1074         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course->id));
1075         $pagecontext = context_module::instance($page->cmid);
1076         $pagecm = get_coursemodule_from_instance('page', $page->id);
1078         // Set the required capabilities by the external function.
1079         $coursecontext = context_course::instance($course->id);
1080         $categorycontext = context_coursecat::instance($course->category);
1081         $roleid = $this->assignUserCapability('moodle/course:create', $categorycontext->id);
1082         $this->assignUserCapability('moodle/course:view', $categorycontext->id, $roleid);
1083         $this->assignUserCapability('moodle/restore:restorecourse', $categorycontext->id, $roleid);
1084         $this->assignUserCapability('moodle/backup:backupcourse', $coursecontext->id, $roleid);
1085         $this->assignUserCapability('moodle/backup:configure', $coursecontext->id, $roleid);
1086         // Optional capabilities to copy user data.
1087         $this->assignUserCapability('moodle/backup:userinfo', $coursecontext->id, $roleid);
1088         $this->assignUserCapability('moodle/restore:userinfo', $categorycontext->id, $roleid);
1090         $newcourse['fullname'] = 'Course duplicate';
1091         $newcourse['shortname'] = 'courseduplicate';
1092         $newcourse['categoryid'] = $course->category;
1093         $newcourse['visible'] = true;
1094         $newcourse['options'][] = array('name' => 'users', 'value' => true);
1096         $duplicate = core_course_external::duplicate_course($course->id, $newcourse['fullname'],
1097                 $newcourse['shortname'], $newcourse['categoryid'], $newcourse['visible'], $newcourse['options']);
1099         // We need to execute the return values cleaning process to simulate the web service server.
1100         $duplicate = external_api::clean_returnvalue(core_course_external::duplicate_course_returns(), $duplicate);
1102         // Check that the course has been duplicated.
1103         $this->assertEquals($newcourse['shortname'], $duplicate['shortname']);
1104     }
1106     /**
1107      * Test update_courses
1108      */
1109     public function test_update_courses() {
1110         global $DB, $CFG, $USER, $COURSE;
1112         // Get current $COURSE to be able to restore it later (defaults to $SITE). We need this
1113         // trick because we are both updating and getting (for testing) course information
1114         // in the same request and core_course_external::update_courses()
1115         // is overwriting $COURSE all over the time with OLD values, so later
1116         // use of get_course() fetches those OLD values instead of the updated ones.
1117         // See MDL-39723 for more info.
1118         $origcourse = clone($COURSE);
1120         $this->resetAfterTest(true);
1122         // Set the required capabilities by the external function.
1123         $contextid = context_system::instance()->id;
1124         $roleid = $this->assignUserCapability('moodle/course:update', $contextid);
1125         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1126         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1127         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1128         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1129         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1130         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
1131         $this->assignUserCapability('moodle/course:viewhiddencourses', $contextid, $roleid);
1133         // Create category and course.
1134         $category1  = self::getDataGenerator()->create_category();
1135         $category2  = self::getDataGenerator()->create_category();
1136         $originalcourse1 = self::getDataGenerator()->create_course();
1137         self::getDataGenerator()->enrol_user($USER->id, $originalcourse1->id, $roleid);
1138         $originalcourse2 = self::getDataGenerator()->create_course();
1139         self::getDataGenerator()->enrol_user($USER->id, $originalcourse2->id, $roleid);
1141         // Course values to be updated.
1142         $course1['id'] = $originalcourse1->id;
1143         $course1['fullname'] = 'Updated test course 1';
1144         $course1['shortname'] = 'Udestedtestcourse1';
1145         $course1['categoryid'] = $category1->id;
1146         $course2['id'] = $originalcourse2->id;
1147         $course2['fullname'] = 'Updated test course 2';
1148         $course2['shortname'] = 'Updestedtestcourse2';
1149         $course2['categoryid'] = $category2->id;
1150         $course2['idnumber'] = 'Updatedidnumber2';
1151         $course2['summary'] = 'Updaated description for course 2';
1152         $course2['summaryformat'] = FORMAT_HTML;
1153         $course2['format'] = 'topics';
1154         $course2['showgrades'] = 1;
1155         $course2['newsitems'] = 3;
1156         $course2['startdate'] = 1420092000; // 01/01/2015.
1157         $course2['enddate'] = 1422669600; // 01/31/2015.
1158         $course2['maxbytes'] = 100000;
1159         $course2['showreports'] = 1;
1160         $course2['visible'] = 0;
1161         $course2['hiddensections'] = 0;
1162         $course2['groupmode'] = 0;
1163         $course2['groupmodeforce'] = 0;
1164         $course2['defaultgroupingid'] = 0;
1165         $course2['enablecompletion'] = 1;
1166         $course2['lang'] = 'en';
1167         $course2['forcetheme'] = 'bootstrapbase';
1168         $courses = array($course1, $course2);
1170         $updatedcoursewarnings = core_course_external::update_courses($courses);
1171         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1172                                                                     $updatedcoursewarnings);
1173         $COURSE = $origcourse; // Restore $COURSE. Instead of using the OLD one set by the previous line.
1175         // Check that right number of courses were created.
1176         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1178         // Check that the courses were correctly created.
1179         foreach ($courses as $course) {
1180             $courseinfo = course_get_format($course['id'])->get_course();
1181             if ($course['id'] == $course2['id']) {
1182                 $this->assertEquals($course2['fullname'], $courseinfo->fullname);
1183                 $this->assertEquals($course2['shortname'], $courseinfo->shortname);
1184                 $this->assertEquals($course2['categoryid'], $courseinfo->category);
1185                 $this->assertEquals($course2['idnumber'], $courseinfo->idnumber);
1186                 $this->assertEquals($course2['summary'], $courseinfo->summary);
1187                 $this->assertEquals($course2['summaryformat'], $courseinfo->summaryformat);
1188                 $this->assertEquals($course2['format'], $courseinfo->format);
1189                 $this->assertEquals($course2['showgrades'], $courseinfo->showgrades);
1190                 $this->assertEquals($course2['newsitems'], $courseinfo->newsitems);
1191                 $this->assertEquals($course2['startdate'], $courseinfo->startdate);
1192                 $this->assertEquals($course2['enddate'], $courseinfo->enddate);
1193                 $this->assertEquals($course2['maxbytes'], $courseinfo->maxbytes);
1194                 $this->assertEquals($course2['showreports'], $courseinfo->showreports);
1195                 $this->assertEquals($course2['visible'], $courseinfo->visible);
1196                 $this->assertEquals($course2['hiddensections'], $courseinfo->hiddensections);
1197                 $this->assertEquals($course2['groupmode'], $courseinfo->groupmode);
1198                 $this->assertEquals($course2['groupmodeforce'], $courseinfo->groupmodeforce);
1199                 $this->assertEquals($course2['defaultgroupingid'], $courseinfo->defaultgroupingid);
1200                 $this->assertEquals($course2['lang'], $courseinfo->lang);
1202                 if (!empty($CFG->allowcoursethemes)) {
1203                     $this->assertEquals($course2['forcetheme'], $courseinfo->theme);
1204                 }
1206                 $this->assertEquals($course2['enablecompletion'], $courseinfo->enablecompletion);
1207             } else if ($course['id'] == $course1['id']) {
1208                 $this->assertEquals($course1['fullname'], $courseinfo->fullname);
1209                 $this->assertEquals($course1['shortname'], $courseinfo->shortname);
1210                 $this->assertEquals($course1['categoryid'], $courseinfo->category);
1211                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1212                 $this->assertEquals('topics', $courseinfo->format);
1213                 $this->assertEquals(5, course_get_format($course['id'])->get_last_section_number());
1214                 $this->assertEquals(0, $courseinfo->newsitems);
1215                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1216             } else {
1217                 throw new moodle_exception('Unexpected shortname');
1218             }
1219         }
1221         $courses = array($course1);
1222         // Try update course without update capability.
1223         $user = self::getDataGenerator()->create_user();
1224         $this->setUser($user);
1225         $this->unassignUserCapability('moodle/course:update', $contextid, $roleid);
1226         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1227         $updatedcoursewarnings = core_course_external::update_courses($courses);
1228         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1229                                                                     $updatedcoursewarnings);
1230         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1232         // Try update course category without capability.
1233         $this->assignUserCapability('moodle/course:update', $contextid, $roleid);
1234         $this->unassignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1235         $user = self::getDataGenerator()->create_user();
1236         $this->setUser($user);
1237         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1238         $course1['categoryid'] = $category2->id;
1239         $courses = array($course1);
1240         $updatedcoursewarnings = core_course_external::update_courses($courses);
1241         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1242                                                                     $updatedcoursewarnings);
1243         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1245         // Try update course fullname without capability.
1246         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1247         $this->unassignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1248         $user = self::getDataGenerator()->create_user();
1249         $this->setUser($user);
1250         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1251         $updatedcoursewarnings = core_course_external::update_courses($courses);
1252         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1253                                                                     $updatedcoursewarnings);
1254         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1255         $course1['fullname'] = 'Testing fullname without permission';
1256         $courses = array($course1);
1257         $updatedcoursewarnings = core_course_external::update_courses($courses);
1258         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1259                                                                     $updatedcoursewarnings);
1260         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1262         // Try update course shortname without capability.
1263         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1264         $this->unassignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1265         $user = self::getDataGenerator()->create_user();
1266         $this->setUser($user);
1267         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1268         $updatedcoursewarnings = core_course_external::update_courses($courses);
1269         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1270                                                                     $updatedcoursewarnings);
1271         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1272         $course1['shortname'] = 'Testing shortname without permission';
1273         $courses = array($course1);
1274         $updatedcoursewarnings = core_course_external::update_courses($courses);
1275         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1276                                                                     $updatedcoursewarnings);
1277         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1279         // Try update course idnumber without capability.
1280         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1281         $this->unassignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1282         $user = self::getDataGenerator()->create_user();
1283         $this->setUser($user);
1284         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1285         $updatedcoursewarnings = core_course_external::update_courses($courses);
1286         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1287                                                                     $updatedcoursewarnings);
1288         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1289         $course1['idnumber'] = 'NEWIDNUMBER';
1290         $courses = array($course1);
1291         $updatedcoursewarnings = core_course_external::update_courses($courses);
1292         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1293                                                                     $updatedcoursewarnings);
1294         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1296         // Try update course summary without capability.
1297         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1298         $this->unassignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1299         $user = self::getDataGenerator()->create_user();
1300         $this->setUser($user);
1301         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1302         $updatedcoursewarnings = core_course_external::update_courses($courses);
1303         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1304                                                                     $updatedcoursewarnings);
1305         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1306         $course1['summary'] = 'New summary';
1307         $courses = array($course1);
1308         $updatedcoursewarnings = core_course_external::update_courses($courses);
1309         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1310                                                                     $updatedcoursewarnings);
1311         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1313         // Try update course with invalid summary format.
1314         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1315         $user = self::getDataGenerator()->create_user();
1316         $this->setUser($user);
1317         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1318         $updatedcoursewarnings = core_course_external::update_courses($courses);
1319         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1320                                                                     $updatedcoursewarnings);
1321         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1322         $course1['summaryformat'] = 10;
1323         $courses = array($course1);
1324         $updatedcoursewarnings = core_course_external::update_courses($courses);
1325         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1326                                                                     $updatedcoursewarnings);
1327         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1329         // Try update course visibility without capability.
1330         $this->unassignUserCapability('moodle/course:visibility', $contextid, $roleid);
1331         $user = self::getDataGenerator()->create_user();
1332         $this->setUser($user);
1333         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1334         $course1['summaryformat'] = FORMAT_MOODLE;
1335         $courses = array($course1);
1336         $updatedcoursewarnings = core_course_external::update_courses($courses);
1337         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1338                                                                     $updatedcoursewarnings);
1339         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1340         $course1['visible'] = 0;
1341         $courses = array($course1);
1342         $updatedcoursewarnings = core_course_external::update_courses($courses);
1343         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1344                                                                     $updatedcoursewarnings);
1345         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1346     }
1348     /**
1349      * Test delete course_module.
1350      */
1351     public function test_delete_modules() {
1352         global $DB;
1354         // Ensure we reset the data after this test.
1355         $this->resetAfterTest(true);
1357         // Create a user.
1358         $user = self::getDataGenerator()->create_user();
1360         // Set the tests to run as the user.
1361         self::setUser($user);
1363         // Create a course to add the modules.
1364         $course = self::getDataGenerator()->create_course();
1366         // Create two test modules.
1367         $record = new stdClass();
1368         $record->course = $course->id;
1369         $module1 = self::getDataGenerator()->create_module('forum', $record);
1370         $module2 = self::getDataGenerator()->create_module('assign', $record);
1372         // Check the forum was correctly created.
1373         $this->assertEquals(1, $DB->count_records('forum', array('id' => $module1->id)));
1375         // Check the assignment was correctly created.
1376         $this->assertEquals(1, $DB->count_records('assign', array('id' => $module2->id)));
1378         // Check data exists in the course modules table.
1379         $this->assertEquals(2, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1380                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1382         // Enrol the user in the course.
1383         $enrol = enrol_get_plugin('manual');
1384         $enrolinstances = enrol_get_instances($course->id, true);
1385         foreach ($enrolinstances as $courseenrolinstance) {
1386             if ($courseenrolinstance->enrol == "manual") {
1387                 $instance = $courseenrolinstance;
1388                 break;
1389             }
1390         }
1391         $enrol->enrol_user($instance, $user->id);
1393         // Assign capabilities to delete module 1.
1394         $modcontext = context_module::instance($module1->cmid);
1395         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id);
1397         // Assign capabilities to delete module 2.
1398         $modcontext = context_module::instance($module2->cmid);
1399         $newrole = create_role('Role 2', 'role2', 'Role 2 description');
1400         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id, $newrole);
1402         // Deleting these module instances.
1403         core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1405         // Check the forum was deleted.
1406         $this->assertEquals(0, $DB->count_records('forum', array('id' => $module1->id)));
1408         // Check the assignment was deleted.
1409         $this->assertEquals(0, $DB->count_records('assign', array('id' => $module2->id)));
1411         // Check we retrieve no data in the course modules table.
1412         $this->assertEquals(0, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1413                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1415         // Call with non-existent course module id and ensure exception thrown.
1416         try {
1417             core_course_external::delete_modules(array('1337'));
1418             $this->fail('Exception expected due to missing course module.');
1419         } catch (dml_missing_record_exception $e) {
1420             $this->assertEquals('invalidcoursemodule', $e->errorcode);
1421         }
1423         // Create two modules.
1424         $module1 = self::getDataGenerator()->create_module('forum', $record);
1425         $module2 = self::getDataGenerator()->create_module('assign', $record);
1427         // Since these modules were recreated the user will not have capabilities
1428         // to delete them, ensure exception is thrown if they try.
1429         try {
1430             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1431             $this->fail('Exception expected due to missing capability.');
1432         } catch (moodle_exception $e) {
1433             $this->assertEquals('nopermissions', $e->errorcode);
1434         }
1436         // Unenrol user from the course.
1437         $enrol->unenrol_user($instance, $user->id);
1439         // Try and delete modules from the course the user was unenrolled in, make sure exception thrown.
1440         try {
1441             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1442             $this->fail('Exception expected due to being unenrolled from the course.');
1443         } catch (moodle_exception $e) {
1444             $this->assertEquals('requireloginerror', $e->errorcode);
1445         }
1446     }
1448     /**
1449      * Test import_course into an empty course
1450      */
1451     public function test_import_course_empty() {
1452         global $USER;
1454         $this->resetAfterTest(true);
1456         $course1  = self::getDataGenerator()->create_course();
1457         $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course1->id, 'name' => 'Forum test'));
1458         $page = $this->getDataGenerator()->create_module('page', array('course' => $course1->id, 'name' => 'Page test'));
1460         $course2  = self::getDataGenerator()->create_course();
1462         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1463         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1465         // Verify the state of the courses before we do the import.
1466         $this->assertCount(2, $course1cms);
1467         $this->assertEmpty($course2cms);
1469         // Setup the user to run the operation (ugly hack because validate_context() will
1470         // fail as the email is not set by $this->setAdminUser()).
1471         $this->setAdminUser();
1472         $USER->email = 'emailtopass@example.com';
1474         // Import from course1 to course2.
1475         core_course_external::import_course($course1->id, $course2->id, 0);
1477         // Verify that now we have two modules in both courses.
1478         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1479         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1480         $this->assertCount(2, $course1cms);
1481         $this->assertCount(2, $course2cms);
1483         // Verify that the names transfered across correctly.
1484         foreach ($course2cms as $cm) {
1485             if ($cm->modname === 'page') {
1486                 $this->assertEquals($cm->name, $page->name);
1487             } else if ($cm->modname === 'forum') {
1488                 $this->assertEquals($cm->name, $forum->name);
1489             } else {
1490                 $this->fail('Unknown CM found.');
1491             }
1492         }
1493     }
1495     /**
1496      * Test import_course into an filled course
1497      */
1498     public function test_import_course_filled() {
1499         global $USER;
1501         $this->resetAfterTest(true);
1503         // Add forum and page to course1.
1504         $course1  = self::getDataGenerator()->create_course();
1505         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1506         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1508         // Add quiz to course 2.
1509         $course2  = self::getDataGenerator()->create_course();
1510         $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1512         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1513         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1515         // Verify the state of the courses before we do the import.
1516         $this->assertCount(2, $course1cms);
1517         $this->assertCount(1, $course2cms);
1519         // Setup the user to run the operation (ugly hack because validate_context() will
1520         // fail as the email is not set by $this->setAdminUser()).
1521         $this->setAdminUser();
1522         $USER->email = 'emailtopass@example.com';
1524         // Import from course1 to course2 without deleting content.
1525         core_course_external::import_course($course1->id, $course2->id, 0);
1527         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1529         // Verify that now we have three modules in course2.
1530         $this->assertCount(3, $course2cms);
1532         // Verify that the names transfered across correctly.
1533         foreach ($course2cms as $cm) {
1534             if ($cm->modname === 'page') {
1535                 $this->assertEquals($cm->name, $page->name);
1536             } else if ($cm->modname === 'forum') {
1537                 $this->assertEquals($cm->name, $forum->name);
1538             } else if ($cm->modname === 'quiz') {
1539                 $this->assertEquals($cm->name, $quiz->name);
1540             } else {
1541                 $this->fail('Unknown CM found.');
1542             }
1543         }
1544     }
1546     /**
1547      * Test import_course with only blocks set to backup
1548      */
1549     public function test_import_course_blocksonly() {
1550         global $USER, $DB;
1552         $this->resetAfterTest(true);
1554         // Add forum and page to course1.
1555         $course1  = self::getDataGenerator()->create_course();
1556         $course1ctx = context_course::instance($course1->id);
1557         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1558         $block = $this->getDataGenerator()->create_block('online_users', array('parentcontextid' => $course1ctx->id));
1560         $course2  = self::getDataGenerator()->create_course();
1561         $course2ctx = context_course::instance($course2->id);
1562         $initialblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1563         $initialcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1565         // Setup the user to run the operation (ugly hack because validate_context() will
1566         // fail as the email is not set by $this->setAdminUser()).
1567         $this->setAdminUser();
1568         $USER->email = 'emailtopass@example.com';
1570         // Import from course1 to course2 without deleting content, but excluding
1571         // activities.
1572         $options = array(
1573             array('name' => 'activities', 'value' => 0),
1574             array('name' => 'blocks', 'value' => 1),
1575             array('name' => 'filters', 'value' => 0),
1576         );
1578         core_course_external::import_course($course1->id, $course2->id, 0, $options);
1580         $newcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1581         $newblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1582         // Check that course modules haven't changed, but that blocks have.
1583         $this->assertEquals($initialcmcount, $newcmcount);
1584         $this->assertEquals(($initialblockcount + 1), $newblockcount);
1585     }
1587     /**
1588      * Test import_course into an filled course, deleting content.
1589      */
1590     public function test_import_course_deletecontent() {
1591         global $USER;
1592         $this->resetAfterTest(true);
1594         // Add forum and page to course1.
1595         $course1  = self::getDataGenerator()->create_course();
1596         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1597         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1599         // Add quiz to course 2.
1600         $course2  = self::getDataGenerator()->create_course();
1601         $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1603         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1604         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1606         // Verify the state of the courses before we do the import.
1607         $this->assertCount(2, $course1cms);
1608         $this->assertCount(1, $course2cms);
1610         // Setup the user to run the operation (ugly hack because validate_context() will
1611         // fail as the email is not set by $this->setAdminUser()).
1612         $this->setAdminUser();
1613         $USER->email = 'emailtopass@example.com';
1615         // Import from course1 to course2,  deleting content.
1616         core_course_external::import_course($course1->id, $course2->id, 1);
1618         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1620         // Verify that now we have two modules in course2.
1621         $this->assertCount(2, $course2cms);
1623         // Verify that the course only contains the imported modules.
1624         foreach ($course2cms as $cm) {
1625             if ($cm->modname === 'page') {
1626                 $this->assertEquals($cm->name, $page->name);
1627             } else if ($cm->modname === 'forum') {
1628                 $this->assertEquals($cm->name, $forum->name);
1629             } else {
1630                 $this->fail('Unknown CM found: '.$cm->name);
1631             }
1632         }
1633     }
1635     /**
1636      * Ensure import_course handles incorrect deletecontent option correctly.
1637      */
1638     public function test_import_course_invalid_deletecontent_option() {
1639         $this->resetAfterTest(true);
1641         $course1  = self::getDataGenerator()->create_course();
1642         $course2  = self::getDataGenerator()->create_course();
1644         $this->expectException('moodle_exception');
1645         $this->expectExceptionMessage(get_string('invalidextparam', 'webservice', -1));
1646         // Import from course1 to course2, with invalid option
1647         core_course_external::import_course($course1->id, $course2->id, -1);;
1648     }
1650     /**
1651      * Test view_course function
1652      */
1653     public function test_view_course() {
1655         $this->resetAfterTest();
1657         // Course without sections.
1658         $course = $this->getDataGenerator()->create_course(array('numsections' => 5), array('createsections' => true));
1659         $this->setAdminUser();
1661         // Redirect events to the sink, so we can recover them later.
1662         $sink = $this->redirectEvents();
1664         $result = core_course_external::view_course($course->id, 1);
1665         $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
1666         $events = $sink->get_events();
1667         $event = reset($events);
1669         // Check the event details are correct.
1670         $this->assertInstanceOf('\core\event\course_viewed', $event);
1671         $this->assertEquals(context_course::instance($course->id), $event->get_context());
1672         $this->assertEquals(1, $event->other['coursesectionnumber']);
1674         $result = core_course_external::view_course($course->id);
1675         $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
1676         $events = $sink->get_events();
1677         $event = array_pop($events);
1678         $sink->close();
1680         // Check the event details are correct.
1681         $this->assertInstanceOf('\core\event\course_viewed', $event);
1682         $this->assertEquals(context_course::instance($course->id), $event->get_context());
1683         $this->assertEmpty($event->other);
1685     }
1687     /**
1688      * Test get_course_module
1689      */
1690     public function test_get_course_module() {
1691         global $DB;
1693         $this->resetAfterTest(true);
1695         $this->setAdminUser();
1696         $course = self::getDataGenerator()->create_course();
1697         $record = array(
1698             'course' => $course->id,
1699             'name' => 'First Assignment'
1700         );
1701         $options = array(
1702             'idnumber' => 'ABC',
1703             'visible' => 0
1704         );
1705         // Hidden activity.
1706         $assign = self::getDataGenerator()->create_module('assign', $record, $options);
1708         $outcomescale = 'Distinction, Very Good, Good, Pass, Fail';
1710         // Insert a custom grade scale to be used by an outcome.
1711         $gradescale = new grade_scale();
1712         $gradescale->name        = 'gettcoursemodulescale';
1713         $gradescale->courseid    = $course->id;
1714         $gradescale->userid      = 0;
1715         $gradescale->scale       = $outcomescale;
1716         $gradescale->description = 'This scale is used to mark standard assignments.';
1717         $gradescale->insert();
1719         // Insert an outcome.
1720         $data = new stdClass();
1721         $data->courseid = $course->id;
1722         $data->fullname = 'Team work';
1723         $data->shortname = 'Team work';
1724         $data->scaleid = $gradescale->id;
1725         $outcome = new grade_outcome($data, false);
1726         $outcome->insert();
1728         $outcomegradeitem = new grade_item();
1729         $outcomegradeitem->itemname = $outcome->shortname;
1730         $outcomegradeitem->itemtype = 'mod';
1731         $outcomegradeitem->itemmodule = 'assign';
1732         $outcomegradeitem->iteminstance = $assign->id;
1733         $outcomegradeitem->outcomeid = $outcome->id;
1734         $outcomegradeitem->cmid = 0;
1735         $outcomegradeitem->courseid = $course->id;
1736         $outcomegradeitem->aggregationcoef = 0;
1737         $outcomegradeitem->itemnumber = 1; // The activity's original grade item will be 0.
1738         $outcomegradeitem->gradetype = GRADE_TYPE_SCALE;
1739         $outcomegradeitem->scaleid = $outcome->scaleid;
1740         $outcomegradeitem->insert();
1742         $assignmentgradeitem = grade_item::fetch(
1743             array(
1744                 'itemtype' => 'mod',
1745                 'itemmodule' => 'assign',
1746                 'iteminstance' => $assign->id,
1747                 'itemnumber' => 0,
1748                 'courseid' => $course->id
1749             )
1750         );
1751         $outcomegradeitem->set_parent($assignmentgradeitem->categoryid);
1752         $outcomegradeitem->move_after_sortorder($assignmentgradeitem->sortorder);
1754         // Test admin user can see the complete hidden activity.
1755         $result = core_course_external::get_course_module($assign->cmid);
1756         $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
1758         $this->assertCount(0, $result['warnings']);
1759         // Test we retrieve all the fields.
1760         $this->assertCount(28, $result['cm']);
1761         $this->assertEquals($record['name'], $result['cm']['name']);
1762         $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
1763         $this->assertEquals(100, $result['cm']['grade']);
1764         $this->assertEquals(0.0, $result['cm']['gradepass']);
1765         $this->assertEquals('submissions', $result['cm']['advancedgrading'][0]['area']);
1766         $this->assertEmpty($result['cm']['advancedgrading'][0]['method']);
1767         $this->assertEquals($outcomescale, $result['cm']['outcomes'][0]['scale']);
1769         $student = $this->getDataGenerator()->create_user();
1770         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1772         self::getDataGenerator()->enrol_user($student->id,  $course->id, $studentrole->id);
1773         $this->setUser($student);
1775         // The user shouldn't be able to see the activity.
1776         try {
1777             core_course_external::get_course_module($assign->cmid);
1778             $this->fail('Exception expected due to invalid permissions.');
1779         } catch (moodle_exception $e) {
1780             $this->assertEquals('requireloginerror', $e->errorcode);
1781         }
1783         // Make module visible.
1784         set_coursemodule_visible($assign->cmid, 1);
1786         // Test student user.
1787         $result = core_course_external::get_course_module($assign->cmid);
1788         $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
1790         $this->assertCount(0, $result['warnings']);
1791         // Test we retrieve only the few files we can see.
1792         $this->assertCount(11, $result['cm']);
1793         $this->assertEquals($assign->cmid, $result['cm']['id']);
1794         $this->assertEquals($course->id, $result['cm']['course']);
1795         $this->assertEquals('assign', $result['cm']['modname']);
1796         $this->assertEquals($assign->id, $result['cm']['instance']);
1798     }
1800     /**
1801      * Test get_course_module_by_instance
1802      */
1803     public function test_get_course_module_by_instance() {
1804         global $DB;
1806         $this->resetAfterTest(true);
1808         $this->setAdminUser();
1809         $course = self::getDataGenerator()->create_course();
1810         $record = array(
1811             'course' => $course->id,
1812             'name' => 'First quiz',
1813             'grade' => 90.00
1814         );
1815         $options = array(
1816             'idnumber' => 'ABC',
1817             'visible' => 0
1818         );
1819         // Hidden activity.
1820         $quiz = self::getDataGenerator()->create_module('quiz', $record, $options);
1822         // Test admin user can see the complete hidden activity.
1823         $result = core_course_external::get_course_module_by_instance('quiz', $quiz->id);
1824         $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
1826         $this->assertCount(0, $result['warnings']);
1827         // Test we retrieve all the fields.
1828         $this->assertCount(26, $result['cm']);
1829         $this->assertEquals($record['name'], $result['cm']['name']);
1830         $this->assertEquals($record['grade'], $result['cm']['grade']);
1831         $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
1833         $student = $this->getDataGenerator()->create_user();
1834         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1836         self::getDataGenerator()->enrol_user($student->id,  $course->id, $studentrole->id);
1837         $this->setUser($student);
1839         // The user shouldn't be able to see the activity.
1840         try {
1841             core_course_external::get_course_module_by_instance('quiz', $quiz->id);
1842             $this->fail('Exception expected due to invalid permissions.');
1843         } catch (moodle_exception $e) {
1844             $this->assertEquals('requireloginerror', $e->errorcode);
1845         }
1847         // Make module visible.
1848         set_coursemodule_visible($quiz->cmid, 1);
1850         // Test student user.
1851         $result = core_course_external::get_course_module_by_instance('quiz', $quiz->id);
1852         $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
1854         $this->assertCount(0, $result['warnings']);
1855         // Test we retrieve only the few files we can see.
1856         $this->assertCount(11, $result['cm']);
1857         $this->assertEquals($quiz->cmid, $result['cm']['id']);
1858         $this->assertEquals($course->id, $result['cm']['course']);
1859         $this->assertEquals('quiz', $result['cm']['modname']);
1860         $this->assertEquals($quiz->id, $result['cm']['instance']);
1862         // Try with an invalid module name.
1863         try {
1864             core_course_external::get_course_module_by_instance('abc', $quiz->id);
1865             $this->fail('Exception expected due to invalid module name.');
1866         } catch (dml_read_exception $e) {
1867             $this->assertEquals('dmlreadexception', $e->errorcode);
1868         }
1870     }
1872     /**
1873      * Test get_activities_overview
1874      */
1875     public function test_get_activities_overview() {
1876         global $USER;
1878         $this->resetAfterTest();
1879         $course1 = self::getDataGenerator()->create_course();
1880         $course2 = self::getDataGenerator()->create_course();
1882         // Create a viewer user.
1883         $viewer = self::getDataGenerator()->create_user((object) array('trackforums' => 1));
1884         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
1885         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
1887         // Create two forums - one in each course.
1888         $record = new stdClass();
1889         $record->course = $course1->id;
1890         $forum1 = self::getDataGenerator()->create_module('forum', (object) array('course' => $course1->id));
1891         $forum2 = self::getDataGenerator()->create_module('forum', (object) array('course' => $course2->id));
1893         $this->setAdminUser();
1894         // A standard post in the forum.
1895         $record = new stdClass();
1896         $record->course = $course1->id;
1897         $record->userid = $USER->id;
1898         $record->forum = $forum1->id;
1899         $this->getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
1901         $this->setUser($viewer->id);
1902         $courses = array($course1->id , $course2->id);
1904         $result = core_course_external::get_activities_overview($courses);
1905         $this->assertDebuggingCalledCount(8);
1906         $result = external_api::clean_returnvalue(core_course_external::get_activities_overview_returns(), $result);
1908         // There should be one entry for course1, and no others.
1909         $this->assertCount(1, $result['courses']);
1910         $this->assertEquals($course1->id, $result['courses'][0]['id']);
1911         // Check expected overview data for the module.
1912         $this->assertEquals('forum', $result['courses'][0]['overviews'][0]['module']);
1913         $this->assertContains('1 total unread', $result['courses'][0]['overviews'][0]['overviewtext']);
1914     }
1916     /**
1917      * Test get_user_navigation_options
1918      */
1919     public function test_get_user_navigation_options() {
1920         global $USER;
1922         $this->resetAfterTest();
1923         $course1 = self::getDataGenerator()->create_course();
1924         $course2 = self::getDataGenerator()->create_course();
1926         // Create a viewer user.
1927         $viewer = self::getDataGenerator()->create_user();
1928         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
1929         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
1931         $this->setUser($viewer->id);
1932         $courses = array($course1->id , $course2->id, SITEID);
1934         $result = core_course_external::get_user_navigation_options($courses);
1935         $result = external_api::clean_returnvalue(core_course_external::get_user_navigation_options_returns(), $result);
1937         $this->assertCount(0, $result['warnings']);
1938         $this->assertCount(3, $result['courses']);
1940         foreach ($result['courses'] as $course) {
1941             $navoptions = new stdClass;
1942             foreach ($course['options'] as $option) {
1943                 $navoptions->{$option['name']} = $option['available'];
1944             }
1945             $this->assertCount(9, $course['options']);
1946             if ($course['id'] == SITEID) {
1947                 $this->assertTrue($navoptions->blogs);
1948                 $this->assertFalse($navoptions->notes);
1949                 $this->assertFalse($navoptions->participants);
1950                 $this->assertTrue($navoptions->badges);
1951                 $this->assertTrue($navoptions->tags);
1952                 $this->assertFalse($navoptions->grades);
1953                 $this->assertFalse($navoptions->search);
1954                 $this->assertTrue($navoptions->calendar);
1955                 $this->assertTrue($navoptions->competencies);
1956             } else {
1957                 $this->assertTrue($navoptions->blogs);
1958                 $this->assertFalse($navoptions->notes);
1959                 $this->assertTrue($navoptions->participants);
1960                 $this->assertTrue($navoptions->badges);
1961                 $this->assertFalse($navoptions->tags);
1962                 $this->assertTrue($navoptions->grades);
1963                 $this->assertFalse($navoptions->search);
1964                 $this->assertFalse($navoptions->calendar);
1965                 $this->assertTrue($navoptions->competencies);
1966             }
1967         }
1968     }
1970     /**
1971      * Test get_user_administration_options
1972      */
1973     public function test_get_user_administration_options() {
1974         global $USER;
1976         $this->resetAfterTest();
1977         $course1 = self::getDataGenerator()->create_course();
1978         $course2 = self::getDataGenerator()->create_course();
1980         // Create a viewer user.
1981         $viewer = self::getDataGenerator()->create_user();
1982         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
1983         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
1985         $this->setUser($viewer->id);
1986         $courses = array($course1->id , $course2->id, SITEID);
1988         $result = core_course_external::get_user_administration_options($courses);
1989         $result = external_api::clean_returnvalue(core_course_external::get_user_administration_options_returns(), $result);
1991         $this->assertCount(0, $result['warnings']);
1992         $this->assertCount(3, $result['courses']);
1994         foreach ($result['courses'] as $course) {
1995             $adminoptions = new stdClass;
1996             foreach ($course['options'] as $option) {
1997                 $adminoptions->{$option['name']} = $option['available'];
1998             }
1999             if ($course['id'] == SITEID) {
2000                 $this->assertCount(16, $course['options']);
2001                 $this->assertFalse($adminoptions->update);
2002                 $this->assertFalse($adminoptions->filters);
2003                 $this->assertFalse($adminoptions->reports);
2004                 $this->assertFalse($adminoptions->backup);
2005                 $this->assertFalse($adminoptions->restore);
2006                 $this->assertFalse($adminoptions->files);
2007                 $this->assertFalse(!isset($adminoptions->tags));
2008                 $this->assertFalse($adminoptions->gradebook);
2009                 $this->assertFalse($adminoptions->outcomes);
2010                 $this->assertFalse($adminoptions->badges);
2011                 $this->assertFalse($adminoptions->import);
2012                 $this->assertFalse($adminoptions->publish);
2013                 $this->assertFalse($adminoptions->reset);
2014                 $this->assertFalse($adminoptions->roles);
2015                 $this->assertFalse($adminoptions->editcompletion);
2016             } else {
2017                 $this->assertCount(15, $course['options']);
2018                 $this->assertFalse($adminoptions->update);
2019                 $this->assertFalse($adminoptions->filters);
2020                 $this->assertFalse($adminoptions->reports);
2021                 $this->assertFalse($adminoptions->backup);
2022                 $this->assertFalse($adminoptions->restore);
2023                 $this->assertFalse($adminoptions->files);
2024                 $this->assertFalse($adminoptions->tags);
2025                 $this->assertFalse($adminoptions->gradebook);
2026                 $this->assertFalse($adminoptions->outcomes);
2027                 $this->assertTrue($adminoptions->badges);
2028                 $this->assertFalse($adminoptions->import);
2029                 $this->assertFalse($adminoptions->publish);
2030                 $this->assertFalse($adminoptions->reset);
2031                 $this->assertFalse($adminoptions->roles);
2032                 $this->assertFalse($adminoptions->editcompletion);
2033             }
2034         }
2035     }
2037     /**
2038      * Test get_courses_by_fields
2039      */
2040     public function test_get_courses_by_field() {
2041         global $DB;
2042         $this->resetAfterTest(true);
2044         $category1 = self::getDataGenerator()->create_category();
2045         $category2 = self::getDataGenerator()->create_category(array('parent' => $category1->id));
2046         $course1 = self::getDataGenerator()->create_course(array('category' => $category1->id, 'shortname' => 'c1'));
2047         $course2 = self::getDataGenerator()->create_course(array('visible' => 0, 'category' => $category2->id, 'idnumber' => 'i2'));
2049         $student1 = self::getDataGenerator()->create_user();
2050         $user1 = self::getDataGenerator()->create_user();
2051         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2052         self::getDataGenerator()->enrol_user($student1->id, $course1->id, $studentrole->id);
2053         self::getDataGenerator()->enrol_user($student1->id, $course2->id, $studentrole->id);
2055         self::setAdminUser();
2056         // As admins, we should be able to retrieve everything.
2057         $result = core_course_external::get_courses_by_field();
2058         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2059         $this->assertCount(3, $result['courses']);
2060         // Expect to receive all the fields.
2061         $this->assertCount(37, $result['courses'][0]);
2062         $this->assertCount(37, $result['courses'][1]);
2063         $this->assertCount(37, $result['courses'][2]);
2065         $result = core_course_external::get_courses_by_field('id', $course1->id);
2066         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2067         $this->assertCount(1, $result['courses']);
2068         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2069         // Expect to receive all the fields.
2070         $this->assertCount(37, $result['courses'][0]);
2072         $result = core_course_external::get_courses_by_field('id', $course2->id);
2073         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2074         $this->assertCount(1, $result['courses']);
2075         $this->assertEquals($course2->id, $result['courses'][0]['id']);
2077         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2078         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2079         $this->assertCount(2, $result['courses']);
2081         // Check default filters.
2082         $this->assertCount(3, $result['courses'][0]['filters']);
2083         $this->assertCount(3, $result['courses'][1]['filters']);
2085         $result = core_course_external::get_courses_by_field('category', $category1->id);
2086         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2087         $this->assertCount(1, $result['courses']);
2088         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2090         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2091         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2092         $this->assertCount(1, $result['courses']);
2093         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2095         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2096         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2097         $this->assertCount(1, $result['courses']);
2098         $this->assertEquals($course2->id, $result['courses'][0]['id']);
2100         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2101         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2102         $this->assertCount(0, $result['courses']);
2104         // Change filter value.
2105         filter_set_local_state('mediaplugin', context_course::instance($course1->id)->id, TEXTFILTER_OFF);
2107         self::setUser($student1);
2108         // All visible courses  (including front page) for normal student.
2109         $result = core_course_external::get_courses_by_field();
2110         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2111         $this->assertCount(2, $result['courses']);
2112         $this->assertCount(30, $result['courses'][0]);
2113         $this->assertCount(30, $result['courses'][1]);
2115         $result = core_course_external::get_courses_by_field('id', $course1->id);
2116         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2117         $this->assertCount(1, $result['courses']);
2118         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2119         // Expect to receive all the files that a student can see.
2120         $this->assertCount(30, $result['courses'][0]);
2122         // Check default filters.
2123         $filters = $result['courses'][0]['filters'];
2124         $this->assertCount(3, $filters);
2125         $found = false;
2126         foreach ($filters as $filter) {
2127             if ($filter['filter'] == 'mediaplugin' and $filter['localstate'] == TEXTFILTER_OFF) {
2128                 $found = true;
2129             }
2130         }
2131         $this->assertTrue($found);
2133         // Course 2 is not visible.
2134         $result = core_course_external::get_courses_by_field('id', $course2->id);
2135         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2136         $this->assertCount(0, $result['courses']);
2138         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2139         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2140         $this->assertCount(1, $result['courses']);
2142         $result = core_course_external::get_courses_by_field('category', $category1->id);
2143         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2144         $this->assertCount(1, $result['courses']);
2145         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2147         $result = core_course_external::get_courses_by_field('shortname', 'c1');
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('idnumber', 'i2');
2153         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2154         $this->assertCount(0, $result['courses']);
2156         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2157         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2158         $this->assertCount(0, $result['courses']);
2160         self::setUser($user1);
2161         // All visible courses (including front page) for authenticated user.
2162         $result = core_course_external::get_courses_by_field();
2163         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2164         $this->assertCount(2, $result['courses']);
2165         $this->assertCount(30, $result['courses'][0]);  // Site course.
2166         $this->assertCount(13, $result['courses'][1]);  // Only public information, not enrolled.
2168         $result = core_course_external::get_courses_by_field('id', $course1->id);
2169         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2170         $this->assertCount(1, $result['courses']);
2171         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2172         // Expect to receive all the files that a authenticated can see.
2173         $this->assertCount(13, $result['courses'][0]);
2175         // Course 2 is not visible.
2176         $result = core_course_external::get_courses_by_field('id', $course2->id);
2177         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2178         $this->assertCount(0, $result['courses']);
2180         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2181         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2182         $this->assertCount(1, $result['courses']);
2184         $result = core_course_external::get_courses_by_field('category', $category1->id);
2185         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2186         $this->assertCount(1, $result['courses']);
2187         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2189         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2190         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2191         $this->assertCount(1, $result['courses']);
2192         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2194         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2195         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2196         $this->assertCount(0, $result['courses']);
2198         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2199         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2200         $this->assertCount(0, $result['courses']);
2201     }
2203     public function test_get_courses_by_field_invalid_field() {
2204         $this->expectException('invalid_parameter_exception');
2205         $result = core_course_external::get_courses_by_field('zyx', 'x');
2206     }
2208     public function test_get_courses_by_field_invalid_courses() {
2209         $result = core_course_external::get_courses_by_field('id', '-1');
2210         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2211         $this->assertCount(0, $result['courses']);
2212     }
2214     /**
2215      * Test get_courses_by_field_invalid_theme_and_lang
2216      */
2217     public function test_get_courses_by_field_invalid_theme_and_lang() {
2218         $this->resetAfterTest(true);
2219         $this->setAdminUser();
2221         $course = self::getDataGenerator()->create_course(array('theme' => 'kkt', 'lang' => 'kkl'));
2222         $result = core_course_external::get_courses_by_field('id', $course->id);
2223         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2224         $this->assertEmpty($result['courses']['0']['theme']);
2225         $this->assertEmpty($result['courses']['0']['lang']);
2226     }
2229     public function test_check_updates() {
2230         global $DB;
2231         $this->resetAfterTest(true);
2232         $this->setAdminUser();
2234         // Create different types of activities.
2235         $course  = self::getDataGenerator()->create_course();
2236         $tocreate = array('assign', 'book', 'choice', 'folder', 'forum', 'glossary', 'imscp', 'label', 'lti', 'page', 'quiz',
2237                             'resource', 'scorm', 'survey', 'url', 'wiki');
2239         $modules = array();
2240         foreach ($tocreate as $modname) {
2241             $modules[$modname]['instance'] = $this->getDataGenerator()->create_module($modname, array('course' => $course->id));
2242             $modules[$modname]['cm'] = get_coursemodule_from_id(false, $modules[$modname]['instance']->cmid);
2243             $modules[$modname]['context'] = context_module::instance($modules[$modname]['instance']->cmid);
2244         }
2246         $student = self::getDataGenerator()->create_user();
2247         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2248         self::getDataGenerator()->enrol_user($student->id, $course->id, $studentrole->id);
2249         $this->setUser($student);
2251         $since = time();
2252         $this->waitForSecond();
2253         $params = array();
2254         foreach ($modules as $modname => $data) {
2255             $params[$data['cm']->id] = array(
2256                 'contextlevel' => 'module',
2257                 'id' => $data['cm']->id,
2258                 'since' => $since
2259             );
2260         }
2262         // Check there is nothing updated because modules are fresh new.
2263         $result = core_course_external::check_updates($course->id, $params);
2264         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2265         $this->assertCount(0, $result['instances']);
2266         $this->assertCount(0, $result['warnings']);
2268         // Test with get_updates_since the same data.
2269         $result = core_course_external::get_updates_since($course->id, $since);
2270         $result = external_api::clean_returnvalue(core_course_external::get_updates_since_returns(), $result);
2271         $this->assertCount(0, $result['instances']);
2272         $this->assertCount(0, $result['warnings']);
2274         // Update a module after a second.
2275         $this->waitForSecond();
2276         set_coursemodule_name($modules['forum']['cm']->id, 'New forum name');
2278         $found = false;
2279         $result = core_course_external::check_updates($course->id, $params);
2280         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2281         $this->assertCount(1, $result['instances']);
2282         $this->assertCount(0, $result['warnings']);
2283         foreach ($result['instances'] as $module) {
2284             foreach ($module['updates'] as $update) {
2285                 if ($module['id'] == $modules['forum']['cm']->id and $update['name'] == 'configuration') {
2286                     $found = true;
2287                 }
2288             }
2289         }
2290         $this->assertTrue($found);
2292         // Test with get_updates_since the same data.
2293         $result = core_course_external::get_updates_since($course->id, $since);
2294         $result = external_api::clean_returnvalue(core_course_external::get_updates_since_returns(), $result);
2295         $this->assertCount(1, $result['instances']);
2296         $this->assertCount(0, $result['warnings']);
2297         $found = false;
2298         $this->assertCount(1, $result['instances']);
2299         $this->assertCount(0, $result['warnings']);
2300         foreach ($result['instances'] as $module) {
2301             foreach ($module['updates'] as $update) {
2302                 if ($module['id'] == $modules['forum']['cm']->id and $update['name'] == 'configuration') {
2303                     $found = true;
2304                 }
2305             }
2306         }
2307         $this->assertTrue($found);
2309         // Do not retrieve the configuration field.
2310         $filter = array('files');
2311         $found = false;
2312         $result = core_course_external::check_updates($course->id, $params, $filter);
2313         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2314         $this->assertCount(0, $result['instances']);
2315         $this->assertCount(0, $result['warnings']);
2316         $this->assertFalse($found);
2318         // Add invalid cmid.
2319         $params[] = array(
2320             'contextlevel' => 'module',
2321             'id' => -2,
2322             'since' => $since
2323         );
2324         $result = core_course_external::check_updates($course->id, $params);
2325         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2326         $this->assertCount(1, $result['warnings']);
2327         $this->assertEquals(-2, $result['warnings'][0]['itemid']);
2328     }