MDL-63958 course: Return raw mimetype apart from description
[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);
204         $this->assignUserCapability('moodle/category:viewhiddencategories', $context->id, $roleid);
206         // Retrieve category1 + sub-categories except not visible ones
207         $categories = core_course_external::get_categories(array(
208             array('key' => 'id', 'value' => $category1->id),
209             array('key' => 'visible', 'value' => 1)), 1);
211         // We need to execute the return values cleaning process to simulate the web service server.
212         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
214         // Check we retrieve the good total number of categories.
215         $this->assertEquals(2, count($categories));
217         // Check the return values
218         foreach ($categories as $category) {
219             $generatedcat = $generatedcats[$category['id']];
220             $this->assertEquals($category['idnumber'], $generatedcat->idnumber);
221             $this->assertEquals($category['name'], $generatedcat->name);
222             // Description was converted to the HTML format.
223             $this->assertEquals($category['description'], format_text($generatedcat->description, FORMAT_MOODLE, array('para' => false)));
224             $this->assertEquals($category['descriptionformat'], FORMAT_HTML);
225         }
227         // Check categories by ids.
228         $ids = implode(',', array_keys($generatedcats));
229         $categories = core_course_external::get_categories(array(
230             array('key' => 'ids', 'value' => $ids)), 0);
232         // We need to execute the return values cleaning process to simulate the web service server.
233         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
235         // Check we retrieve the good total number of categories.
236         $this->assertEquals(6, count($categories));
237         // Check ids.
238         $returnedids = [];
239         foreach ($categories as $category) {
240             $returnedids[] = $category['id'];
241         }
242         // Sort the arrays upon comparision.
243         $this->assertEquals(array_keys($generatedcats), $returnedids, '', 0.0, 10, true);
245         // Check different params.
246         $categories = core_course_external::get_categories(array(
247             array('key' => 'id', 'value' => $category1->id),
248             array('key' => 'ids', 'value' => $category1->id),
249             array('key' => 'idnumber', 'value' => $category1->idnumber),
250             array('key' => 'visible', 'value' => 1)), 0);
252         // We need to execute the return values cleaning process to simulate the web service server.
253         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
255         $this->assertEquals(1, count($categories));
257         // Same query, but forcing a parameters clean.
258         $categories = core_course_external::get_categories(array(
259             array('key' => 'id', 'value' => "$category1->id"),
260             array('key' => 'idnumber', 'value' => $category1->idnumber),
261             array('key' => 'name', 'value' => $category1->name . "<br/>"),
262             array('key' => 'visible', 'value' => '1')), 0);
263         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
265         $this->assertEquals(1, count($categories));
267         // Retrieve categories from parent.
268         $categories = core_course_external::get_categories(array(
269             array('key' => 'parent', 'value' => $category3->id)), 1);
270         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
272         $this->assertEquals(2, count($categories));
274         // Retrieve all categories.
275         $categories = core_course_external::get_categories();
277         // We need to execute the return values cleaning process to simulate the web service server.
278         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
280         $this->assertEquals($DB->count_records('course_categories'), count($categories));
282         $this->unassignUserCapability('moodle/category:viewhiddencategories', $context->id, $roleid);
284         // Ensure maxdepthcategory is 2 and retrieve all categories without category:viewhiddencategories capability.
285         // It should retrieve all visible categories as well.
286         set_config('maxcategorydepth', 2);
287         $categories = core_course_external::get_categories();
289         // We need to execute the return values cleaning process to simulate the web service server.
290         $categories = external_api::clean_returnvalue(core_course_external::get_categories_returns(), $categories);
292         $this->assertEquals($DB->count_records('course_categories', array('visible' => 1)), count($categories));
294         // Call without required capability (it will fail cause of the search on idnumber).
295         $this->expectException('moodle_exception');
296         $categories = core_course_external::get_categories(array(
297             array('key' => 'id', 'value' => $category1->id),
298             array('key' => 'idnumber', 'value' => $category1->idnumber),
299             array('key' => 'visible', 'value' => 1)), 0);
300     }
302     /**
303      * Test update_categories
304      */
305     public function test_update_categories() {
306         global $DB;
308         $this->resetAfterTest(true);
310         // Set the required capabilities by the external function
311         $contextid = context_system::instance()->id;
312         $roleid = $this->assignUserCapability('moodle/category:manage', $contextid);
314         // Create base categories.
315         $category1data['idnumber'] = 'idnumbercat1';
316         $category1data['name'] = 'Category 1 for PHPunit test';
317         $category1data['description'] = 'Category 1 description';
318         $category1data['descriptionformat'] = FORMAT_MOODLE;
319         $category1  = self::getDataGenerator()->create_category($category1data);
320         $category2  = self::getDataGenerator()->create_category(
321                 array('parent' => $category1->id));
322         $category3  = self::getDataGenerator()->create_category();
323         $category4  = self::getDataGenerator()->create_category(
324                 array('parent' => $category3->id));
325         $category5  = self::getDataGenerator()->create_category(
326                 array('parent' => $category4->id));
328         // We update all category1 attribut.
329         // Then we move cat4 and cat5 parent: cat3 => cat1
330         $categories = array(
331             array('id' => $category1->id,
332                 'name' => $category1->name . '_updated',
333                 'idnumber' => $category1->idnumber . '_updated',
334                 'description' => $category1->description . '_updated',
335                 'descriptionformat' => FORMAT_HTML,
336                 'theme' => $category1->theme),
337             array('id' => $category4->id, 'parent' => $category1->id));
339         core_course_external::update_categories($categories);
341         // Check the values were updated.
342         $dbcategories = $DB->get_records_select('course_categories',
343                 'id IN (' . $category1->id . ',' . $category2->id . ',' . $category2->id
344                 . ',' . $category3->id . ',' . $category4->id . ',' . $category5->id .')');
345         $this->assertEquals($category1->name . '_updated',
346                 $dbcategories[$category1->id]->name);
347         $this->assertEquals($category1->idnumber . '_updated',
348                 $dbcategories[$category1->id]->idnumber);
349         $this->assertEquals($category1->description . '_updated',
350                 $dbcategories[$category1->id]->description);
351         $this->assertEquals(FORMAT_HTML, $dbcategories[$category1->id]->descriptionformat);
353         // Check that category4 and category5 have been properly moved.
354         $this->assertEquals('/' . $category1->id . '/' . $category4->id,
355                 $dbcategories[$category4->id]->path);
356         $this->assertEquals('/' . $category1->id . '/' . $category4->id . '/' . $category5->id,
357                 $dbcategories[$category5->id]->path);
359         // Call without required capability.
360         $this->unassignUserCapability('moodle/category:manage', $contextid, $roleid);
361         $this->expectException('required_capability_exception');
362         core_course_external::update_categories($categories);
363     }
365     /**
366      * Test create_courses numsections
367      */
368     public function test_create_course_numsections() {
369         global $DB;
371         $this->resetAfterTest(true);
373         // Set the required capabilities by the external function.
374         $contextid = context_system::instance()->id;
375         $roleid = $this->assignUserCapability('moodle/course:create', $contextid);
376         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
378         $numsections = 10;
379         $category  = self::getDataGenerator()->create_category();
381         // Create base categories.
382         $course1['fullname'] = 'Test course 1';
383         $course1['shortname'] = 'Testcourse1';
384         $course1['categoryid'] = $category->id;
385         $course1['courseformatoptions'][] = array('name' => 'numsections', 'value' => $numsections);
387         $courses = array($course1);
389         $createdcourses = core_course_external::create_courses($courses);
390         foreach ($createdcourses as $createdcourse) {
391             $existingsections = $DB->get_records('course_sections', array('course' => $createdcourse['id']));
392             $modinfo = get_fast_modinfo($createdcourse['id']);
393             $sections = $modinfo->get_section_info_all();
394             $this->assertEquals(count($sections), $numsections + 1); // Includes generic section.
395             $this->assertEquals(count($existingsections), $numsections + 1); // Includes generic section.
396         }
397     }
399     /**
400      * Test create_courses
401      */
402     public function test_create_courses() {
403         global $DB;
405         $this->resetAfterTest(true);
407         // Enable course completion.
408         set_config('enablecompletion', 1);
409         // Enable course themes.
410         set_config('allowcoursethemes', 1);
412         // Set the required capabilities by the external function
413         $contextid = context_system::instance()->id;
414         $roleid = $this->assignUserCapability('moodle/course:create', $contextid);
415         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
416         $this->assignUserCapability('moodle/course:setforcedlanguage', $contextid, $roleid);
418         $category  = self::getDataGenerator()->create_category();
420         // Create base categories.
421         $course1['fullname'] = 'Test course 1';
422         $course1['shortname'] = 'Testcourse1';
423         $course1['categoryid'] = $category->id;
424         $course2['fullname'] = 'Test course 2';
425         $course2['shortname'] = 'Testcourse2';
426         $course2['categoryid'] = $category->id;
427         $course2['idnumber'] = 'testcourse2idnumber';
428         $course2['summary'] = 'Description for course 2';
429         $course2['summaryformat'] = FORMAT_MOODLE;
430         $course2['format'] = 'weeks';
431         $course2['showgrades'] = 1;
432         $course2['newsitems'] = 3;
433         $course2['startdate'] = 1420092000; // 01/01/2015.
434         $course2['enddate'] = 1422669600; // 01/31/2015.
435         $course2['numsections'] = 4;
436         $course2['maxbytes'] = 100000;
437         $course2['showreports'] = 1;
438         $course2['visible'] = 0;
439         $course2['hiddensections'] = 0;
440         $course2['groupmode'] = 0;
441         $course2['groupmodeforce'] = 0;
442         $course2['defaultgroupingid'] = 0;
443         $course2['enablecompletion'] = 1;
444         $course2['completionnotify'] = 1;
445         $course2['lang'] = 'en';
446         $course2['forcetheme'] = 'bootstrapbase';
447         $course2['courseformatoptions'][] = array('name' => 'automaticenddate', 'value' => 0);
448         $course3['fullname'] = 'Test course 3';
449         $course3['shortname'] = 'Testcourse3';
450         $course3['categoryid'] = $category->id;
451         $course3['format'] = 'topics';
452         $course3options = array('numsections' => 8,
453             'hiddensections' => 1,
454             'coursedisplay' => 1);
455         $course3['courseformatoptions'] = array();
456         foreach ($course3options as $key => $value) {
457             $course3['courseformatoptions'][] = array('name' => $key, 'value' => $value);
458         }
459         $courses = array($course1, $course2, $course3);
461         $createdcourses = core_course_external::create_courses($courses);
463         // We need to execute the return values cleaning process to simulate the web service server.
464         $createdcourses = external_api::clean_returnvalue(core_course_external::create_courses_returns(), $createdcourses);
466         // Check that right number of courses were created.
467         $this->assertEquals(3, count($createdcourses));
469         // Check that the courses were correctly created.
470         foreach ($createdcourses as $createdcourse) {
471             $courseinfo = course_get_format($createdcourse['id'])->get_course();
473             if ($createdcourse['shortname'] == $course2['shortname']) {
474                 $this->assertEquals($courseinfo->fullname, $course2['fullname']);
475                 $this->assertEquals($courseinfo->shortname, $course2['shortname']);
476                 $this->assertEquals($courseinfo->category, $course2['categoryid']);
477                 $this->assertEquals($courseinfo->idnumber, $course2['idnumber']);
478                 $this->assertEquals($courseinfo->summary, $course2['summary']);
479                 $this->assertEquals($courseinfo->summaryformat, $course2['summaryformat']);
480                 $this->assertEquals($courseinfo->format, $course2['format']);
481                 $this->assertEquals($courseinfo->showgrades, $course2['showgrades']);
482                 $this->assertEquals($courseinfo->newsitems, $course2['newsitems']);
483                 $this->assertEquals($courseinfo->startdate, $course2['startdate']);
484                 $this->assertEquals($courseinfo->enddate, $course2['enddate']);
485                 $this->assertEquals(course_get_format($createdcourse['id'])->get_last_section_number(), $course2['numsections']);
486                 $this->assertEquals($courseinfo->maxbytes, $course2['maxbytes']);
487                 $this->assertEquals($courseinfo->showreports, $course2['showreports']);
488                 $this->assertEquals($courseinfo->visible, $course2['visible']);
489                 $this->assertEquals($courseinfo->hiddensections, $course2['hiddensections']);
490                 $this->assertEquals($courseinfo->groupmode, $course2['groupmode']);
491                 $this->assertEquals($courseinfo->groupmodeforce, $course2['groupmodeforce']);
492                 $this->assertEquals($courseinfo->defaultgroupingid, $course2['defaultgroupingid']);
493                 $this->assertEquals($courseinfo->completionnotify, $course2['completionnotify']);
494                 $this->assertEquals($courseinfo->lang, $course2['lang']);
495                 $this->assertEquals($courseinfo->theme, $course2['forcetheme']);
497                 // We enabled completion at the beginning of the test.
498                 $this->assertEquals($courseinfo->enablecompletion, $course2['enablecompletion']);
500             } else if ($createdcourse['shortname'] == $course1['shortname']) {
501                 $courseconfig = get_config('moodlecourse');
502                 $this->assertEquals($courseinfo->fullname, $course1['fullname']);
503                 $this->assertEquals($courseinfo->shortname, $course1['shortname']);
504                 $this->assertEquals($courseinfo->category, $course1['categoryid']);
505                 $this->assertEquals($courseinfo->summaryformat, FORMAT_HTML);
506                 $this->assertEquals($courseinfo->format, $courseconfig->format);
507                 $this->assertEquals($courseinfo->showgrades, $courseconfig->showgrades);
508                 $this->assertEquals($courseinfo->newsitems, $courseconfig->newsitems);
509                 $this->assertEquals($courseinfo->maxbytes, $courseconfig->maxbytes);
510                 $this->assertEquals($courseinfo->showreports, $courseconfig->showreports);
511                 $this->assertEquals($courseinfo->groupmode, $courseconfig->groupmode);
512                 $this->assertEquals($courseinfo->groupmodeforce, $courseconfig->groupmodeforce);
513                 $this->assertEquals($courseinfo->defaultgroupingid, 0);
514             } else if ($createdcourse['shortname'] == $course3['shortname']) {
515                 $this->assertEquals($courseinfo->fullname, $course3['fullname']);
516                 $this->assertEquals($courseinfo->shortname, $course3['shortname']);
517                 $this->assertEquals($courseinfo->category, $course3['categoryid']);
518                 $this->assertEquals($courseinfo->format, $course3['format']);
519                 $this->assertEquals($courseinfo->hiddensections, $course3options['hiddensections']);
520                 $this->assertEquals(course_get_format($createdcourse['id'])->get_last_section_number(),
521                     $course3options['numsections']);
522                 $this->assertEquals($courseinfo->coursedisplay, $course3options['coursedisplay']);
523             } else {
524                 throw new moodle_exception('Unexpected shortname');
525             }
526         }
528         // Call without required capability
529         $this->unassignUserCapability('moodle/course:create', $contextid, $roleid);
530         $this->expectException('required_capability_exception');
531         $createdsubcats = core_course_external::create_courses($courses);
532     }
534     /**
535      * Test delete_courses
536      */
537     public function test_delete_courses() {
538         global $DB, $USER;
540         $this->resetAfterTest(true);
542         // Admin can delete a course.
543         $this->setAdminUser();
544         // Validate_context() will fail as the email is not set by $this->setAdminUser().
545         $USER->email = 'emailtopass@example.com';
547         $course1  = self::getDataGenerator()->create_course();
548         $course2  = self::getDataGenerator()->create_course();
549         $course3  = self::getDataGenerator()->create_course();
551         // Delete courses.
552         $result = core_course_external::delete_courses(array($course1->id, $course2->id));
553         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
554         // Check for 0 warnings.
555         $this->assertEquals(0, count($result['warnings']));
557         // Check $course 1 and 2 are deleted.
558         $notdeletedcount = $DB->count_records_select('course',
559             'id IN ( ' . $course1->id . ',' . $course2->id . ')');
560         $this->assertEquals(0, $notdeletedcount);
562         // Try to delete non-existent course.
563         $result = core_course_external::delete_courses(array($course1->id));
564         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
565         // Check for 1 warnings.
566         $this->assertEquals(1, count($result['warnings']));
568         // Try to delete Frontpage course.
569         $result = core_course_external::delete_courses(array(0));
570         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
571         // Check for 1 warnings.
572         $this->assertEquals(1, count($result['warnings']));
574          // Fail when the user has access to course (enrolled) but does not have permission or is not admin.
575         $student1 = self::getDataGenerator()->create_user();
576         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
577         $this->getDataGenerator()->enrol_user($student1->id,
578                                               $course3->id,
579                                               $studentrole->id);
580         $this->setUser($student1);
581         $result = core_course_external::delete_courses(array($course3->id));
582         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
583         // Check for 1 warnings.
584         $this->assertEquals(1, count($result['warnings']));
586          // Fail when the user is not allow to access the course (enrolled) or is not admin.
587         $this->setGuestUser();
588         $this->expectException('require_login_exception');
590         $result = core_course_external::delete_courses(array($course3->id));
591         $result = external_api::clean_returnvalue(core_course_external::delete_courses_returns(), $result);
592     }
594     /**
595      * Test get_courses
596      */
597     public function test_get_courses () {
598         global $DB;
600         $this->resetAfterTest(true);
602         $generatedcourses = array();
603         $coursedata['idnumber'] = 'idnumbercourse1';
604         // Adding tags here to check that format_string is applied.
605         $coursedata['fullname'] = '<b>Course 1 for PHPunit test</b>';
606         $coursedata['shortname'] = '<b>Course 1 for PHPunit test</b>';
607         $coursedata['summary'] = 'Course 1 description';
608         $coursedata['summaryformat'] = FORMAT_MOODLE;
609         $course1  = self::getDataGenerator()->create_course($coursedata);
611         $generatedcourses[$course1->id] = $course1;
612         $course2  = self::getDataGenerator()->create_course();
613         $generatedcourses[$course2->id] = $course2;
614         $course3  = self::getDataGenerator()->create_course(array('format' => 'topics'));
615         $generatedcourses[$course3->id] = $course3;
617         // Set the required capabilities by the external function.
618         $context = context_system::instance();
619         $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
620         $this->assignUserCapability('moodle/course:update',
621                 context_course::instance($course1->id)->id, $roleid);
622         $this->assignUserCapability('moodle/course:update',
623                 context_course::instance($course2->id)->id, $roleid);
624         $this->assignUserCapability('moodle/course:update',
625                 context_course::instance($course3->id)->id, $roleid);
627         $courses = core_course_external::get_courses(array('ids' =>
628             array($course1->id, $course2->id)));
630         // We need to execute the return values cleaning process to simulate the web service server.
631         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
633         // Check we retrieve the good total number of categories.
634         $this->assertEquals(2, count($courses));
636         foreach ($courses as $course) {
637             $coursecontext = context_course::instance($course['id']);
638             $dbcourse = $generatedcourses[$course['id']];
639             $this->assertEquals($course['idnumber'], $dbcourse->idnumber);
640             $this->assertEquals($course['fullname'], external_format_string($dbcourse->fullname, $coursecontext->id));
641             $this->assertEquals($course['displayname'], external_format_string(get_course_display_name_for_list($dbcourse),
642                 $coursecontext->id));
643             // Summary was converted to the HTML format.
644             $this->assertEquals($course['summary'], format_text($dbcourse->summary, FORMAT_MOODLE, array('para' => false)));
645             $this->assertEquals($course['summaryformat'], FORMAT_HTML);
646             $this->assertEquals($course['shortname'], external_format_string($dbcourse->shortname, $coursecontext->id));
647             $this->assertEquals($course['categoryid'], $dbcourse->category);
648             $this->assertEquals($course['format'], $dbcourse->format);
649             $this->assertEquals($course['showgrades'], $dbcourse->showgrades);
650             $this->assertEquals($course['newsitems'], $dbcourse->newsitems);
651             $this->assertEquals($course['startdate'], $dbcourse->startdate);
652             $this->assertEquals($course['enddate'], $dbcourse->enddate);
653             $this->assertEquals($course['numsections'], course_get_format($dbcourse)->get_last_section_number());
654             $this->assertEquals($course['maxbytes'], $dbcourse->maxbytes);
655             $this->assertEquals($course['showreports'], $dbcourse->showreports);
656             $this->assertEquals($course['visible'], $dbcourse->visible);
657             $this->assertEquals($course['hiddensections'], $dbcourse->hiddensections);
658             $this->assertEquals($course['groupmode'], $dbcourse->groupmode);
659             $this->assertEquals($course['groupmodeforce'], $dbcourse->groupmodeforce);
660             $this->assertEquals($course['defaultgroupingid'], $dbcourse->defaultgroupingid);
661             $this->assertEquals($course['completionnotify'], $dbcourse->completionnotify);
662             $this->assertEquals($course['lang'], $dbcourse->lang);
663             $this->assertEquals($course['forcetheme'], $dbcourse->theme);
664             $this->assertEquals($course['enablecompletion'], $dbcourse->enablecompletion);
665             if ($dbcourse->format === 'topics') {
666                 $this->assertEquals($course['courseformatoptions'], array(
667                     array('name' => 'hiddensections', 'value' => $dbcourse->hiddensections),
668                     array('name' => 'coursedisplay', 'value' => $dbcourse->coursedisplay),
669                 ));
670             }
671         }
673         // Get all courses in the DB
674         $courses = core_course_external::get_courses(array());
676         // We need to execute the return values cleaning process to simulate the web service server.
677         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
679         $this->assertEquals($DB->count_records('course'), count($courses));
680     }
682     /**
683      * Test get_courses without capability
684      */
685     public function test_get_courses_without_capability() {
686         $this->resetAfterTest(true);
688         $course1 = $this->getDataGenerator()->create_course();
689         $this->setUser($this->getDataGenerator()->create_user());
691         // No permissions are required to get the site course.
692         $courses = core_course_external::get_courses(array('ids' => [SITEID]));
693         $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses);
695         $this->assertEquals(1, count($courses));
696         $this->assertEquals('PHPUnit test site', $courses[0]['fullname']);
697         $this->assertEquals('site', $courses[0]['format']);
699         // Requesting course without being enrolled or capability to view it will throw an exception.
700         try {
701             core_course_external::get_courses(array('ids' => [$course1->id]));
702             $this->fail('Exception expected');
703         } catch (moodle_exception $e) {
704             $this->assertEquals(1, preg_match('/Course or activity not accessible. \(Not enrolled\)/', $e->getMessage()));
705         }
706     }
708     /**
709      * Test search_courses
710      */
711     public function test_search_courses () {
713         global $DB;
715         $this->resetAfterTest(true);
716         $this->setAdminUser();
717         $generatedcourses = array();
718         $coursedata1['fullname'] = 'FIRST COURSE';
719         $course1  = self::getDataGenerator()->create_course($coursedata1);
721         $page = new moodle_page();
722         $page->set_course($course1);
723         $page->blocks->add_blocks([BLOCK_POS_LEFT => ['news_items'], BLOCK_POS_RIGHT => []], 'course-view-*');
725         $coursedata2['fullname'] = 'SECOND COURSE';
726         $course2  = self::getDataGenerator()->create_course($coursedata2);
728         $page = new moodle_page();
729         $page->set_course($course2);
730         $page->blocks->add_blocks([BLOCK_POS_LEFT => ['news_items'], BLOCK_POS_RIGHT => []], 'course-view-*');
731         // Search by name.
732         $results = core_course_external::search_courses('search', 'FIRST');
733         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
734         $this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']);
735         $this->assertCount(1, $results['courses']);
737         // Create the forum.
738         $record = new stdClass();
739         $record->introformat = FORMAT_HTML;
740         $record->course = $course2->id;
741         // Set Aggregate type = Average of ratings.
742         $forum = self::getDataGenerator()->create_module('forum', $record);
744         // Search by module.
745         $results = core_course_external::search_courses('modulelist', 'forum');
746         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
747         $this->assertEquals(1, $results['total']);
749         // Enable coursetag option.
750         set_config('block_tags_showcoursetags', true);
751         // Add tag 'TAG-LABEL ON SECOND COURSE' to Course2.
752         core_tag_tag::set_item_tags('core', 'course', $course2->id, context_course::instance($course2->id),
753                 array('TAG-LABEL ON SECOND COURSE'));
754         $taginstance = $DB->get_record('tag_instance',
755                 array('itemtype' => 'course', 'itemid' => $course2->id), '*', MUST_EXIST);
756         // Search by tagid.
757         $results = core_course_external::search_courses('tagid', $taginstance->tagid);
758         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
759         $this->assertEquals($coursedata2['fullname'], $results['courses'][0]['fullname']);
761         // Search by block (use news_items default block).
762         $blockid = $DB->get_field('block', 'id', array('name' => 'news_items'));
763         $results = core_course_external::search_courses('blocklist', $blockid);
764         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
765         $this->assertEquals(2, $results['total']);
767         // Now as a normal user.
768         $user = self::getDataGenerator()->create_user();
770         // Add a 3rd, hidden, course we shouldn't see, even when enrolled as student.
771         $coursedata3['fullname'] = 'HIDDEN COURSE';
772         $coursedata3['visible'] = 0;
773         $course3  = self::getDataGenerator()->create_course($coursedata3);
774         $this->getDataGenerator()->enrol_user($user->id, $course3->id, 'student');
776         $this->getDataGenerator()->enrol_user($user->id, $course2->id, 'student');
777         $this->setUser($user);
779         $results = core_course_external::search_courses('search', 'FIRST');
780         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
781         $this->assertCount(1, $results['courses']);
782         $this->assertEquals(1, $results['total']);
783         $this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']);
785         // Check that we can see both without the limit to enrolled setting.
786         $results = core_course_external::search_courses('search', 'COURSE', 0, 0, array(), 0);
787         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
788         $this->assertCount(2, $results['courses']);
789         $this->assertEquals(2, $results['total']);
791         // Check that we only see our enrolled course when limiting.
792         $results = core_course_external::search_courses('search', 'COURSE', 0, 0, array(), 1);
793         $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results);
794         $this->assertCount(1, $results['courses']);
795         $this->assertEquals(1, $results['total']);
796         $this->assertEquals($coursedata2['fullname'], $results['courses'][0]['fullname']);
798         // Search by block (use news_items default block). Should fail (only admins allowed).
799         $this->expectException('required_capability_exception');
800         $results = core_course_external::search_courses('blocklist', $blockid);
802     }
804     /**
805      * Create a course with contents
806      * @return array A list with the course object and course modules objects
807      */
808     private function prepare_get_course_contents_test() {
809         global $DB, $CFG;
811         $CFG->allowstealth = 1; // Allow stealth activities.
812         $CFG->enablecompletion = true;
813         $course  = self::getDataGenerator()->create_course(['numsections' => 4, 'enablecompletion' => 1]);
815         $forumdescription = 'This is the forum description';
816         $forum = $this->getDataGenerator()->create_module('forum',
817             array('course' => $course->id, 'intro' => $forumdescription, 'trackingtype' => 2),
818             array('showdescription' => true, 'completion' => COMPLETION_TRACKING_MANUAL));
819         $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
820         // Add discussions to the tracking forced forum.
821         $record = new stdClass();
822         $record->course = $course->id;
823         $record->userid = 0;
824         $record->forum = $forum->id;
825         $discussionforce = $this->getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
826         $data = $this->getDataGenerator()->create_module('data',
827             array('assessed' => 1, 'scale' => 100, 'course' => $course->id, 'completion' => 2, 'completionentries' => 3));
828         $datacm = get_coursemodule_from_instance('data', $data->id);
829         $page = $this->getDataGenerator()->create_module('page', array('course' => $course->id));
830         $pagecm = get_coursemodule_from_instance('page', $page->id);
831         // This is an stealth page (set by visibleoncoursepage).
832         $pagestealth = $this->getDataGenerator()->create_module('page', array('course' => $course->id, 'visibleoncoursepage' => 0));
833         $labeldescription = 'This is a very long label to test if more than 50 characters are returned.
834                 So bla bla bla bla <b>bold bold bold</b> bla bla bla bla.';
835         $label = $this->getDataGenerator()->create_module('label', array('course' => $course->id,
836             'intro' => $labeldescription));
837         $labelcm = get_coursemodule_from_instance('label', $label->id);
838         $tomorrow = time() + DAYSECS;
839         // Module with availability restrictions not met.
840         $url = $this->getDataGenerator()->create_module('url',
841             array('course' => $course->id, 'name' => 'URL: % & $ ../', 'section' => 2, 'display' => RESOURCELIB_DISPLAY_POPUP,
842                 'popupwidth' => 100, 'popupheight' => 100),
843             array('availability' => '{"op":"&","c":[{"type":"date","d":">=","t":' . $tomorrow . '}],"showc":[true]}'));
844         $urlcm = get_coursemodule_from_instance('url', $url->id);
845         // Module for the last section.
846         $this->getDataGenerator()->create_module('url',
847             array('course' => $course->id, 'name' => 'URL for last section', 'section' => 3));
848         // Module for section 1 with availability restrictions met.
849         $yesterday = time() - DAYSECS;
850         $this->getDataGenerator()->create_module('url',
851             array('course' => $course->id, 'name' => 'URL restrictions met', 'section' => 1),
852             array('availability' => '{"op":"&","c":[{"type":"date","d":">=","t":'. $yesterday .'}],"showc":[true]}'));
854         // Set the required capabilities by the external function.
855         $context = context_course::instance($course->id);
856         $roleid = $this->assignUserCapability('moodle/course:view', $context->id);
857         $this->assignUserCapability('moodle/course:update', $context->id, $roleid);
858         $this->assignUserCapability('mod/data:view', $context->id, $roleid);
860         $conditions = array('course' => $course->id, 'section' => 2);
861         $DB->set_field('course_sections', 'summary', 'Text with iframe <iframe src="https://moodle.org"></iframe>', $conditions);
863         // Add date availability condition not met for section 3.
864         $availability = '{"op":"&","c":[{"type":"date","d":">=","t":' . $tomorrow . '}],"showc":[true]}';
865         $DB->set_field('course_sections', 'availability', $availability,
866                 array('course' => $course->id, 'section' => 3));
868         // Create resource for last section.
869         $pageinhiddensection = $this->getDataGenerator()->create_module('page',
870             array('course' => $course->id, 'name' => 'Page in hidden section', 'section' => 4));
871         // Set not visible last section.
872         $DB->set_field('course_sections', 'visible', 0,
873                 array('course' => $course->id, 'section' => 4));
875         rebuild_course_cache($course->id, true);
877         return array($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm);
878     }
880     /**
881      * Test get_course_contents
882      */
883     public function test_get_course_contents() {
884         global $CFG;
885         $this->resetAfterTest(true);
887         $CFG->forum_allowforcedreadtracking = 1;
888         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
890         // We first run the test as admin.
891         $this->setAdminUser();
892         $sections = core_course_external::get_course_contents($course->id, array());
893         // We need to execute the return values cleaning process to simulate the web service server.
894         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
896         $modinfo = get_fast_modinfo($course);
897         $testexecuted = 0;
898         foreach ($sections[0]['modules'] as $module) {
899             if ($module['id'] == $forumcm->id and $module['modname'] == 'forum') {
900                 $cm = $modinfo->cms[$forumcm->id];
901                 $formattedtext = format_text($cm->content, FORMAT_HTML,
902                     array('noclean' => true, 'para' => false, 'filter' => false));
903                 $this->assertEquals($formattedtext, $module['description']);
904                 $this->assertEquals($forumcm->instance, $module['instance']);
905                 $this->assertContains('1 unread post', $module['afterlink']);
906                 $testexecuted = $testexecuted + 2;
907             } else if ($module['id'] == $labelcm->id and $module['modname'] == 'label') {
908                 $cm = $modinfo->cms[$labelcm->id];
909                 $formattedtext = format_text($cm->content, FORMAT_HTML,
910                     array('noclean' => true, 'para' => false, 'filter' => false));
911                 $this->assertEquals($formattedtext, $module['description']);
912                 $this->assertEquals($labelcm->instance, $module['instance']);
913                 $testexecuted = $testexecuted + 1;
914             } else if ($module['id'] == $datacm->id and $module['modname'] == 'data') {
915                 $this->assertContains('customcompletionrules', $module['customdata']);
916                 $testexecuted = $testexecuted + 1;
917             }
918         }
919         foreach ($sections[2]['modules'] as $module) {
920             if ($module['id'] == $urlcm->id and $module['modname'] == 'url') {
921                 $this->assertContains('width=100,height=100', $module['onclick']);
922                 $testexecuted = $testexecuted + 1;
923             }
924         }
926         $CFG->forum_allowforcedreadtracking = 0;    // Recover original value.
927         forum_tp_count_forum_unread_posts($forumcm, $course, true);    // Reset static cache for further tests.
929         $this->assertEquals(5, $testexecuted);
930         $this->assertEquals(0, $sections[0]['section']);
932         $this->assertCount(5, $sections[0]['modules']);
933         $this->assertCount(1, $sections[1]['modules']);
934         $this->assertCount(1, $sections[2]['modules']);
935         $this->assertCount(1, $sections[3]['modules']); // One module for the section with availability restrictions.
936         $this->assertCount(1, $sections[4]['modules']); // One module for the hidden section with a visible activity.
937         $this->assertNotEmpty($sections[3]['availabilityinfo']);
938         $this->assertEquals(1, $sections[1]['section']);
939         $this->assertEquals(2, $sections[2]['section']);
940         $this->assertEquals(3, $sections[3]['section']);
941         $this->assertEquals(4, $sections[4]['section']);
942         $this->assertContains('<iframe', $sections[2]['summary']);
943         $this->assertContains('</iframe>', $sections[2]['summary']);
944         $this->assertNotEmpty($sections[2]['modules'][0]['availabilityinfo']);
945         try {
946             $sections = core_course_external::get_course_contents($course->id,
947                                                                     array(array("name" => "invalid", "value" => 1)));
948             $this->fail('Exception expected due to invalid option.');
949         } catch (moodle_exception $e) {
950             $this->assertEquals('errorinvalidparam', $e->errorcode);
951         }
952     }
955     /**
956      * Test get_course_contents as student
957      */
958     public function test_get_course_contents_student() {
959         global $DB;
960         $this->resetAfterTest(true);
962         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
964         $studentroleid = $DB->get_field('role', 'id', array('shortname' => 'student'));
965         $user = self::getDataGenerator()->create_user();
966         self::getDataGenerator()->enrol_user($user->id, $course->id, $studentroleid);
967         $this->setUser($user);
969         $sections = core_course_external::get_course_contents($course->id, array());
970         // We need to execute the return values cleaning process to simulate the web service server.
971         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
973         $this->assertCount(4, $sections); // Nothing for the not visible section.
974         $this->assertCount(5, $sections[0]['modules']);
975         $this->assertCount(1, $sections[1]['modules']);
976         $this->assertCount(1, $sections[2]['modules']);
977         $this->assertCount(0, $sections[3]['modules']); // No modules for the section with availability restrictions.
979         $this->assertNotEmpty($sections[3]['availabilityinfo']);
980         $this->assertEquals(1, $sections[1]['section']);
981         $this->assertEquals(2, $sections[2]['section']);
982         $this->assertEquals(3, $sections[3]['section']);
983         // The module with the availability restriction met is returning contents.
984         $this->assertNotEmpty($sections[1]['modules'][0]['contents']);
985         // The module with the availability restriction not met is not returning contents.
986         $this->assertArrayNotHasKey('contents', $sections[2]['modules'][0]);
988         // Now include flag for returning stealth information (fake section).
989         $sections = core_course_external::get_course_contents($course->id,
990             array(array("name" => "includestealthmodules", "value" => 1)));
991         // We need to execute the return values cleaning process to simulate the web service server.
992         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
994         $this->assertCount(5, $sections); // Include fake section with stealth activities.
995         $this->assertCount(5, $sections[0]['modules']);
996         $this->assertCount(1, $sections[1]['modules']);
997         $this->assertCount(1, $sections[2]['modules']);
998         $this->assertCount(0, $sections[3]['modules']); // No modules for the section with availability restrictions.
999         $this->assertCount(1, $sections[4]['modules']); // One stealh module.
1000         $this->assertEquals(-1, $sections[4]['id']);
1001     }
1003     /**
1004      * Test get_course_contents excluding modules
1005      */
1006     public function test_get_course_contents_excluding_modules() {
1007         $this->resetAfterTest(true);
1009         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1011         // Test exclude modules.
1012         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludemodules", "value" => 1)));
1014         // We need to execute the return values cleaning process to simulate the web service server.
1015         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1017         $this->assertEmpty($sections[0]['modules']);
1018         $this->assertEmpty($sections[1]['modules']);
1019     }
1021     /**
1022      * Test get_course_contents excluding contents
1023      */
1024     public function test_get_course_contents_excluding_contents() {
1025         $this->resetAfterTest(true);
1027         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1029         // Test exclude modules.
1030         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "excludecontents", "value" => 1)));
1032         // We need to execute the return values cleaning process to simulate the web service server.
1033         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1035         foreach ($sections as $section) {
1036             foreach ($section['modules'] as $module) {
1037                 // Only resources return contents.
1038                 if (isset($module['contents'])) {
1039                     $this->assertEmpty($module['contents']);
1040                 }
1041             }
1042         }
1043     }
1045     /**
1046      * Test get_course_contents filtering by section number
1047      */
1048     public function test_get_course_contents_section_number() {
1049         $this->resetAfterTest(true);
1051         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1053         // Test exclude modules.
1054         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "sectionnumber", "value" => 0)));
1056         // We need to execute the return values cleaning process to simulate the web service server.
1057         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1059         $this->assertCount(1, $sections);
1060         $this->assertCount(5, $sections[0]['modules']);
1061     }
1063     /**
1064      * Test get_course_contents filtering by cmid
1065      */
1066     public function test_get_course_contents_cmid() {
1067         $this->resetAfterTest(true);
1069         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1071         // Test exclude modules.
1072         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "cmid", "value" => $forumcm->id)));
1074         // We need to execute the return values cleaning process to simulate the web service server.
1075         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1077         $this->assertCount(4, $sections);
1078         $this->assertCount(1, $sections[0]['modules']);
1079         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
1080     }
1083     /**
1084      * Test get_course_contents filtering by cmid and section
1085      */
1086     public function test_get_course_contents_section_cmid() {
1087         $this->resetAfterTest(true);
1089         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1091         // Test exclude modules.
1092         $sections = core_course_external::get_course_contents($course->id, array(
1093                                                                         array("name" => "cmid", "value" => $forumcm->id),
1094                                                                         array("name" => "sectionnumber", "value" => 0)
1095                                                                         ));
1097         // We need to execute the return values cleaning process to simulate the web service server.
1098         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1100         $this->assertCount(1, $sections);
1101         $this->assertCount(1, $sections[0]['modules']);
1102         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
1103     }
1105     /**
1106      * Test get_course_contents filtering by modname
1107      */
1108     public function test_get_course_contents_modname() {
1109         $this->resetAfterTest(true);
1111         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1113         // Test exclude modules.
1114         $sections = core_course_external::get_course_contents($course->id, array(array("name" => "modname", "value" => "forum")));
1116         // We need to execute the return values cleaning process to simulate the web service server.
1117         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1119         $this->assertCount(4, $sections);
1120         $this->assertCount(1, $sections[0]['modules']);
1121         $this->assertEquals($forumcm->id, $sections[0]['modules'][0]["id"]);
1122     }
1124     /**
1125      * Test get_course_contents filtering by modname
1126      */
1127     public function test_get_course_contents_modid() {
1128         $this->resetAfterTest(true);
1130         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1132         // Test exclude modules.
1133         $sections = core_course_external::get_course_contents($course->id, array(
1134                                                                             array("name" => "modname", "value" => "page"),
1135                                                                             array("name" => "modid", "value" => $pagecm->instance),
1136                                                                             ));
1138         // We need to execute the return values cleaning process to simulate the web service server.
1139         $sections = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $sections);
1141         $this->assertCount(4, $sections);
1142         $this->assertCount(1, $sections[0]['modules']);
1143         $this->assertEquals("page", $sections[0]['modules'][0]["modname"]);
1144         $this->assertEquals($pagecm->instance, $sections[0]['modules'][0]["instance"]);
1145     }
1147     /**
1148      * Test get course contents completion
1149      */
1150     public function test_get_course_contents_completion() {
1151         global $CFG;
1152         $this->resetAfterTest(true);
1154         list($course, $forumcm, $datacm, $pagecm, $labelcm, $urlcm) = $this->prepare_get_course_contents_test();
1156         // Test activity not completed yet.
1157         $result = core_course_external::get_course_contents($course->id, array(
1158             array("name" => "modname", "value" => "forum"), array("name" => "modid", "value" => $forumcm->instance)));
1159         // We need to execute the return values cleaning process to simulate the web service server.
1160         $result = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $result);
1162         $this->assertCount(1, $result[0]['modules']);
1163         $this->assertEquals("forum", $result[0]['modules'][0]["modname"]);
1164         $this->assertEquals(COMPLETION_TRACKING_MANUAL, $result[0]['modules'][0]["completion"]);
1165         $this->assertEquals(0, $result[0]['modules'][0]["completiondata"]['state']);
1166         $this->assertEquals(0, $result[0]['modules'][0]["completiondata"]['timecompleted']);
1167         $this->assertEmpty($result[0]['modules'][0]["completiondata"]['overrideby']);
1169         // Set activity completed.
1170         core_completion_external::update_activity_completion_status_manually($forumcm->id, true);
1172         $result = core_course_external::get_course_contents($course->id, array(
1173             array("name" => "modname", "value" => "forum"), array("name" => "modid", "value" => $forumcm->instance)));
1174         // We need to execute the return values cleaning process to simulate the web service server.
1175         $result = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $result);
1177         $this->assertEquals(COMPLETION_COMPLETE, $result[0]['modules'][0]["completiondata"]['state']);
1178         $this->assertNotEmpty($result[0]['modules'][0]["completiondata"]['timecompleted']);
1179         $this->assertEmpty($result[0]['modules'][0]["completiondata"]['overrideby']);
1181         // Disable completion.
1182         $CFG->enablecompletion = 0;
1183         $result = core_course_external::get_course_contents($course->id, array(
1184             array("name" => "modname", "value" => "forum"), array("name" => "modid", "value" => $forumcm->instance)));
1185         // We need to execute the return values cleaning process to simulate the web service server.
1186         $result = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $result);
1188         $this->assertArrayNotHasKey('completiondata', $result[0]['modules'][0]);
1189     }
1191     /**
1192      * Test mimetype is returned for resources with showtype set.
1193      */
1194     public function test_get_course_contents_including_mimetype() {
1195         $this->resetAfterTest(true);
1197         $this->setAdminUser();
1198         $course = self::getDataGenerator()->create_course();
1200         $record = new stdClass();
1201         $record->course = $course->id;
1202         $record->showtype = 1;
1203         $resource = self::getDataGenerator()->create_module('resource', $record);
1205         $result = core_course_external::get_course_contents($course->id);
1206         $result = external_api::clean_returnvalue(core_course_external::get_course_contents_returns(), $result);
1207         $this->assertCount(1, $result[0]['modules']);   // One module, first section.
1208         $customdata = unserialize(json_decode($result[0]['modules'][0]['customdata']));
1209         $this->assertEquals('text/plain', $customdata['filedetails']['mimetype']);
1210     }
1212     /**
1213      * Test duplicate_course
1214      */
1215     public function test_duplicate_course() {
1216         $this->resetAfterTest(true);
1218         // Create one course with three modules.
1219         $course  = self::getDataGenerator()->create_course();
1220         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course->id));
1221         $forumcm = get_coursemodule_from_id('forum', $forum->cmid);
1222         $forumcontext = context_module::instance($forum->cmid);
1223         $data = $this->getDataGenerator()->create_module('data', array('assessed'=>1, 'scale'=>100, 'course'=>$course->id));
1224         $datacontext = context_module::instance($data->cmid);
1225         $datacm = get_coursemodule_from_instance('page', $data->id);
1226         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course->id));
1227         $pagecontext = context_module::instance($page->cmid);
1228         $pagecm = get_coursemodule_from_instance('page', $page->id);
1230         // Set the required capabilities by the external function.
1231         $coursecontext = context_course::instance($course->id);
1232         $categorycontext = context_coursecat::instance($course->category);
1233         $roleid = $this->assignUserCapability('moodle/course:create', $categorycontext->id);
1234         $this->assignUserCapability('moodle/course:view', $categorycontext->id, $roleid);
1235         $this->assignUserCapability('moodle/restore:restorecourse', $categorycontext->id, $roleid);
1236         $this->assignUserCapability('moodle/backup:backupcourse', $coursecontext->id, $roleid);
1237         $this->assignUserCapability('moodle/backup:configure', $coursecontext->id, $roleid);
1238         // Optional capabilities to copy user data.
1239         $this->assignUserCapability('moodle/backup:userinfo', $coursecontext->id, $roleid);
1240         $this->assignUserCapability('moodle/restore:userinfo', $categorycontext->id, $roleid);
1242         $newcourse['fullname'] = 'Course duplicate';
1243         $newcourse['shortname'] = 'courseduplicate';
1244         $newcourse['categoryid'] = $course->category;
1245         $newcourse['visible'] = true;
1246         $newcourse['options'][] = array('name' => 'users', 'value' => true);
1248         $duplicate = core_course_external::duplicate_course($course->id, $newcourse['fullname'],
1249                 $newcourse['shortname'], $newcourse['categoryid'], $newcourse['visible'], $newcourse['options']);
1251         // We need to execute the return values cleaning process to simulate the web service server.
1252         $duplicate = external_api::clean_returnvalue(core_course_external::duplicate_course_returns(), $duplicate);
1254         // Check that the course has been duplicated.
1255         $this->assertEquals($newcourse['shortname'], $duplicate['shortname']);
1256     }
1258     /**
1259      * Test update_courses
1260      */
1261     public function test_update_courses() {
1262         global $DB, $CFG, $USER, $COURSE;
1264         // Get current $COURSE to be able to restore it later (defaults to $SITE). We need this
1265         // trick because we are both updating and getting (for testing) course information
1266         // in the same request and core_course_external::update_courses()
1267         // is overwriting $COURSE all over the time with OLD values, so later
1268         // use of get_course() fetches those OLD values instead of the updated ones.
1269         // See MDL-39723 for more info.
1270         $origcourse = clone($COURSE);
1272         $this->resetAfterTest(true);
1274         // Set the required capabilities by the external function.
1275         $contextid = context_system::instance()->id;
1276         $roleid = $this->assignUserCapability('moodle/course:update', $contextid);
1277         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1278         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1279         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1280         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1281         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1282         $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid);
1283         $this->assignUserCapability('moodle/course:viewhiddencourses', $contextid, $roleid);
1284         $this->assignUserCapability('moodle/course:setforcedlanguage', $contextid, $roleid);
1286         // Create category and course.
1287         $category1  = self::getDataGenerator()->create_category();
1288         $category2  = self::getDataGenerator()->create_category();
1289         $originalcourse1 = self::getDataGenerator()->create_course();
1290         self::getDataGenerator()->enrol_user($USER->id, $originalcourse1->id, $roleid);
1291         $originalcourse2 = self::getDataGenerator()->create_course();
1292         self::getDataGenerator()->enrol_user($USER->id, $originalcourse2->id, $roleid);
1294         // Course values to be updated.
1295         $course1['id'] = $originalcourse1->id;
1296         $course1['fullname'] = 'Updated test course 1';
1297         $course1['shortname'] = 'Udestedtestcourse1';
1298         $course1['categoryid'] = $category1->id;
1299         $course2['id'] = $originalcourse2->id;
1300         $course2['fullname'] = 'Updated test course 2';
1301         $course2['shortname'] = 'Updestedtestcourse2';
1302         $course2['categoryid'] = $category2->id;
1303         $course2['idnumber'] = 'Updatedidnumber2';
1304         $course2['summary'] = 'Updaated description for course 2';
1305         $course2['summaryformat'] = FORMAT_HTML;
1306         $course2['format'] = 'topics';
1307         $course2['showgrades'] = 1;
1308         $course2['newsitems'] = 3;
1309         $course2['startdate'] = 1420092000; // 01/01/2015.
1310         $course2['enddate'] = 1422669600; // 01/31/2015.
1311         $course2['maxbytes'] = 100000;
1312         $course2['showreports'] = 1;
1313         $course2['visible'] = 0;
1314         $course2['hiddensections'] = 0;
1315         $course2['groupmode'] = 0;
1316         $course2['groupmodeforce'] = 0;
1317         $course2['defaultgroupingid'] = 0;
1318         $course2['enablecompletion'] = 1;
1319         $course2['lang'] = 'en';
1320         $course2['forcetheme'] = 'bootstrapbase';
1321         $courses = array($course1, $course2);
1323         $updatedcoursewarnings = core_course_external::update_courses($courses);
1324         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1325                                                                     $updatedcoursewarnings);
1326         $COURSE = $origcourse; // Restore $COURSE. Instead of using the OLD one set by the previous line.
1328         // Check that right number of courses were created.
1329         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1331         // Check that the courses were correctly created.
1332         foreach ($courses as $course) {
1333             $courseinfo = course_get_format($course['id'])->get_course();
1334             if ($course['id'] == $course2['id']) {
1335                 $this->assertEquals($course2['fullname'], $courseinfo->fullname);
1336                 $this->assertEquals($course2['shortname'], $courseinfo->shortname);
1337                 $this->assertEquals($course2['categoryid'], $courseinfo->category);
1338                 $this->assertEquals($course2['idnumber'], $courseinfo->idnumber);
1339                 $this->assertEquals($course2['summary'], $courseinfo->summary);
1340                 $this->assertEquals($course2['summaryformat'], $courseinfo->summaryformat);
1341                 $this->assertEquals($course2['format'], $courseinfo->format);
1342                 $this->assertEquals($course2['showgrades'], $courseinfo->showgrades);
1343                 $this->assertEquals($course2['newsitems'], $courseinfo->newsitems);
1344                 $this->assertEquals($course2['startdate'], $courseinfo->startdate);
1345                 $this->assertEquals($course2['enddate'], $courseinfo->enddate);
1346                 $this->assertEquals($course2['maxbytes'], $courseinfo->maxbytes);
1347                 $this->assertEquals($course2['showreports'], $courseinfo->showreports);
1348                 $this->assertEquals($course2['visible'], $courseinfo->visible);
1349                 $this->assertEquals($course2['hiddensections'], $courseinfo->hiddensections);
1350                 $this->assertEquals($course2['groupmode'], $courseinfo->groupmode);
1351                 $this->assertEquals($course2['groupmodeforce'], $courseinfo->groupmodeforce);
1352                 $this->assertEquals($course2['defaultgroupingid'], $courseinfo->defaultgroupingid);
1353                 $this->assertEquals($course2['lang'], $courseinfo->lang);
1355                 if (!empty($CFG->allowcoursethemes)) {
1356                     $this->assertEquals($course2['forcetheme'], $courseinfo->theme);
1357                 }
1359                 $this->assertEquals($course2['enablecompletion'], $courseinfo->enablecompletion);
1360             } else if ($course['id'] == $course1['id']) {
1361                 $this->assertEquals($course1['fullname'], $courseinfo->fullname);
1362                 $this->assertEquals($course1['shortname'], $courseinfo->shortname);
1363                 $this->assertEquals($course1['categoryid'], $courseinfo->category);
1364                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1365                 $this->assertEquals('topics', $courseinfo->format);
1366                 $this->assertEquals(5, course_get_format($course['id'])->get_last_section_number());
1367                 $this->assertEquals(0, $courseinfo->newsitems);
1368                 $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat);
1369             } else {
1370                 throw new moodle_exception('Unexpected shortname');
1371             }
1372         }
1374         $courses = array($course1);
1375         // Try update course without update capability.
1376         $user = self::getDataGenerator()->create_user();
1377         $this->setUser($user);
1378         $this->unassignUserCapability('moodle/course:update', $contextid, $roleid);
1379         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1380         $updatedcoursewarnings = core_course_external::update_courses($courses);
1381         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1382                                                                     $updatedcoursewarnings);
1383         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1385         // Try update course category without capability.
1386         $this->assignUserCapability('moodle/course:update', $contextid, $roleid);
1387         $this->unassignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1388         $user = self::getDataGenerator()->create_user();
1389         $this->setUser($user);
1390         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1391         $course1['categoryid'] = $category2->id;
1392         $courses = array($course1);
1393         $updatedcoursewarnings = core_course_external::update_courses($courses);
1394         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1395                                                                     $updatedcoursewarnings);
1396         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1398         // Try update course fullname without capability.
1399         $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid);
1400         $this->unassignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1401         $user = self::getDataGenerator()->create_user();
1402         $this->setUser($user);
1403         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1404         $updatedcoursewarnings = core_course_external::update_courses($courses);
1405         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1406                                                                     $updatedcoursewarnings);
1407         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1408         $course1['fullname'] = 'Testing fullname without permission';
1409         $courses = array($course1);
1410         $updatedcoursewarnings = core_course_external::update_courses($courses);
1411         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1412                                                                     $updatedcoursewarnings);
1413         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1415         // Try update course shortname without capability.
1416         $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid);
1417         $this->unassignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1418         $user = self::getDataGenerator()->create_user();
1419         $this->setUser($user);
1420         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1421         $updatedcoursewarnings = core_course_external::update_courses($courses);
1422         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1423                                                                     $updatedcoursewarnings);
1424         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1425         $course1['shortname'] = 'Testing shortname without permission';
1426         $courses = array($course1);
1427         $updatedcoursewarnings = core_course_external::update_courses($courses);
1428         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1429                                                                     $updatedcoursewarnings);
1430         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1432         // Try update course idnumber without capability.
1433         $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid);
1434         $this->unassignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1435         $user = self::getDataGenerator()->create_user();
1436         $this->setUser($user);
1437         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1438         $updatedcoursewarnings = core_course_external::update_courses($courses);
1439         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1440                                                                     $updatedcoursewarnings);
1441         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1442         $course1['idnumber'] = 'NEWIDNUMBER';
1443         $courses = array($course1);
1444         $updatedcoursewarnings = core_course_external::update_courses($courses);
1445         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1446                                                                     $updatedcoursewarnings);
1447         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1449         // Try update course summary without capability.
1450         $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid);
1451         $this->unassignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1452         $user = self::getDataGenerator()->create_user();
1453         $this->setUser($user);
1454         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1455         $updatedcoursewarnings = core_course_external::update_courses($courses);
1456         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1457                                                                     $updatedcoursewarnings);
1458         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1459         $course1['summary'] = 'New summary';
1460         $courses = array($course1);
1461         $updatedcoursewarnings = core_course_external::update_courses($courses);
1462         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1463                                                                     $updatedcoursewarnings);
1464         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1466         // Try update course with invalid summary format.
1467         $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid);
1468         $user = self::getDataGenerator()->create_user();
1469         $this->setUser($user);
1470         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1471         $updatedcoursewarnings = core_course_external::update_courses($courses);
1472         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1473                                                                     $updatedcoursewarnings);
1474         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1475         $course1['summaryformat'] = 10;
1476         $courses = array($course1);
1477         $updatedcoursewarnings = core_course_external::update_courses($courses);
1478         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1479                                                                     $updatedcoursewarnings);
1480         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1482         // Try update course visibility without capability.
1483         $this->unassignUserCapability('moodle/course:visibility', $contextid, $roleid);
1484         $user = self::getDataGenerator()->create_user();
1485         $this->setUser($user);
1486         self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid);
1487         $course1['summaryformat'] = FORMAT_MOODLE;
1488         $courses = array($course1);
1489         $updatedcoursewarnings = core_course_external::update_courses($courses);
1490         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1491                                                                     $updatedcoursewarnings);
1492         $this->assertEquals(0, count($updatedcoursewarnings['warnings']));
1493         $course1['visible'] = 0;
1494         $courses = array($course1);
1495         $updatedcoursewarnings = core_course_external::update_courses($courses);
1496         $updatedcoursewarnings = external_api::clean_returnvalue(core_course_external::update_courses_returns(),
1497                                                                     $updatedcoursewarnings);
1498         $this->assertEquals(1, count($updatedcoursewarnings['warnings']));
1499     }
1501     /**
1502      * Test delete course_module.
1503      */
1504     public function test_delete_modules() {
1505         global $DB;
1507         // Ensure we reset the data after this test.
1508         $this->resetAfterTest(true);
1510         // Create a user.
1511         $user = self::getDataGenerator()->create_user();
1513         // Set the tests to run as the user.
1514         self::setUser($user);
1516         // Create a course to add the modules.
1517         $course = self::getDataGenerator()->create_course();
1519         // Create two test modules.
1520         $record = new stdClass();
1521         $record->course = $course->id;
1522         $module1 = self::getDataGenerator()->create_module('forum', $record);
1523         $module2 = self::getDataGenerator()->create_module('assign', $record);
1525         // Check the forum was correctly created.
1526         $this->assertEquals(1, $DB->count_records('forum', array('id' => $module1->id)));
1528         // Check the assignment was correctly created.
1529         $this->assertEquals(1, $DB->count_records('assign', array('id' => $module2->id)));
1531         // Check data exists in the course modules table.
1532         $this->assertEquals(2, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1533                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1535         // Enrol the user in the course.
1536         $enrol = enrol_get_plugin('manual');
1537         $enrolinstances = enrol_get_instances($course->id, true);
1538         foreach ($enrolinstances as $courseenrolinstance) {
1539             if ($courseenrolinstance->enrol == "manual") {
1540                 $instance = $courseenrolinstance;
1541                 break;
1542             }
1543         }
1544         $enrol->enrol_user($instance, $user->id);
1546         // Assign capabilities to delete module 1.
1547         $modcontext = context_module::instance($module1->cmid);
1548         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id);
1550         // Assign capabilities to delete module 2.
1551         $modcontext = context_module::instance($module2->cmid);
1552         $newrole = create_role('Role 2', 'role2', 'Role 2 description');
1553         $this->assignUserCapability('moodle/course:manageactivities', $modcontext->id, $newrole);
1555         // Deleting these module instances.
1556         core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1558         // Check the forum was deleted.
1559         $this->assertEquals(0, $DB->count_records('forum', array('id' => $module1->id)));
1561         // Check the assignment was deleted.
1562         $this->assertEquals(0, $DB->count_records('assign', array('id' => $module2->id)));
1564         // Check we retrieve no data in the course modules table.
1565         $this->assertEquals(0, $DB->count_records_select('course_modules', 'id = :module1 OR id = :module2',
1566                 array('module1' => $module1->cmid, 'module2' => $module2->cmid)));
1568         // Call with non-existent course module id and ensure exception thrown.
1569         try {
1570             core_course_external::delete_modules(array('1337'));
1571             $this->fail('Exception expected due to missing course module.');
1572         } catch (dml_missing_record_exception $e) {
1573             $this->assertEquals('invalidcoursemodule', $e->errorcode);
1574         }
1576         // Create two modules.
1577         $module1 = self::getDataGenerator()->create_module('forum', $record);
1578         $module2 = self::getDataGenerator()->create_module('assign', $record);
1580         // Since these modules were recreated the user will not have capabilities
1581         // to delete them, ensure exception is thrown if they try.
1582         try {
1583             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1584             $this->fail('Exception expected due to missing capability.');
1585         } catch (moodle_exception $e) {
1586             $this->assertEquals('nopermissions', $e->errorcode);
1587         }
1589         // Unenrol user from the course.
1590         $enrol->unenrol_user($instance, $user->id);
1592         // Try and delete modules from the course the user was unenrolled in, make sure exception thrown.
1593         try {
1594             core_course_external::delete_modules(array($module1->cmid, $module2->cmid));
1595             $this->fail('Exception expected due to being unenrolled from the course.');
1596         } catch (moodle_exception $e) {
1597             $this->assertEquals('requireloginerror', $e->errorcode);
1598         }
1599     }
1601     /**
1602      * Test import_course into an empty course
1603      */
1604     public function test_import_course_empty() {
1605         global $USER;
1607         $this->resetAfterTest(true);
1609         $course1  = self::getDataGenerator()->create_course();
1610         $forum = $this->getDataGenerator()->create_module('forum', array('course' => $course1->id, 'name' => 'Forum test'));
1611         $page = $this->getDataGenerator()->create_module('page', array('course' => $course1->id, 'name' => 'Page test'));
1613         $course2  = self::getDataGenerator()->create_course();
1615         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1616         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1618         // Verify the state of the courses before we do the import.
1619         $this->assertCount(2, $course1cms);
1620         $this->assertEmpty($course2cms);
1622         // Setup the user to run the operation (ugly hack because validate_context() will
1623         // fail as the email is not set by $this->setAdminUser()).
1624         $this->setAdminUser();
1625         $USER->email = 'emailtopass@example.com';
1627         // Import from course1 to course2.
1628         core_course_external::import_course($course1->id, $course2->id, 0);
1630         // Verify that now we have two modules in both courses.
1631         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1632         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1633         $this->assertCount(2, $course1cms);
1634         $this->assertCount(2, $course2cms);
1636         // Verify that the names transfered across correctly.
1637         foreach ($course2cms as $cm) {
1638             if ($cm->modname === 'page') {
1639                 $this->assertEquals($cm->name, $page->name);
1640             } else if ($cm->modname === 'forum') {
1641                 $this->assertEquals($cm->name, $forum->name);
1642             } else {
1643                 $this->fail('Unknown CM found.');
1644             }
1645         }
1646     }
1648     /**
1649      * Test import_course into an filled course
1650      */
1651     public function test_import_course_filled() {
1652         global $USER;
1654         $this->resetAfterTest(true);
1656         // Add forum and page to course1.
1657         $course1  = self::getDataGenerator()->create_course();
1658         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1659         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1661         // Add quiz to course 2.
1662         $course2  = self::getDataGenerator()->create_course();
1663         $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1665         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1666         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1668         // Verify the state of the courses before we do the import.
1669         $this->assertCount(2, $course1cms);
1670         $this->assertCount(1, $course2cms);
1672         // Setup the user to run the operation (ugly hack because validate_context() will
1673         // fail as the email is not set by $this->setAdminUser()).
1674         $this->setAdminUser();
1675         $USER->email = 'emailtopass@example.com';
1677         // Import from course1 to course2 without deleting content.
1678         core_course_external::import_course($course1->id, $course2->id, 0);
1680         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1682         // Verify that now we have three modules in course2.
1683         $this->assertCount(3, $course2cms);
1685         // Verify that the names transfered across correctly.
1686         foreach ($course2cms as $cm) {
1687             if ($cm->modname === 'page') {
1688                 $this->assertEquals($cm->name, $page->name);
1689             } else if ($cm->modname === 'forum') {
1690                 $this->assertEquals($cm->name, $forum->name);
1691             } else if ($cm->modname === 'quiz') {
1692                 $this->assertEquals($cm->name, $quiz->name);
1693             } else {
1694                 $this->fail('Unknown CM found.');
1695             }
1696         }
1697     }
1699     /**
1700      * Test import_course with only blocks set to backup
1701      */
1702     public function test_import_course_blocksonly() {
1703         global $USER, $DB;
1705         $this->resetAfterTest(true);
1707         // Add forum and page to course1.
1708         $course1  = self::getDataGenerator()->create_course();
1709         $course1ctx = context_course::instance($course1->id);
1710         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1711         $block = $this->getDataGenerator()->create_block('online_users', array('parentcontextid' => $course1ctx->id));
1713         $course2  = self::getDataGenerator()->create_course();
1714         $course2ctx = context_course::instance($course2->id);
1715         $initialblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1716         $initialcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1718         // Setup the user to run the operation (ugly hack because validate_context() will
1719         // fail as the email is not set by $this->setAdminUser()).
1720         $this->setAdminUser();
1721         $USER->email = 'emailtopass@example.com';
1723         // Import from course1 to course2 without deleting content, but excluding
1724         // activities.
1725         $options = array(
1726             array('name' => 'activities', 'value' => 0),
1727             array('name' => 'blocks', 'value' => 1),
1728             array('name' => 'filters', 'value' => 0),
1729         );
1731         core_course_external::import_course($course1->id, $course2->id, 0, $options);
1733         $newcmcount = count(get_fast_modinfo($course2->id)->get_cms());
1734         $newblockcount = $DB->count_records('block_instances', array('parentcontextid' => $course2ctx->id));
1735         // Check that course modules haven't changed, but that blocks have.
1736         $this->assertEquals($initialcmcount, $newcmcount);
1737         $this->assertEquals(($initialblockcount + 1), $newblockcount);
1738     }
1740     /**
1741      * Test import_course into an filled course, deleting content.
1742      */
1743     public function test_import_course_deletecontent() {
1744         global $USER;
1745         $this->resetAfterTest(true);
1747         // Add forum and page to course1.
1748         $course1  = self::getDataGenerator()->create_course();
1749         $forum = $this->getDataGenerator()->create_module('forum', array('course'=>$course1->id, 'name' => 'Forum test'));
1750         $page = $this->getDataGenerator()->create_module('page', array('course'=>$course1->id, 'name' => 'Page test'));
1752         // Add quiz to course 2.
1753         $course2  = self::getDataGenerator()->create_course();
1754         $quiz = $this->getDataGenerator()->create_module('quiz', array('course'=>$course2->id, 'name' => 'Page test'));
1756         $course1cms = get_fast_modinfo($course1->id)->get_cms();
1757         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1759         // Verify the state of the courses before we do the import.
1760         $this->assertCount(2, $course1cms);
1761         $this->assertCount(1, $course2cms);
1763         // Setup the user to run the operation (ugly hack because validate_context() will
1764         // fail as the email is not set by $this->setAdminUser()).
1765         $this->setAdminUser();
1766         $USER->email = 'emailtopass@example.com';
1768         // Import from course1 to course2,  deleting content.
1769         core_course_external::import_course($course1->id, $course2->id, 1);
1771         $course2cms = get_fast_modinfo($course2->id)->get_cms();
1773         // Verify that now we have two modules in course2.
1774         $this->assertCount(2, $course2cms);
1776         // Verify that the course only contains the imported modules.
1777         foreach ($course2cms as $cm) {
1778             if ($cm->modname === 'page') {
1779                 $this->assertEquals($cm->name, $page->name);
1780             } else if ($cm->modname === 'forum') {
1781                 $this->assertEquals($cm->name, $forum->name);
1782             } else {
1783                 $this->fail('Unknown CM found: '.$cm->name);
1784             }
1785         }
1786     }
1788     /**
1789      * Ensure import_course handles incorrect deletecontent option correctly.
1790      */
1791     public function test_import_course_invalid_deletecontent_option() {
1792         $this->resetAfterTest(true);
1794         $course1  = self::getDataGenerator()->create_course();
1795         $course2  = self::getDataGenerator()->create_course();
1797         $this->expectException('moodle_exception');
1798         $this->expectExceptionMessage(get_string('invalidextparam', 'webservice', -1));
1799         // Import from course1 to course2, with invalid option
1800         core_course_external::import_course($course1->id, $course2->id, -1);;
1801     }
1803     /**
1804      * Test view_course function
1805      */
1806     public function test_view_course() {
1808         $this->resetAfterTest();
1810         // Course without sections.
1811         $course = $this->getDataGenerator()->create_course(array('numsections' => 5), array('createsections' => true));
1812         $this->setAdminUser();
1814         // Redirect events to the sink, so we can recover them later.
1815         $sink = $this->redirectEvents();
1817         $result = core_course_external::view_course($course->id, 1);
1818         $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
1819         $events = $sink->get_events();
1820         $event = reset($events);
1822         // Check the event details are correct.
1823         $this->assertInstanceOf('\core\event\course_viewed', $event);
1824         $this->assertEquals(context_course::instance($course->id), $event->get_context());
1825         $this->assertEquals(1, $event->other['coursesectionnumber']);
1827         $result = core_course_external::view_course($course->id);
1828         $result = external_api::clean_returnvalue(core_course_external::view_course_returns(), $result);
1829         $events = $sink->get_events();
1830         $event = array_pop($events);
1831         $sink->close();
1833         // Check the event details are correct.
1834         $this->assertInstanceOf('\core\event\course_viewed', $event);
1835         $this->assertEquals(context_course::instance($course->id), $event->get_context());
1836         $this->assertEmpty($event->other);
1838     }
1840     /**
1841      * Test get_course_module
1842      */
1843     public function test_get_course_module() {
1844         global $DB;
1846         $this->resetAfterTest(true);
1848         $this->setAdminUser();
1849         $course = self::getDataGenerator()->create_course();
1850         $record = array(
1851             'course' => $course->id,
1852             'name' => 'First Assignment'
1853         );
1854         $options = array(
1855             'idnumber' => 'ABC',
1856             'visible' => 0
1857         );
1858         // Hidden activity.
1859         $assign = self::getDataGenerator()->create_module('assign', $record, $options);
1861         $outcomescale = 'Distinction, Very Good, Good, Pass, Fail';
1863         // Insert a custom grade scale to be used by an outcome.
1864         $gradescale = new grade_scale();
1865         $gradescale->name        = 'gettcoursemodulescale';
1866         $gradescale->courseid    = $course->id;
1867         $gradescale->userid      = 0;
1868         $gradescale->scale       = $outcomescale;
1869         $gradescale->description = 'This scale is used to mark standard assignments.';
1870         $gradescale->insert();
1872         // Insert an outcome.
1873         $data = new stdClass();
1874         $data->courseid = $course->id;
1875         $data->fullname = 'Team work';
1876         $data->shortname = 'Team work';
1877         $data->scaleid = $gradescale->id;
1878         $outcome = new grade_outcome($data, false);
1879         $outcome->insert();
1881         $outcomegradeitem = new grade_item();
1882         $outcomegradeitem->itemname = $outcome->shortname;
1883         $outcomegradeitem->itemtype = 'mod';
1884         $outcomegradeitem->itemmodule = 'assign';
1885         $outcomegradeitem->iteminstance = $assign->id;
1886         $outcomegradeitem->outcomeid = $outcome->id;
1887         $outcomegradeitem->cmid = 0;
1888         $outcomegradeitem->courseid = $course->id;
1889         $outcomegradeitem->aggregationcoef = 0;
1890         $outcomegradeitem->itemnumber = 1; // The activity's original grade item will be 0.
1891         $outcomegradeitem->gradetype = GRADE_TYPE_SCALE;
1892         $outcomegradeitem->scaleid = $outcome->scaleid;
1893         $outcomegradeitem->insert();
1895         $assignmentgradeitem = grade_item::fetch(
1896             array(
1897                 'itemtype' => 'mod',
1898                 'itemmodule' => 'assign',
1899                 'iteminstance' => $assign->id,
1900                 'itemnumber' => 0,
1901                 'courseid' => $course->id
1902             )
1903         );
1904         $outcomegradeitem->set_parent($assignmentgradeitem->categoryid);
1905         $outcomegradeitem->move_after_sortorder($assignmentgradeitem->sortorder);
1907         // Test admin user can see the complete hidden activity.
1908         $result = core_course_external::get_course_module($assign->cmid);
1909         $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
1911         $this->assertCount(0, $result['warnings']);
1912         // Test we retrieve all the fields.
1913         $this->assertCount(28, $result['cm']);
1914         $this->assertEquals($record['name'], $result['cm']['name']);
1915         $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
1916         $this->assertEquals(100, $result['cm']['grade']);
1917         $this->assertEquals(0.0, $result['cm']['gradepass']);
1918         $this->assertEquals('submissions', $result['cm']['advancedgrading'][0]['area']);
1919         $this->assertEmpty($result['cm']['advancedgrading'][0]['method']);
1920         $this->assertEquals($outcomescale, $result['cm']['outcomes'][0]['scale']);
1922         $student = $this->getDataGenerator()->create_user();
1923         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1925         self::getDataGenerator()->enrol_user($student->id,  $course->id, $studentrole->id);
1926         $this->setUser($student);
1928         // The user shouldn't be able to see the activity.
1929         try {
1930             core_course_external::get_course_module($assign->cmid);
1931             $this->fail('Exception expected due to invalid permissions.');
1932         } catch (moodle_exception $e) {
1933             $this->assertEquals('requireloginerror', $e->errorcode);
1934         }
1936         // Make module visible.
1937         set_coursemodule_visible($assign->cmid, 1);
1939         // Test student user.
1940         $result = core_course_external::get_course_module($assign->cmid);
1941         $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
1943         $this->assertCount(0, $result['warnings']);
1944         // Test we retrieve only the few files we can see.
1945         $this->assertCount(11, $result['cm']);
1946         $this->assertEquals($assign->cmid, $result['cm']['id']);
1947         $this->assertEquals($course->id, $result['cm']['course']);
1948         $this->assertEquals('assign', $result['cm']['modname']);
1949         $this->assertEquals($assign->id, $result['cm']['instance']);
1951     }
1953     /**
1954      * Test get_course_module_by_instance
1955      */
1956     public function test_get_course_module_by_instance() {
1957         global $DB;
1959         $this->resetAfterTest(true);
1961         $this->setAdminUser();
1962         $course = self::getDataGenerator()->create_course();
1963         $record = array(
1964             'course' => $course->id,
1965             'name' => 'First quiz',
1966             'grade' => 90.00
1967         );
1968         $options = array(
1969             'idnumber' => 'ABC',
1970             'visible' => 0
1971         );
1972         // Hidden activity.
1973         $quiz = self::getDataGenerator()->create_module('quiz', $record, $options);
1975         // Test admin user can see the complete hidden activity.
1976         $result = core_course_external::get_course_module_by_instance('quiz', $quiz->id);
1977         $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
1979         $this->assertCount(0, $result['warnings']);
1980         // Test we retrieve all the fields.
1981         $this->assertCount(26, $result['cm']);
1982         $this->assertEquals($record['name'], $result['cm']['name']);
1983         $this->assertEquals($record['grade'], $result['cm']['grade']);
1984         $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
1986         $student = $this->getDataGenerator()->create_user();
1987         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1989         self::getDataGenerator()->enrol_user($student->id,  $course->id, $studentrole->id);
1990         $this->setUser($student);
1992         // The user shouldn't be able to see the activity.
1993         try {
1994             core_course_external::get_course_module_by_instance('quiz', $quiz->id);
1995             $this->fail('Exception expected due to invalid permissions.');
1996         } catch (moodle_exception $e) {
1997             $this->assertEquals('requireloginerror', $e->errorcode);
1998         }
2000         // Make module visible.
2001         set_coursemodule_visible($quiz->cmid, 1);
2003         // Test student user.
2004         $result = core_course_external::get_course_module_by_instance('quiz', $quiz->id);
2005         $result = external_api::clean_returnvalue(core_course_external::get_course_module_by_instance_returns(), $result);
2007         $this->assertCount(0, $result['warnings']);
2008         // Test we retrieve only the few files we can see.
2009         $this->assertCount(11, $result['cm']);
2010         $this->assertEquals($quiz->cmid, $result['cm']['id']);
2011         $this->assertEquals($course->id, $result['cm']['course']);
2012         $this->assertEquals('quiz', $result['cm']['modname']);
2013         $this->assertEquals($quiz->id, $result['cm']['instance']);
2015         // Try with an invalid module name.
2016         try {
2017             core_course_external::get_course_module_by_instance('abc', $quiz->id);
2018             $this->fail('Exception expected due to invalid module name.');
2019         } catch (dml_read_exception $e) {
2020             $this->assertEquals('dmlreadexception', $e->errorcode);
2021         }
2023     }
2025     /**
2026      * Test get_activities_overview
2027      */
2028     public function test_get_activities_overview() {
2029         global $USER;
2031         $this->resetAfterTest();
2032         $course1 = self::getDataGenerator()->create_course();
2033         $course2 = self::getDataGenerator()->create_course();
2035         // Create a viewer user.
2036         $viewer = self::getDataGenerator()->create_user((object) array('trackforums' => 1));
2037         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
2038         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
2040         // Create two forums - one in each course.
2041         $record = new stdClass();
2042         $record->course = $course1->id;
2043         $forum1 = self::getDataGenerator()->create_module('forum', (object) array('course' => $course1->id));
2044         $forum2 = self::getDataGenerator()->create_module('forum', (object) array('course' => $course2->id));
2046         $this->setAdminUser();
2047         // A standard post in the forum.
2048         $record = new stdClass();
2049         $record->course = $course1->id;
2050         $record->userid = $USER->id;
2051         $record->forum = $forum1->id;
2052         $this->getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
2054         $this->setUser($viewer->id);
2055         $courses = array($course1->id , $course2->id);
2057         $result = core_course_external::get_activities_overview($courses);
2058         $this->assertDebuggingCalledCount(8);
2059         $result = external_api::clean_returnvalue(core_course_external::get_activities_overview_returns(), $result);
2061         // There should be one entry for course1, and no others.
2062         $this->assertCount(1, $result['courses']);
2063         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2064         // Check expected overview data for the module.
2065         $this->assertEquals('forum', $result['courses'][0]['overviews'][0]['module']);
2066         $this->assertContains('1 total unread', $result['courses'][0]['overviews'][0]['overviewtext']);
2067     }
2069     /**
2070      * Test get_user_navigation_options
2071      */
2072     public function test_get_user_navigation_options() {
2073         global $USER;
2075         $this->resetAfterTest();
2076         $course1 = self::getDataGenerator()->create_course();
2077         $course2 = self::getDataGenerator()->create_course();
2079         // Create a viewer user.
2080         $viewer = self::getDataGenerator()->create_user();
2081         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
2082         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
2084         $this->setUser($viewer->id);
2085         $courses = array($course1->id , $course2->id, SITEID);
2087         $result = core_course_external::get_user_navigation_options($courses);
2088         $result = external_api::clean_returnvalue(core_course_external::get_user_navigation_options_returns(), $result);
2090         $this->assertCount(0, $result['warnings']);
2091         $this->assertCount(3, $result['courses']);
2093         foreach ($result['courses'] as $course) {
2094             $navoptions = new stdClass;
2095             foreach ($course['options'] as $option) {
2096                 $navoptions->{$option['name']} = $option['available'];
2097             }
2098             $this->assertCount(9, $course['options']);
2099             if ($course['id'] == SITEID) {
2100                 $this->assertTrue($navoptions->blogs);
2101                 $this->assertFalse($navoptions->notes);
2102                 $this->assertFalse($navoptions->participants);
2103                 $this->assertTrue($navoptions->badges);
2104                 $this->assertTrue($navoptions->tags);
2105                 $this->assertFalse($navoptions->grades);
2106                 $this->assertFalse($navoptions->search);
2107                 $this->assertTrue($navoptions->calendar);
2108                 $this->assertTrue($navoptions->competencies);
2109             } else {
2110                 $this->assertTrue($navoptions->blogs);
2111                 $this->assertFalse($navoptions->notes);
2112                 $this->assertTrue($navoptions->participants);
2113                 $this->assertTrue($navoptions->badges);
2114                 $this->assertFalse($navoptions->tags);
2115                 $this->assertTrue($navoptions->grades);
2116                 $this->assertFalse($navoptions->search);
2117                 $this->assertFalse($navoptions->calendar);
2118                 $this->assertTrue($navoptions->competencies);
2119             }
2120         }
2121     }
2123     /**
2124      * Test get_user_administration_options
2125      */
2126     public function test_get_user_administration_options() {
2127         global $USER;
2129         $this->resetAfterTest();
2130         $course1 = self::getDataGenerator()->create_course();
2131         $course2 = self::getDataGenerator()->create_course();
2133         // Create a viewer user.
2134         $viewer = self::getDataGenerator()->create_user();
2135         $this->getDataGenerator()->enrol_user($viewer->id, $course1->id);
2136         $this->getDataGenerator()->enrol_user($viewer->id, $course2->id);
2138         $this->setUser($viewer->id);
2139         $courses = array($course1->id , $course2->id, SITEID);
2141         $result = core_course_external::get_user_administration_options($courses);
2142         $result = external_api::clean_returnvalue(core_course_external::get_user_administration_options_returns(), $result);
2144         $this->assertCount(0, $result['warnings']);
2145         $this->assertCount(3, $result['courses']);
2147         foreach ($result['courses'] as $course) {
2148             $adminoptions = new stdClass;
2149             foreach ($course['options'] as $option) {
2150                 $adminoptions->{$option['name']} = $option['available'];
2151             }
2152             if ($course['id'] == SITEID) {
2153                 $this->assertCount(16, $course['options']);
2154                 $this->assertFalse($adminoptions->update);
2155                 $this->assertFalse($adminoptions->filters);
2156                 $this->assertFalse($adminoptions->reports);
2157                 $this->assertFalse($adminoptions->backup);
2158                 $this->assertFalse($adminoptions->restore);
2159                 $this->assertFalse($adminoptions->files);
2160                 $this->assertFalse(!isset($adminoptions->tags));
2161                 $this->assertFalse($adminoptions->gradebook);
2162                 $this->assertFalse($adminoptions->outcomes);
2163                 $this->assertFalse($adminoptions->badges);
2164                 $this->assertFalse($adminoptions->import);
2165                 $this->assertFalse($adminoptions->publish);
2166                 $this->assertFalse($adminoptions->reset);
2167                 $this->assertFalse($adminoptions->roles);
2168                 $this->assertFalse($adminoptions->editcompletion);
2169             } else {
2170                 $this->assertCount(15, $course['options']);
2171                 $this->assertFalse($adminoptions->update);
2172                 $this->assertFalse($adminoptions->filters);
2173                 $this->assertFalse($adminoptions->reports);
2174                 $this->assertFalse($adminoptions->backup);
2175                 $this->assertFalse($adminoptions->restore);
2176                 $this->assertFalse($adminoptions->files);
2177                 $this->assertFalse($adminoptions->tags);
2178                 $this->assertFalse($adminoptions->gradebook);
2179                 $this->assertFalse($adminoptions->outcomes);
2180                 $this->assertTrue($adminoptions->badges);
2181                 $this->assertFalse($adminoptions->import);
2182                 $this->assertFalse($adminoptions->publish);
2183                 $this->assertFalse($adminoptions->reset);
2184                 $this->assertFalse($adminoptions->roles);
2185                 $this->assertFalse($adminoptions->editcompletion);
2186             }
2187         }
2188     }
2190     /**
2191      * Test get_courses_by_fields
2192      */
2193     public function test_get_courses_by_field() {
2194         global $DB;
2195         $this->resetAfterTest(true);
2197         $category1 = self::getDataGenerator()->create_category(array('name' => 'Cat 1'));
2198         $category2 = self::getDataGenerator()->create_category(array('parent' => $category1->id));
2199         $course1 = self::getDataGenerator()->create_course(
2200             array('category' => $category1->id, 'shortname' => 'c1', 'format' => 'topics'));
2201         $course2 = self::getDataGenerator()->create_course(array('visible' => 0, 'category' => $category2->id, 'idnumber' => 'i2'));
2203         $student1 = self::getDataGenerator()->create_user();
2204         $user1 = self::getDataGenerator()->create_user();
2205         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2206         self::getDataGenerator()->enrol_user($student1->id, $course1->id, $studentrole->id);
2207         self::getDataGenerator()->enrol_user($student1->id, $course2->id, $studentrole->id);
2209         self::setAdminUser();
2210         // As admins, we should be able to retrieve everything.
2211         $result = core_course_external::get_courses_by_field();
2212         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2213         $this->assertCount(3, $result['courses']);
2214         // Expect to receive all the fields.
2215         $this->assertCount(37, $result['courses'][0]);
2216         $this->assertCount(38, $result['courses'][1]);  // One more field because is not the site course.
2217         $this->assertCount(38, $result['courses'][2]);  // One more field because is not the site course.
2219         $result = core_course_external::get_courses_by_field('id', $course1->id);
2220         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2221         $this->assertCount(1, $result['courses']);
2222         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2223         // Expect to receive all the fields.
2224         $this->assertCount(38, $result['courses'][0]);
2225         // Check default values for course format topics.
2226         $this->assertCount(2, $result['courses'][0]['courseformatoptions']);
2227         foreach ($result['courses'][0]['courseformatoptions'] as $option) {
2228             if ($option['name'] == 'hiddensections') {
2229                 $this->assertEquals(0, $option['value']);
2230             } else {
2231                 $this->assertEquals('coursedisplay', $option['name']);
2232                 $this->assertEquals(0, $option['value']);
2233             }
2234         }
2236         $result = core_course_external::get_courses_by_field('id', $course2->id);
2237         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2238         $this->assertCount(1, $result['courses']);
2239         $this->assertEquals($course2->id, $result['courses'][0]['id']);
2241         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2242         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2243         $this->assertCount(2, $result['courses']);
2245         // Check default filters.
2246         $this->assertCount(3, $result['courses'][0]['filters']);
2247         $this->assertCount(3, $result['courses'][1]['filters']);
2249         $result = core_course_external::get_courses_by_field('category', $category1->id);
2250         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2251         $this->assertCount(1, $result['courses']);
2252         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2253         $this->assertEquals('Cat 1', $result['courses'][0]['categoryname']);
2255         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2256         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2257         $this->assertCount(1, $result['courses']);
2258         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2260         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2261         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2262         $this->assertCount(1, $result['courses']);
2263         $this->assertEquals($course2->id, $result['courses'][0]['id']);
2265         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2266         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2267         $this->assertCount(0, $result['courses']);
2269         // Change filter value.
2270         filter_set_local_state('mediaplugin', context_course::instance($course1->id)->id, TEXTFILTER_OFF);
2272         self::setUser($student1);
2273         // All visible courses  (including front page) for normal student.
2274         $result = core_course_external::get_courses_by_field();
2275         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2276         $this->assertCount(2, $result['courses']);
2277         $this->assertCount(30, $result['courses'][0]);
2278         $this->assertCount(31, $result['courses'][1]);  // One field more (course format options), not present in site course.
2280         $result = core_course_external::get_courses_by_field('id', $course1->id);
2281         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2282         $this->assertCount(1, $result['courses']);
2283         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2284         // Expect to receive all the files that a student can see.
2285         $this->assertCount(31, $result['courses'][0]);
2287         // Check default filters.
2288         $filters = $result['courses'][0]['filters'];
2289         $this->assertCount(3, $filters);
2290         $found = false;
2291         foreach ($filters as $filter) {
2292             if ($filter['filter'] == 'mediaplugin' and $filter['localstate'] == TEXTFILTER_OFF) {
2293                 $found = true;
2294             }
2295         }
2296         $this->assertTrue($found);
2298         // Course 2 is not visible.
2299         $result = core_course_external::get_courses_by_field('id', $course2->id);
2300         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2301         $this->assertCount(0, $result['courses']);
2303         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2304         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2305         $this->assertCount(1, $result['courses']);
2307         $result = core_course_external::get_courses_by_field('category', $category1->id);
2308         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2309         $this->assertCount(1, $result['courses']);
2310         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2312         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2313         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2314         $this->assertCount(1, $result['courses']);
2315         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2317         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2318         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2319         $this->assertCount(0, $result['courses']);
2321         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2322         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2323         $this->assertCount(0, $result['courses']);
2325         self::setUser($user1);
2326         // All visible courses (including front page) for authenticated user.
2327         $result = core_course_external::get_courses_by_field();
2328         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2329         $this->assertCount(2, $result['courses']);
2330         $this->assertCount(30, $result['courses'][0]);  // Site course.
2331         $this->assertCount(13, $result['courses'][1]);  // Only public information, not enrolled.
2333         $result = core_course_external::get_courses_by_field('id', $course1->id);
2334         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2335         $this->assertCount(1, $result['courses']);
2336         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2337         // Expect to receive all the files that a authenticated can see.
2338         $this->assertCount(13, $result['courses'][0]);
2340         // Course 2 is not visible.
2341         $result = core_course_external::get_courses_by_field('id', $course2->id);
2342         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2343         $this->assertCount(0, $result['courses']);
2345         $result = core_course_external::get_courses_by_field('ids', "$course1->id,$course2->id");
2346         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2347         $this->assertCount(1, $result['courses']);
2349         $result = core_course_external::get_courses_by_field('category', $category1->id);
2350         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2351         $this->assertCount(1, $result['courses']);
2352         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2354         $result = core_course_external::get_courses_by_field('shortname', 'c1');
2355         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2356         $this->assertCount(1, $result['courses']);
2357         $this->assertEquals($course1->id, $result['courses'][0]['id']);
2359         $result = core_course_external::get_courses_by_field('idnumber', 'i2');
2360         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2361         $this->assertCount(0, $result['courses']);
2363         $result = core_course_external::get_courses_by_field('idnumber', 'x');
2364         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2365         $this->assertCount(0, $result['courses']);
2366     }
2368     public function test_get_courses_by_field_invalid_field() {
2369         $this->expectException('invalid_parameter_exception');
2370         $result = core_course_external::get_courses_by_field('zyx', 'x');
2371     }
2373     public function test_get_courses_by_field_invalid_courses() {
2374         $result = core_course_external::get_courses_by_field('id', '-1');
2375         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2376         $this->assertCount(0, $result['courses']);
2377     }
2379     /**
2380      * Test get_courses_by_field_invalid_theme_and_lang
2381      */
2382     public function test_get_courses_by_field_invalid_theme_and_lang() {
2383         $this->resetAfterTest(true);
2384         $this->setAdminUser();
2386         $course = self::getDataGenerator()->create_course(array('theme' => 'kkt', 'lang' => 'kkl'));
2387         $result = core_course_external::get_courses_by_field('id', $course->id);
2388         $result = external_api::clean_returnvalue(core_course_external::get_courses_by_field_returns(), $result);
2389         $this->assertEmpty($result['courses']['0']['theme']);
2390         $this->assertEmpty($result['courses']['0']['lang']);
2391     }
2394     public function test_check_updates() {
2395         global $DB;
2396         $this->resetAfterTest(true);
2397         $this->setAdminUser();
2399         // Create different types of activities.
2400         $course  = self::getDataGenerator()->create_course();
2401         $tocreate = array('assign', 'book', 'choice', 'folder', 'forum', 'glossary', 'imscp', 'label', 'lti', 'page', 'quiz',
2402                             'resource', 'scorm', 'survey', 'url', 'wiki');
2404         $modules = array();
2405         foreach ($tocreate as $modname) {
2406             $modules[$modname]['instance'] = $this->getDataGenerator()->create_module($modname, array('course' => $course->id));
2407             $modules[$modname]['cm'] = get_coursemodule_from_id(false, $modules[$modname]['instance']->cmid);
2408             $modules[$modname]['context'] = context_module::instance($modules[$modname]['instance']->cmid);
2409         }
2411         $student = self::getDataGenerator()->create_user();
2412         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
2413         self::getDataGenerator()->enrol_user($student->id, $course->id, $studentrole->id);
2414         $this->setUser($student);
2416         $since = time();
2417         $this->waitForSecond();
2418         $params = array();
2419         foreach ($modules as $modname => $data) {
2420             $params[$data['cm']->id] = array(
2421                 'contextlevel' => 'module',
2422                 'id' => $data['cm']->id,
2423                 'since' => $since
2424             );
2425         }
2427         // Check there is nothing updated because modules are fresh new.
2428         $result = core_course_external::check_updates($course->id, $params);
2429         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2430         $this->assertCount(0, $result['instances']);
2431         $this->assertCount(0, $result['warnings']);
2433         // Test with get_updates_since the same data.
2434         $result = core_course_external::get_updates_since($course->id, $since);
2435         $result = external_api::clean_returnvalue(core_course_external::get_updates_since_returns(), $result);
2436         $this->assertCount(0, $result['instances']);
2437         $this->assertCount(0, $result['warnings']);
2439         // Update a module after a second.
2440         $this->waitForSecond();
2441         set_coursemodule_name($modules['forum']['cm']->id, 'New forum name');
2443         $found = false;
2444         $result = core_course_external::check_updates($course->id, $params);
2445         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2446         $this->assertCount(1, $result['instances']);
2447         $this->assertCount(0, $result['warnings']);
2448         foreach ($result['instances'] as $module) {
2449             foreach ($module['updates'] as $update) {
2450                 if ($module['id'] == $modules['forum']['cm']->id and $update['name'] == 'configuration') {
2451                     $found = true;
2452                 }
2453             }
2454         }
2455         $this->assertTrue($found);
2457         // Test with get_updates_since the same data.
2458         $result = core_course_external::get_updates_since($course->id, $since);
2459         $result = external_api::clean_returnvalue(core_course_external::get_updates_since_returns(), $result);
2460         $this->assertCount(1, $result['instances']);
2461         $this->assertCount(0, $result['warnings']);
2462         $found = false;
2463         $this->assertCount(1, $result['instances']);
2464         $this->assertCount(0, $result['warnings']);
2465         foreach ($result['instances'] as $module) {
2466             foreach ($module['updates'] as $update) {
2467                 if ($module['id'] == $modules['forum']['cm']->id and $update['name'] == 'configuration') {
2468                     $found = true;
2469                 }
2470             }
2471         }
2472         $this->assertTrue($found);
2474         // Do not retrieve the configuration field.
2475         $filter = array('files');
2476         $found = false;
2477         $result = core_course_external::check_updates($course->id, $params, $filter);
2478         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2479         $this->assertCount(0, $result['instances']);
2480         $this->assertCount(0, $result['warnings']);
2481         $this->assertFalse($found);
2483         // Add invalid cmid.
2484         $params[] = array(
2485             'contextlevel' => 'module',
2486             'id' => -2,
2487             'since' => $since
2488         );
2489         $result = core_course_external::check_updates($course->id, $params);
2490         $result = external_api::clean_returnvalue(core_course_external::check_updates_returns(), $result);
2491         $this->assertCount(1, $result['warnings']);
2492         $this->assertEquals(-2, $result['warnings'][0]['itemid']);
2493     }
2495     /**
2496      * Test cases for the get_enrolled_courses_by_timeline_classification test.
2497      */
2498     public function get_get_enrolled_courses_by_timeline_classification_test_cases() {
2499         $now = time();
2500         $day = 86400;
2502         $coursedata = [
2503             [
2504                 'shortname' => 'apast',
2505                 'startdate' => $now - ($day * 2),
2506                 'enddate' => $now - $day
2507             ],
2508             [
2509                 'shortname' => 'bpast',
2510                 'startdate' => $now - ($day * 2),
2511                 'enddate' => $now - $day
2512             ],
2513             [
2514                 'shortname' => 'cpast',
2515                 'startdate' => $now - ($day * 2),
2516                 'enddate' => $now - $day
2517             ],
2518             [
2519                 'shortname' => 'dpast',
2520                 'startdate' => $now - ($day * 2),
2521                 'enddate' => $now - $day
2522             ],
2523             [
2524                 'shortname' => 'epast',
2525                 'startdate' => $now - ($day * 2),
2526                 'enddate' => $now - $day
2527             ],
2528             [
2529                 'shortname' => 'ainprogress',
2530                 'startdate' => $now - $day,
2531                 'enddate' => $now + $day
2532             ],
2533             [
2534                 'shortname' => 'binprogress',
2535                 'startdate' => $now - $day,
2536                 'enddate' => $now + $day
2537             ],
2538             [
2539                 'shortname' => 'cinprogress',
2540                 'startdate' => $now - $day,
2541                 'enddate' => $now + $day
2542             ],
2543             [
2544                 'shortname' => 'dinprogress',
2545                 'startdate' => $now - $day,
2546                 'enddate' => $now + $day
2547             ],
2548             [
2549                 'shortname' => 'einprogress',
2550                 'startdate' => $now - $day,
2551                 'enddate' => $now + $day
2552             ],
2553             [
2554                 'shortname' => 'afuture',
2555                 'startdate' => $now + $day
2556             ],
2557             [
2558                 'shortname' => 'bfuture',
2559                 'startdate' => $now + $day
2560             ],
2561             [
2562                 'shortname' => 'cfuture',
2563                 'startdate' => $now + $day
2564             ],
2565             [
2566                 'shortname' => 'dfuture',
2567                 'startdate' => $now + $day
2568             ],
2569             [
2570                 'shortname' => 'efuture',
2571                 'startdate' => $now + $day
2572             ]
2573         ];
2575         // Raw enrolled courses result set should be returned in this order:
2576         // afuture, ainprogress, apast, bfuture, binprogress, bpast, cfuture, cinprogress, cpast,
2577         // dfuture, dinprogress, dpast, efuture, einprogress, epast
2578         //
2579         // By classification the offset values for each record should be:
2580         // COURSE_TIMELINE_FUTURE
2581         // 0 (afuture), 3 (bfuture), 6 (cfuture), 9 (dfuture), 12 (efuture)
2582         // COURSE_TIMELINE_INPROGRESS
2583         // 1 (ainprogress), 4 (binprogress), 7 (cinprogress), 10 (dinprogress), 13 (einprogress)
2584         // COURSE_TIMELINE_PAST
2585         // 2 (apast), 5 (bpast), 8 (cpast), 11 (dpast), 14 (epast).
2586         //
2587         // NOTE: The offset applies to the unfiltered full set of courses before the classification
2588         // filtering is done.
2589         // E.g. In our example if an offset of 2 is given then it would mean the first
2590         // two courses (afuture, ainprogress) are ignored.
2591         return [
2592             'empty set' => [
2593                 'coursedata' => [],
2594                 'classification' => 'future',
2595                 'limit' => 2,
2596                 'offset' => 0,
2597                 'expectedcourses' => [],
2598                 'expectednextoffset' => 0
2599             ],
2600             // COURSE_TIMELINE_FUTURE.
2601             'future not limit no offset' => [
2602                 'coursedata' => $coursedata,
2603                 'classification' => 'future',
2604                 'limit' => 0,
2605                 'offset' => 0,
2606                 'expectedcourses' => ['afuture', 'bfuture', 'cfuture', 'dfuture', 'efuture'],
2607                 'expectednextoffset' => 15
2608             ],
2609             'future no offset' => [
2610                 'coursedata' => $coursedata,
2611                 'classification' => 'future',
2612                 'limit' => 2,
2613                 'offset' => 0,
2614                 'expectedcourses' => ['afuture', 'bfuture'],
2615                 'expectednextoffset' => 4
2616             ],
2617             'future offset' => [
2618                 'coursedata' => $coursedata,
2619                 'classification' => 'future',
2620                 'limit' => 2,
2621                 'offset' => 2,
2622                 'expectedcourses' => ['bfuture', 'cfuture'],
2623                 'expectednextoffset' => 7
2624             ],
2625             'future exact limit' => [
2626                 'coursedata' => $coursedata,
2627                 'classification' => 'future',
2628                 'limit' => 5,
2629                 'offset' => 0,
2630                 'expectedcourses' => ['afuture', 'bfuture', 'cfuture', 'dfuture', 'efuture'],
2631                 'expectednextoffset' => 13
2632             ],
2633             'future limit less results' => [
2634                 'coursedata' => $coursedata,
2635                 'classification' => 'future',
2636                 'limit' => 10,
2637                 'offset' => 0,
2638                 'expectedcourses' => ['afuture', 'bfuture', 'cfuture', 'dfuture', 'efuture'],
2639                 'expectednextoffset' => 15
2640             ],
2641             'future limit less results with offset' => [
2642                 'coursedata' => $coursedata,
2643                 'classification' => 'future',
2644                 'limit' => 10,
2645                 'offset' => 5,
2646                 'expectedcourses' => ['cfuture', 'dfuture', 'efuture'],
2647                 'expectednextoffset' => 15
2648             ],
2649             'all no limit or offset' => [
2650                 'coursedata' => $coursedata,
2651                 'classification' => 'all',
2652                 'limit' => 0,
2653                 'offset' => 0,
2654                 'expectedcourses' => [
2655                     'afuture',
2656                     'ainprogress',
2657                     'apast',
2658                     'bfuture',
2659                     'binprogress',
2660                     'bpast',
2661                     'cfuture',
2662                     'cinprogress',
2663                     'cpast',
2664                     'dfuture',
2665                     'dinprogress',
2666                     'dpast',
2667                     'efuture',
2668                     'einprogress',
2669                     'epast'
2670                 ],
2671                 'expectednextoffset' => 15
2672             ],
2673             'all limit no offset' => [
2674                 'coursedata' => $coursedata,
2675                 'classification' => 'all',
2676                 'limit' => 5,
2677                 'offset' => 0,
2678                 'expectedcourses' => [
2679                     'afuture',
2680                     'ainprogress',
2681                     'apast',
2682                     'bfuture',
2683                     'binprogress'
2684                 ],
2685                 'expectednextoffset' => 5
2686             ],
2687             'all limit and offset' => [
2688                 'coursedata' => $coursedata,
2689                 'classification' => 'all',
2690                 'limit' => 5,
2691                 'offset' => 5,
2692                 'expectedcourses' => [
2693                     'bpast',
2694                     'cfuture',
2695                     'cinprogress',
2696                     'cpast',
2697                     'dfuture'
2698                 ],
2699                 'expectednextoffset' => 10
2700             ],
2701             'all offset past result set' => [
2702                 'coursedata' => $coursedata,
2703                 'classification' => 'all',
2704                 'limit' => 5,
2705                 'offset' => 50,
2706                 'expectedcourses' => [],
2707                 'expectednextoffset' => 50
2708             ],
2709         ];
2710     }
2712     /**
2713      * Test the get_enrolled_courses_by_timeline_classification function.
2714      *
2715      * @dataProvider get_get_enrolled_courses_by_timeline_classification_test_cases()
2716      * @param array $coursedata Courses to create
2717      * @param string $classification Timeline classification
2718      * @param int $limit Maximum number of results
2719      * @param int $offset Offset the unfiltered courses result set by this amount
2720      * @param array $expectedcourses Expected courses in result
2721      * @param int $expectednextoffset Expected next offset value in result
2722      */
2723     public function test_get_enrolled_courses_by_timeline_classification(
2724         $coursedata,
2725         $classification,
2726         $limit,
2727         $offset,
2728         $expectedcourses,
2729         $expectednextoffset
2730     ) {
2731         $this->resetAfterTest();
2732         $generator = $this->getDataGenerator();
2734         $courses = array_map(function($coursedata) use ($generator) {
2735             return $generator->create_course($coursedata);
2736         }, $coursedata);
2738         $student = $generator->create_user();
2740         foreach ($courses as $course) {
2741             $generator->enrol_user($student->id, $course->id, 'student');
2742         }
2744         $this->setUser($student);
2746         // NOTE: The offset applies to the unfiltered full set of courses before the classification
2747         // filtering is done.
2748         // E.g. In our example if an offset of 2 is given then it would mean the first
2749         // two courses (afuture, ainprogress) are ignored.
2750         $result = core_course_external::get_enrolled_courses_by_timeline_classification(
2751             $classification,
2752             $limit,
2753             $offset,
2754             'shortname ASC'
2755         );
2756         $result = external_api::clean_returnvalue(
2757             core_course_external::get_enrolled_courses_by_timeline_classification_returns(),
2758             $result
2759         );
2761         $actual = array_map(function($course) {
2762             return $course['shortname'];
2763         }, $result['courses']);
2765         $this->assertEquals($expectedcourses, $actual);
2766         $this->assertEquals($expectednextoffset, $result['nextoffset']);
2767     }
2769     /**
2770      * Test the get_recent_courses function.
2771      */
2772     public function test_get_recent_courses() {
2773         global $USER, $DB;
2775         $this->resetAfterTest();
2776         $generator = $this->getDataGenerator();
2778         set_config('hiddenuserfields', 'lastaccess');
2780         $courses = array();
2781         for ($i = 1; $i < 12; $i++) {
2782             $courses[]  = $generator->create_course();
2783         };
2785         $student = $generator->create_user();
2786         $teacher = $generator->create_user();
2788         foreach ($courses as $course) {
2789             $generator->enrol_user($student->id, $course->id, 'student');
2790         }
2792         $generator->enrol_user($teacher->id, $courses[0]->id, 'teacher');
2794         $this->setUser($student);
2796         $result = core_course_external::get_recent_courses($USER->id);
2798         // No course accessed.
2799         $this->assertCount(0, $result);
2801         foreach ($courses as $course) {
2802             core_course_external::view_course($course->id);
2803         }
2805         // Every course accessed.
2806         $result = core_course_external::get_recent_courses($USER->id);
2807         $this->assertCount( 11, $result);
2809         // Every course accessed, result limited to 10 courses.
2810         $result = core_course_external::get_recent_courses($USER->id, 10);
2811         $this->assertCount(10, $result);
2813         $guestcourse = $generator->create_course(
2814                 (object)array('shortname' => 'guestcourse',
2815                 'enrol_guest_status_0' => ENROL_INSTANCE_ENABLED,
2816                 'enrol_guest_password_0' => ''));
2817         core_course_external::view_course($guestcourse->id);
2819         // Every course accessed, even the not enrolled one.
2820         $result = core_course_external::get_recent_courses($USER->id);
2821         $this->assertCount(12, $result);
2823         // Offset 5, return 7 out of 12.
2824         $result = core_course_external::get_recent_courses($USER->id, 0, 5);
2825         $this->assertCount(7, $result);
2827         // Offset 5 and limit 3, return 3 out of 12.
2828         $result = core_course_external::get_recent_courses($USER->id, 3, 5);
2829         $this->assertCount(3, $result);
2831         // Sorted by course id ASC.
2832         $result = core_course_external::get_recent_courses($USER->id, 0, 0, 'id ASC');
2833         $this->assertEquals($courses[0]->id, array_shift($result)->id);
2835         // Sorted by course id DESC.
2836         $result = core_course_external::get_recent_courses($USER->id, 0, 0, 'id DESC');
2837         $this->assertEquals($guestcourse->id, array_shift($result)->id);
2839         // If last access is hidden, only get the courses where has viewhiddenuserfields capability.
2840         $this->setUser($teacher);
2841         $teacherroleid = $DB->get_field('role', 'id', array('shortname' => 'editingteacher'));
2842         $usercontext = context_user::instance($student->id);
2843         $this->assignUserCapability('moodle/user:viewdetails', $usercontext, $teacherroleid);
2845         // Sorted by course id DESC.
2846         $result = core_course_external::get_recent_courses($student->id);
2847         $this->assertCount(1, $result);
2848         $this->assertEquals($courses[0]->id, array_shift($result)->id);
2849     }